import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Switch,
  Table,
  Typography,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { dictionaryApi } from '@/lib/api'
import type { Dictionary, DictionaryDetail } from '@/types/system'

export function DictionaryManagementPage() {
  const [dictForm] = Form.useForm()
  const [detailForm] = Form.useForm()
  const [dictionaries, setDictionaries] = useState<Dictionary[]>([])
  const [activeDictionary, setActiveDictionary] = useState<Dictionary | null>(null)
  const [details, setDetails] = useState<DictionaryDetail[]>([])
  const [loading, setLoading] = useState(false)
  const [dictModalOpen, setDictModalOpen] = useState(false)
  const [detailModalOpen, setDetailModalOpen] = useState(false)
  const [editingDictionary, setEditingDictionary] = useState<Dictionary | null>(null)
  const [editingDetail, setEditingDetail] = useState<DictionaryDetail | null>(null)

  const reloadDictionaries = useCallback(async () => {
    setLoading(true)
    try {
      const response = await dictionaryApi.getDictionaryList()
      const list = response.data
      setDictionaries(list)
      if (!activeDictionary && list.length) {
        setActiveDictionary(list[0])
      }
    } finally {
      setLoading(false)
    }
  }, [activeDictionary])

  const reloadDetails = useCallback(async (dictionary?: Dictionary | null) => {
    const target = dictionary || activeDictionary
    if (!target) {
      setDetails([])
      return
    }

    const response = await dictionaryApi.getDictionaryTree(target.ID)
    setDetails(response.data.list)
  }, [activeDictionary])

  useEffect(() => {
    reloadDictionaries()
  }, [reloadDictionaries])

  useEffect(() => {
    reloadDetails(activeDictionary)
  }, [activeDictionary, reloadDetails])

  const openCreateDictionary = () => {
    setEditingDictionary(null)
    dictForm.resetFields()
    dictForm.setFieldsValue({ status: true })
    setDictModalOpen(true)
  }

  const openEditDictionary = (record: Dictionary) => {
    setEditingDictionary(record)
    dictForm.setFieldsValue({
      name: record.name,
      type: record.type,
      desc: record.desc,
      status: record.status ?? true,
      parentID: record.parentID,
    })
    setDictModalOpen(true)
  }

  const saveDictionary = async () => {
    const values = await dictForm.validateFields()
    const payload = {
      ID: editingDictionary?.ID,
      ...values,
    }

    if (editingDictionary) {
      await dictionaryApi.updateDictionary(payload)
      message.success('字典已更新')
    } else {
      await dictionaryApi.createDictionary(payload)
      message.success('字典已创建')
    }
    setDictModalOpen(false)
    reloadDictionaries()
  }

  const deleteDictionary = (record: Dictionary) => {
    Modal.confirm({
      title: `删除字典 ${record.name}`,
      okButtonProps: { danger: true },
      onOk: async () => {
        await dictionaryApi.deleteDictionary({ ID: record.ID })
        message.success('字典已删除')
        if (activeDictionary?.ID === record.ID) {
          setActiveDictionary(null)
        }
        reloadDictionaries()
      },
    })
  }

  const openCreateDetail = () => {
    if (!activeDictionary) {
      message.warning('请先选择字典')
      return
    }
    setEditingDetail(null)
    detailForm.resetFields()
    detailForm.setFieldsValue({
      sysDictionaryID: activeDictionary.ID,
      status: true,
      sort: 1,
    })
    setDetailModalOpen(true)
  }

  const openEditDetail = (record: DictionaryDetail) => {
    setEditingDetail(record)
    detailForm.setFieldsValue({
      label: record.label,
      value: record.value,
      extend: record.extend,
      status: record.status ?? true,
      sort: record.sort,
      parentID: record.parentID,
    })
    setDetailModalOpen(true)
  }

  const saveDetail = async () => {
    if (!activeDictionary) {
      return
    }
    const values = await detailForm.validateFields()
    const payload = {
      ID: editingDetail?.ID,
      sysDictionaryID: activeDictionary.ID,
      ...values,
    }
    if (editingDetail) {
      await dictionaryApi.updateDictionaryDetail(payload)
      message.success('字典项已更新')
    } else {
      await dictionaryApi.createDictionaryDetail(payload)
      message.success('字典项已创建')
    }
    setDetailModalOpen(false)
    reloadDetails()
  }

  const deleteDetail = (record: DictionaryDetail) => {
    Modal.confirm({
      title: `删除字典项 ${record.label}`,
      okButtonProps: { danger: true },
      onOk: async () => {
        await dictionaryApi.deleteDictionaryDetail({ ID: record.ID })
        message.success('字典项已删除')
        reloadDetails()
      },
    })
  }

  const detailColumns: ColumnsType<DictionaryDetail> = [
    { title: '展示值', dataIndex: 'label', width: 180 },
    { title: '字典值', dataIndex: 'value', width: 180 },
    { title: '扩展值', dataIndex: 'extend', width: 180 },
    { title: '排序', dataIndex: 'sort', width: 80 },
    {
      title: '状态',
      width: 100,
      render: (_, record) => (record.status ? '启用' : '停用'),
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => openEditDetail(record)}>
            编辑
          </Button>
          <Button danger type="link" onClick={() => deleteDetail(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              字典管理
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              当前页覆盖字典主表和树形字典项管理。
            </Typography.Paragraph>
          </div>
          <Space>
            <Button onClick={openCreateDetail} disabled={!activeDictionary}>
              新建字典项
            </Button>
            <Button type="primary" onClick={openCreateDictionary}>
              新建字典
            </Button>
          </Space>
        </div>
        <Row gutter={20}>
          <Col xs={24} xl={8}>
            <Card title="字典列表" bordered={false}>
              <Space direction="vertical" style={{ width: '100%' }}>
                {dictionaries.map((item) => (
                  <Card
                    key={item.ID}
                    size="small"
                    hoverable
                    onClick={() => setActiveDictionary(item)}
                    style={{
                      borderColor: activeDictionary?.ID === item.ID ? '#d16f3f' : undefined,
                    }}
                    extra={
                      <Space size={4}>
                        <Button type="link" size="small" onClick={(event) => { event.stopPropagation(); openEditDictionary(item) }}>
                          编辑
                        </Button>
                        <Button danger type="link" size="small" onClick={(event) => { event.stopPropagation(); deleteDictionary(item) }}>
                          删除
                        </Button>
                      </Space>
                    }
                  >
                    <Typography.Text strong>{item.name}</Typography.Text>
                    <div className="text-muted">{item.type}</div>
                  </Card>
                ))}
              </Space>
            </Card>
          </Col>
          <Col xs={24} xl={16}>
            <Card
              title={activeDictionary ? `字典项 · ${activeDictionary.name}` : '字典项'}
              bordered={false}
              loading={loading}
            >
              <Table
                rowKey="ID"
                columns={detailColumns}
                dataSource={details}
                pagination={false}
                expandable={{ defaultExpandAllRows: true }}
              />
            </Card>
          </Col>
        </Row>
      </Card>

      <Modal
        open={dictModalOpen}
        title={editingDictionary ? '编辑字典' : '新建字典'}
        onCancel={() => setDictModalOpen(false)}
        onOk={saveDictionary}
      >
        <Form form={dictForm} layout="vertical">
          <Form.Item name="parentID" label="父级字典">
            <Select allowClear options={dictionaries.map((item) => ({ label: `${item.name} (${item.type})`, value: item.ID }))} />
          </Form.Item>
          <Form.Item name="name" label="字典名（中）" rules={[{ required: true, message: '请输入字典名' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="type" label="字典名（英）" rules={[{ required: true, message: '请输入字典类型' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="desc" label="描述">
            <Input />
          </Form.Item>
          <Form.Item name="status" label="启用" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        open={detailModalOpen}
        title={editingDetail ? '编辑字典项' : '新建字典项'}
        onCancel={() => setDetailModalOpen(false)}
        onOk={saveDetail}
      >
        <Form form={detailForm} layout="vertical">
          <Form.Item name="parentID" label="父级字典项">
            <Select
              allowClear
              options={details.map((item) => ({ label: item.label, value: item.ID }))}
            />
          </Form.Item>
          <Form.Item name="label" label="展示值" rules={[{ required: true, message: '请输入展示值' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="value" label="字典值" rules={[{ required: true, message: '请输入字典值' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="extend" label="扩展值">
            <Input />
          </Form.Item>
          <Form.Item name="sort" label="排序">
            <InputNumber style={{ width: '100%' }} min={0} />
          </Form.Item>
          <Form.Item name="status" label="启用" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
