import React, { useState, useEffect, useRef } from 'react';
import {
  Table,
  Button,
  Space,
  Input,
  Drawer,
  Form,
  Switch,
  InputNumber,
  Popconfirm,
  message,
  TreeSelect,
  Tag,
} from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  getDictionaryDetailList,
  createDictionaryDetail,
  updateDictionaryDetail,
  deleteDictionaryDetail,
  findDictionaryDetail,
} from '@/services/kratos/dictionaryDetail';

interface DictionaryDetailItem {
  ID: number;
  label: string;
  value: string;
  extend?: string;
  status: boolean;
  sort: number;
  parentID?: number;
  level?: number;
  children?: DictionaryDetailItem[];
  sysDictionaryID: number;
}

interface DictionaryDetailProps {
  sysDictionaryID: number;
}

const DictionaryDetail: React.FC<DictionaryDetailProps> = ({ sysDictionaryID }) => {
  const [treeData, setTreeData] = useState<DictionaryDetailItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchName, setSearchName] = useState('');
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editType, setEditType] = useState<'create' | 'update'>('create');
  const [currentRecord, setCurrentRecord] = useState<DictionaryDetailItem | null>(null);
  const [form] = Form.useForm();

  // 获取树形数据
  const fetchTreeData = async () => {
    if (!sysDictionaryID) return;
    setLoading(true);
    try {
      const res = await getDictionaryDetailList({
        sysDictionaryID,
        label: searchName.trim(),
      });
      if (res.code === 0) {
        setTreeData(res.data?.list || []);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTreeData();
  }, [sysDictionaryID]);

  // 搜索
  const handleSearch = () => {
    fetchTreeData();
  };

  // 打开新增抽屉
  const handleAdd = () => {
    setEditType('create');
    setCurrentRecord(null);
    form.resetFields();
    form.setFieldsValue({
      status: true,
      sort: 0,
      sysDictionaryID,
    });
    setDrawerVisible(true);
  };

  // 添加子项
  const handleAddChild = (parentRecord: DictionaryDetailItem) => {
    setEditType('create');
    setCurrentRecord(null);
    form.resetFields();
    form.setFieldsValue({
      status: true,
      sort: 0,
      parentID: parentRecord.ID,
      sysDictionaryID,
    });
    setDrawerVisible(true);
  };

  // 打开编辑抽屉
  const handleEdit = async (record: DictionaryDetailItem) => {
    setEditType('update');
    try {
      const res = await findDictionaryDetail({ ID: record.ID });
      if (res.code === 0) {
        setCurrentRecord(res.data.reSysDictionaryDetail);
        form.setFieldsValue(res.data.reSysDictionaryDetail);
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  // 删除
  const handleDelete = async (record: DictionaryDetailItem) => {
    try {
      const res = await deleteDictionaryDetail({ ID: record.ID });
      if (res.code === 0) {
        message.success('删除成功');
        fetchTreeData();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 关闭抽屉
  const handleCloseDrawer = () => {
    setDrawerVisible(false);
    form.resetFields();
    setCurrentRecord(null);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const submitData = {
        ...values,
        sysDictionaryID,
      };
      let res;
      if (editType === 'create') {
        res = await createDictionaryDetail(submitData);
      } else {
        res = await updateDictionaryDetail({ ...currentRecord, ...submitData });
      }
      if (res.code === 0) {
        message.success(editType === 'create' ? '创建成功' : '更新成功');
        handleCloseDrawer();
        fetchTreeData();
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 构建树形选择数据
  const buildTreeSelectData = (data: DictionaryDetailItem[]): any[] => {
    return data.map((item) => ({
      title: item.label,
      value: item.ID,
      children: item.children ? buildTreeSelectData(item.children) : undefined,
    }));
  };

  const columns: ColumnsType<DictionaryDetailItem> = [
    {
      title: '展示值',
      dataIndex: 'label',
      key: 'label',
      width: 150,
    },
    {
      title: '字典值',
      dataIndex: 'value',
      key: 'value',
      width: 120,
    },
    {
      title: '扩展值',
      dataIndex: 'extend',
      key: 'extend',
      width: 120,
    },
    {
      title: '层级',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      render: (level) => level || 1,
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status ? 'success' : 'default'}>{status ? '启用' : '停用'}</Tag>
      ),
    },
    {
      title: '排序标记',
      dataIndex: 'sort',
      key: 'sort',
      width: 100,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<PlusOutlined />} onClick={() => handleAddChild(record)}>
            添加子项
          </Button>
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            变更
          </Button>
          <Popconfirm title="确定要删除吗？" onConfirm={() => handleDelete(record)}>
            <Button type="link" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <Input
          placeholder="搜索展示值"
          value={searchName}
          onChange={(e) => setSearchName(e.target.value)}
          onPressEnter={handleSearch}
          suffix={<SearchOutlined onClick={handleSearch} />}
          style={{ width: 250 }}
          allowClear
          onClear={() => {
            setSearchName('');
            fetchTreeData();
          }}
        />
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增字典项
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={treeData}
        loading={loading}
        rowKey="ID"
        pagination={false}
        scroll={{ x: 900 }}
        expandable={{
          defaultExpandAllRows: true,
          childrenColumnName: 'children',
        }}
      />

      <Drawer
        title={editType === 'create' ? '添加字典项' : '修改字典项'}
        open={drawerVisible}
        onClose={handleCloseDrawer}
        width={500}
        extra={
          <Space>
            <Button onClick={handleCloseDrawer}>取消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item label="父级字典项" name="parentID">
            <TreeSelect
              placeholder="请选择父级字典项（可选）"
              allowClear
              showSearch
              treeDefaultExpandAll
              treeData={[
                { title: '无父级（根级）', value: null },
                ...buildTreeSelectData(treeData),
              ]}
              filterTreeNode={(input, node) =>
                (node?.title as string)?.toLowerCase().includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item
            label="展示值"
            name="label"
            rules={[{ required: true, message: '请输入展示值' }]}
          >
            <Input placeholder="请输入展示值" />
          </Form.Item>
          <Form.Item
            label="字典值"
            name="value"
            rules={[{ required: true, message: '请输入字典值' }]}
          >
            <Input placeholder="请输入字典值" />
          </Form.Item>
          <Form.Item label="扩展值" name="extend">
            <Input placeholder="请输入扩展值" />
          </Form.Item>
          <Form.Item label="启用状态" name="status" valuePropName="checked">
            <Switch checkedChildren="开启" unCheckedChildren="停用" />
          </Form.Item>
          <Form.Item
            label="排序标记"
            name="sort"
            rules={[{ required: true, message: '请输入排序标记' }]}
          >
            <InputNumber placeholder="排序标记" style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default DictionaryDetail;
