import { useEffect, useState } from 'react'
import {
  Drawer, Form, Input, Select, Checkbox, Button, message, Table
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { getStaffs, getPermissionGroups, createUser, updateUser, StaffVO, PermissionGroupVO, UserCreateReq, UserUpdateReq } from '../../api/usr'

interface InitialData {
  userType: string
  language: string
  canEditDoc: boolean
  isDisabled: boolean
  employeeId?: string | null
}

interface Props {
  open: boolean
  onClose: () => void
  onSuccess: () => void
  userId?: string
  initialData?: InitialData
}

export default function UserFormDrawer({ open, onClose, onSuccess, userId, initialData }: Props) {
  const [form] = Form.useForm()
  const [staffs, setStaffs] = useState<StaffVO[]>([])
  const [permGroups, setPermGroups] = useState<PermissionGroupVO[]>([])
  const [selectedPermIds, setSelectedPermIds] = useState<string[]>([])
  const [submitting, setSubmitting] = useState(false)

  const isEditMode = !!userId

  useEffect(() => {
    if (open) {
      getStaffs().then(setStaffs).catch(() => {})
      getPermissionGroups().then(setPermGroups).catch(() => {})
      if (isEditMode && initialData) {
        form.setFieldsValue({
          userType: initialData.userType,
          language: initialData.language,
          canEditDoc: initialData.canEditDoc,
          isDisabled: initialData.isDisabled,
          employeeId: initialData.employeeId ?? null,
        })
        setSelectedPermIds([])
      } else {
        form.resetFields()
        setSelectedPermIds([])
      }
    }
  }, [open])

  const permColumns: ColumnsType<PermissionGroupVO> = [
    {
      title: '',
      key: 'select',
      width: 40,
      render: (_, record) => (
        <Checkbox
          checked={selectedPermIds.includes(record.sId)}
          onChange={e => {
            setSelectedPermIds(prev =>
              e.target.checked ? [...prev, record.sId] : prev.filter(id => id !== record.sId)
            )
          }}
        />
      )
    },
    { title: '权限组', dataIndex: 'sGroupName' },
    { title: '分类', dataIndex: 'sCategory' }
  ]

  async function handleSubmit() {
    try {
      const values = await form.validateFields()
      setSubmitting(true)
      if (isEditMode) {
        const req: UserUpdateReq = {
          userType: values.userType,
          language: values.language,
          canEditDoc: values.canEditDoc ?? false,
          isDisabled: values.isDisabled ?? false,
          employeeId: values.employeeId ?? null,
          permGroupIds: selectedPermIds
        }
        await updateUser(userId, req)
        message.success('修改用户成功')
      } else {
        const req: UserCreateReq = {
          userCode: values.userCode,
          username: values.username,
          userType: values.userType,
          language: values.language,
          canEditDoc: values.canEditDoc ?? false,
          employeeId: values.employeeId ?? null,
          permGroupIds: selectedPermIds
        }
        await createUser(req)
        message.success('新增用户成功')
      }
      form.resetFields()
      setSelectedPermIds([])
      onSuccess()
    } catch (e: unknown) {
      if (e instanceof Error) {
        message.error(e.message)
      }
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Drawer
      title={isEditMode ? '修改用户' : '新增用户'}
      open={open}
      onClose={onClose}
      width={520}
      footer={
        <div style={{ textAlign: 'right' }}>
          <Button onClick={onClose} style={{ marginRight: 8 }}>取消</Button>
          <Button type="primary" onClick={handleSubmit} loading={submitting}>确认</Button>
        </div>
      }
    >
      <Form form={form} layout="vertical">
        {!isEditMode && (
          <>
            <Form.Item name="userCode" label="用户号" rules={[{ required: true, message: '请输入用户号' }]}>
              <Input placeholder="请输入用户号" />
            </Form.Item>
            <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
              <Input placeholder="请输入用户名" />
            </Form.Item>
          </>
        )}
        <Form.Item name="userType" label="用户类型" rules={[{ required: true }]} initialValue="普通用户">
          <Select options={[{ value: '普通用户', label: '普通用户' }, { value: '超级管理员', label: '超级管理员' }]} />
        </Form.Item>
        <Form.Item name="language" label="语言" rules={[{ required: true }]} initialValue="中文">
          <Select options={[{ value: '中文', label: '中文' }, { value: '英文', label: 'English' }, { value: '繁体', label: '繁體' }]} />
        </Form.Item>
        <Form.Item name="canEditDoc" valuePropName="checked">
          <Checkbox>可编辑文档</Checkbox>
        </Form.Item>
        {isEditMode && (
          <Form.Item name="isDisabled" valuePropName="checked">
            <Checkbox>作废</Checkbox>
          </Form.Item>
        )}
        <Form.Item name="employeeId" label="关联员工">
          <Select
            allowClear
            placeholder="选择员工（可选）"
            options={staffs.map(s => ({ value: s.sId, label: s.sStaffName }))}
          />
        </Form.Item>
        <Form.Item label="权限组">
          <Table
            size="small"
            columns={permColumns}
            dataSource={permGroups}
            rowKey="sId"
            pagination={false}
          />
        </Form.Item>
      </Form>
    </Drawer>
  )
}
