'use client'
import React, { useEffect, useState } from 'react'
import { RiAddLine, RiCloseLine } from '@remixicon/react'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import { deptAddUsers, deptDelUsers, fetchIntent, fetchNoDeptUsers } from '@/service/common'
import 'react-multi-email/dist/style.css'
import cn from '@/utils/classnames'
import Confirm from '@/app/components/base/confirm'
import { Select as AntdSelect } from 'antd'

const UserModal = ({
  onCancel,
  onSend,
  transfer,
}: any) => {
  const [list, setList] = useState<any>([])
  const [total, setTotal] = useState(0)
  const handlePage = () => {
    fetchIntent({
      url: `/dept/dept-accounts/${transfer.row.dept_id}`,
      params: {},
    }).then((res: any) => {
      setList(res.data)
      setTotal(res.data.length)
    })
  }
  useEffect(() => {
    handlePage()
  }, [])
  const [showConfirmDelete, setShowConfirmDelete] = useState(false)
  const [row, setRow] = useState<any>({})
  const handleDel = async () => {
    try {
      const { result }: any = await deptDelUsers({
        url: '/dept/dept-accounts',
        body: { dept_id: transfer.row.dept_id, account_ids: [{ account_id: row.account_id }] },
      })
      if (result === 'success') {
        setShowConfirmDelete(false)
        handlePage()
      }
    }
    catch (e) { }
  }
  const [showDetail, setShowDetail] = useState(false)
  const [selectUser, setSelectUser] = useState<any>([])
  const [userOptions, setUserOptions] = useState<any>([])
  useEffect(() => {
    fetchNoDeptUsers({
      url: '/account/nodept',
      params: {},
    }).then((res: any) => {
      setUserOptions(res.data.map((v: any) => ({ label: v.email, value: v.account_id })) || [])
    })
  }, [])
  const handleSave = async () => {
    try {
      const { result }: any = await deptAddUsers({
        url: '/dept/dept-accounts',
        body: { dept_id: transfer.row.dept_id, account_ids: selectUser.map((v: any) => ({ account_id: v })) },
      })
      if (result === 'success') {
        setShowDetail(false)
        handlePage()
      }
    }
    catch (e) { }
  }
  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={() => {
                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>用户账号</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>{item.email}</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'>
                  <AntdSelect
                    className="w-full"
                    mode="multiple"
                    showSearch
                    placeholder="请选择用户"
                    optionFilterProp="label"
                    onChange={v => setSelectUser(v)}
                    options={userOptions}
                  />
                </div>
              </div>
              <Button
                tabIndex={0}
                className='w-full'
                onClick={handleSave}
                disabled={!selectUser.length}
                variant='primary'
              >
                保存
              </Button>
            </div>
          </Modal>
        )
      }
    </div>
  )
}

export default UserModal
