'use client'
import React, { useCallback, useEffect, useState } from 'react'
import { RiAddLine, RiCloseLine, RiRefreshLine, RiSearchLine } from '@remixicon/react'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import { delCorpus, fetchIntentType, fetchTypes } from '@/service/common'
import 'react-multi-email/dist/style.css'
import Input from '@/app/components/base/input'
import useSWR from 'swr'
import cn from '@/utils/classnames'
import Confirm from '@/app/components/base/confirm'
import Pagination from '@/app/components/base/pagination'
import { SimpleSelect } from '@/app/components/base/select'

const TypeModal = ({
  onCancel,
  onSend,
}: any) => {
  const [page, setPage] = React.useState<number>(0)
  const [limit, setLimit] = useState<number>(10)
  const [name, setName] = useState('')
  const [query, setQuery] = useState<any>({})
  const { data, mutate }: any = useSWR(
    {
      url: '/xxx',
      params: {
        page: page + 1,
        limit,
        ...query,
      },
    },
    fetchIntentType,
  )
  const list: any = data?.data || []
  const total = data?.total || 0
  const handleSearch = (reset = false) => {
    if (reset)
      setIntentType('')

    const params: any = {}
    if (intentType)
      params.intentType = intentType
    setQuery(params)
    setPage(0)
  }
  useEffect(() => {
    mutate()
  }, [page, limit])
  const [showConfirmDelete, setShowConfirmDelete] = useState(false)
  const [row, setRow] = useState<any>({})
  const handleDel = async () => {
    try {
      await delCorpus({
        url: `/tags/${row.id}`,
        body: {},
      })
      setShowConfirmDelete(false)
    }
    catch (e) { }
  }
  const [showDetail, setShowDetail] = useState(false)
  const [mode, setMode] = useState<any>('add')
  const [editIntentType, setEditIntentType] = useState('')
  const [selectUser, setSelectUser] = useState<any>('')
  const [userOptions, setUserOptions] = useState<any>([])
  useEffect(() => {
    fetchTypes({
      url: '/tags/page',
      params: {
        page: 1,
        limit: 1000,
        tag_type: 'knowledge_category',
      },
    }).then((res: any) => {
      setUserOptions(res.data.map((v: any) => ({ name: v.name, value: v.id })) || [])
    })
  }, [])
  const handleSave = useCallback(async () => {
    // try {
    //   let res
    //   if (transfer.mode === 'add') {
    //     res = await addCorpus({
    //       url: '/xxx',
    //       body: { name, type: 'knowledge_category' },
    //     })
    //   }
    //   else {
    //     res = await editCorpus({
    //       url: '/xxx',
    //       body: { name },
    //     })
    //   }
    //   const { id }: any = res
    //   if (id) {
    //     onCancel()
    //     onSend()
    //   }
    // }
    // catch (e) { }
  }, [mode, editIntentType, onCancel, onSend])
  return (
    <div>
      <Modal overflowVisible isShow onClose={() => { }} className="p-[24px 32px] w-[800px] max-w-[800px]">
        <div className='mb-2 flex justify-between'>
          <div className='text-xl font-semibold text-text-primary'>关联用户</div>
          <RiCloseLine className='h-4 w-4 cursor-pointer text-text-tertiary' onClick={onCancel} />
        </div>
        <div className='flex h-[600px] flex-col'>
          <div className="flex items-center gap-2">
            <div className="flex shrink-0 items-center text-gray-500">
              用户名称
              <Input
                className="ml-2"
                showClearIcon
                wrapperClassName='!w-[200px]'
                value={name}
                onChange={e => setName(e.target.value)}
                onClear={() => setName('')}
              />
            </div>
            <Button variant='primary' className={cn('ml-auto shrink-0')} onClick={() => {
              handleSearch(false)
            }}>
              <RiSearchLine className='mr-1 h-4 w-4' />
              搜索
            </Button>
            <Button variant='primary' className={cn('shrink-0')} onClick={() => {
              handleSearch(true)
            }}>
              <RiRefreshLine className='mr-1 h-4 w-4' />
              重置
            </Button>
          </div>
          <div className="mt-2">
            <Button variant='primary' className={cn('shrink-0')}
              onClick={() => {
                setMode('add')
                setEditIntentType('')
                setShowDetail(true)
              }}>
              <RiAddLine className='mr-1 h-4 w-4' />
              添加用户
            </Button>
          </div>
          <div className="flex-1">
            <div className='relative flex h-full w-full flex-col'>
              <div className='relative grow overflow-x-auto'>
                <table className={'mt-3 w-full min-w-[700px] max-w-full border-collapse border-0 text-sm'}>
                  <thead className="h-8 border-b border-divider-subtle text-xs font-medium uppercase leading-8 text-text-tertiary">
                    <tr>
                      <td>用户名称</td>
                      <td className="w-[120px] text-center">操作</td>
                    </tr>
                  </thead>
                  <tbody className="text-text-secondary">
                    {list.map((item: any) => (
                      <tr
                        key={item.id}
                        className={'h-8 border-b border-divider-subtle hover:bg-background-default-hover'}
                      >
                        <td>{item.name}</td>
                        <td className="flex justify-center gap-2">
                          <Button variant='ghost' size='small' className={cn('shrink-0 text-red-600')} onClick={() => {
                            setRow(item)
                            setShowConfirmDelete(true)
                          }}>
                            解除关联
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {/* Show Pagination only if the total is more than the limit */}
              {total && (
                <Pagination
                  total={total}
                  limit={limit}
                  onLimitChange={setLimit}
                  current={page}
                  onChange={setPage}
                  className='w-full shrink-0 px-0 pb-0'
                />
              )}
            </div>
          </div>
        </div>
      </Modal>
      {showConfirmDelete && (
        <Confirm
          title="删除确认"
          content={`请确认是否删除${row.name}？`}
          isShow={showConfirmDelete}
          onConfirm={handleDel}
          onCancel={() => setShowConfirmDelete(false)}
        />
      )}
      {
        showDetail && (
          <Modal overflowVisible isShow onClose={() => { }} className="p-[24px 32px] w-[400px]">
            <div className='mb-2 flex justify-between'>
              <div className='text-xl font-semibold text-text-primary'>添加用户</div>
              <RiCloseLine className='h-4 w-4 cursor-pointer text-text-tertiary' onClick={() => setShowDetail(false)} />
            </div>
            <div>
              <div className={cn('flex flex-wrap items-center justify-between py-4')}>
                <div className='shrink-0 py-2 text-sm font-medium leading-[20px] text-text-primary'>
                  选择用户
                </div>
                <div className='w-full'>
                  <SimpleSelect
                    defaultValue={selectUser}
                    onSelect={(i) => { setSelectUser(i.value) }}
                    items={userOptions}
                    allowSearch={false}
                  />
                </div>
              </div>
              <Button
                tabIndex={0}
                className='w-full'
                onClick={handleSave}
                disabled={!editIntentType.length}
                variant='primary'
              >
                保存
              </Button>
            </div>
          </Modal>
        )
      }
    </div>
  )
}

export default TypeModal
