import {
  Button,
  Card,
  Col,
  Drawer,
  Form,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Typography
} from "antd";
import { useEffect, useState } from "react";
import {
  createDictItem,
  createDictType,
  deleteDictItem,
  deleteDictType,
  fetchDictItems,
  fetchDictTypes,
  updateDictItem,
  updateDictType
} from "../api";
import { usePermission } from "../hooks/usePermission";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import type { SysDictItem, SysDictType } from "../types";

const { Title } = Typography;

export default function Dictionaries() {
  const { can } = usePermission();
  const [types, setTypes] = useState<SysDictType[]>([]);
  const [items, setItems] = useState<SysDictItem[]>([]);
  const [selectedType, setSelectedType] = useState<SysDictType | null>(null);
  const [loadingTypes, setLoadingTypes] = useState(false);
  const [loadingItems, setLoadingItems] = useState(false);

  // Type Drawer
  const [typeDrawerVisible, setTypeDrawerVisible] = useState(false);
  const [editingType, setEditingType] = useState<SysDictType | null>(null);
  const [typeForm] = Form.useForm();

  // Item Drawer
  const [itemDrawerVisible, setItemDrawerVisible] = useState(false);
  const [editingItem, setEditingItem] = useState<SysDictItem | null>(null);
  const [itemForm] = Form.useForm();

  const loadTypes = async () => {
    setLoadingTypes(true);
    try {
      const data = await fetchDictTypes();
      setTypes(data || []);
      if (data && data.length > 0 && !selectedType) {
        setSelectedType(data[0]);
      }
    } finally {
      setLoadingTypes(false);
    }
  };

  const loadItems = async (typeCode: string) => {
    setLoadingItems(true);
    try {
      const data = await fetchDictItems(typeCode);
      setItems(data || []);
    } finally {
      setLoadingItems(false);
    }
  };

  useEffect(() => {
    loadTypes();
  }, []);

  useEffect(() => {
    if (selectedType) {
      loadItems(selectedType.typeCode);
    } else {
      setItems([]);
    }
  }, [selectedType]);

  // Type Actions
  const handleAddType = () => {
    setEditingType(null);
    typeForm.resetFields();
    setTypeDrawerVisible(true);
  };

  const handleEditType = (record: SysDictType) => {
    setEditingType(record);
    typeForm.setFieldsValue(record);
    setTypeDrawerVisible(true);
  };

  const handleDeleteType = async (id: number) => {
    await deleteDictType(id);
    message.success("删除成功");
    loadTypes();
  };

  const handleTypeSubmit = async () => {
    const values = await typeForm.validateFields();
    if (editingType) {
      await updateDictType(editingType.dictTypeId, values);
    } else {
      await createDictType(values);
    }
    message.success(editingType ? "更新成功" : "创建成功");
    setTypeDrawerVisible(false);
    loadTypes();
  };

  // Item Actions
  const handleAddItem = () => {
    if (!selectedType) {
      message.warning("请先选择一个字典类型");
      return;
    }
    setEditingItem(null);
    itemForm.resetFields();
    itemForm.setFieldsValue({ typeCode: selectedType.typeCode, sortOrder: 0, status: 1 });
    setItemDrawerVisible(true);
  };

  const handleEditItem = (record: SysDictItem) => {
    setEditingItem(record);
    itemForm.setFieldsValue(record);
    setItemDrawerVisible(true);
  };

  const handleDeleteItem = async (id: number) => {
    await deleteDictItem(id);
    message.success("删除成功");
    if (selectedType) loadItems(selectedType.typeCode);
  };

  const handleItemSubmit = async () => {
    const values = await itemForm.validateFields();
    if (editingItem) {
      await updateDictItem(editingItem.dictItemId, values);
    } else {
      await createDictItem(values);
    }
    message.success(editingItem ? "更新成功" : "创建成功");
    setItemDrawerVisible(false);
    if (selectedType) loadItems(selectedType.typeCode);
  };

  return (
    <div className="p-6">
      <Title level={4} className="mb-6">字典管理</Title>
      <Row gutter={16}>
        <Col span={8}>
          <Card
            title="字典类型"
            extra={
              can("sys_dict:type:create") && (
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAddType}>
                  新增
                </Button>
              )
            }
          >
            <Table
              rowKey="dictTypeId"
              loading={loadingTypes}
              dataSource={types}
              pagination={false}
              size="small"
              onRow={(record) => ({
                onClick: () => setSelectedType(record),
                className: `cursor-pointer ${selectedType?.dictTypeId === record.dictTypeId ? "ant-table-row-selected" : ""}`
              })}
              columns={[
                { title: "类型名称", dataIndex: "typeName" },
                { title: "编码", dataIndex: "typeCode" },
                {
                  title: "操作",
                  width: 100,
                  render: (_, record) => (
                    <Space>
                      {can("sys_dict:type:update") && (
                        <Button
                          type="text"
                          size="small"
                          icon={<EditOutlined />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleEditType(record);
                          }}
                        />
                      )}
                      {can("sys_dict:type:delete") && (
                        <Popconfirm
                          title="删除类型会影响关联的项，确认删除？"
                          onConfirm={(e) => {
                            e?.stopPropagation();
                            handleDeleteType(record.dictTypeId);
                          }}
                        >
                          <Button
                            type="text"
                            size="small"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={(e) => e.stopPropagation()}
                          />
                        </Popconfirm>
                      )}
                    </Space>
                  )
                }
              ]}
            />
          </Card>
        </Col>
        <Col span={16}>
          <Card
            title={`字典项 - ${selectedType?.typeName || "未选择"}`}
            extra={
              can("sys_dict:item:create") && (
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAddItem} disabled={!selectedType}>
                  新增
                </Button>
              )
            }
          >
            <Table
              rowKey="dictItemId"
              loading={loadingItems}
              dataSource={items}
              pagination={false}
              columns={[
                { title: "标签", dataIndex: "itemLabel" },
                { title: "数值", dataIndex: "itemValue" },
                { title: "排序", dataIndex: "sortOrder", width: 80 },
                {
                  title: "状态",
                  dataIndex: "status",
                  width: 80,
                  render: (v) => (v === 1 ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>)
                },
                {
                  title: "操作",
                  width: 120,
                  render: (_, record) => (
                    <Space>
                      {can("sys_dict:item:update") && (
                        <Button
                          type="text"
                          size="small"
                          icon={<EditOutlined />}
                          onClick={() => handleEditItem(record)}
                        />
                      )}
                      {can("sys_dict:item:delete") && (
                        <Popconfirm title="确认删除该项？" onConfirm={() => handleDeleteItem(record.dictItemId)}>
                          <Button type="text" size="small" danger icon={<DeleteOutlined />} />
                        </Popconfirm>
                      )}
                    </Space>
                  )
                }
              ]}
            />
          </Card>
        </Col>
      </Row>

      {/* Type Drawer */}
      <Drawer
        title={editingType ? "编辑字典类型" : "新增字典类型"}
        open={typeDrawerVisible}
        onClose={() => setTypeDrawerVisible(false)}
        width={400}
        destroyOnClose
        footer={
          <div className="flex justify-end space-x-2">
            <Button onClick={() => setTypeDrawerVisible(false)}>取消</Button>
            <Button type="primary" onClick={handleTypeSubmit}>确认</Button>
          </div>
        }
      >
        <Form form={typeForm} layout="vertical">
          <Form.Item label="类型编码" name="typeCode" rules={[{ required: true }]}>
            <Input disabled={!!editingType} placeholder="例如：user_status" />
          </Form.Item>
          <Form.Item label="类型名称" name="typeName" rules={[{ required: true }]}>
            <Input placeholder="例如：用户状态" />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Drawer>

      {/* Item Drawer */}
      <Drawer
        title={editingItem ? "编辑字典项" : "新增字典项"}
        open={itemDrawerVisible}
        onClose={() => setItemDrawerVisible(false)}
        width={400}
        destroyOnClose
        footer={
          <div className="flex justify-end space-x-2">
            <Button onClick={() => setItemDrawerVisible(false)}>取消</Button>
            <Button type="primary" onClick={handleItemSubmit}>确认</Button>
          </div>
        }
      >
        <Form form={itemForm} layout="vertical">
          <Form.Item label="所属类型" name="typeCode">
            <Input disabled />
          </Form.Item>
          <Form.Item label="标签" name="itemLabel" rules={[{ required: true }]}>
            <Input placeholder="例如：启用" />
          </Form.Item>
          <Form.Item label="数值" name="itemValue" rules={[{ required: true }]}>
            <Input placeholder="例如：1" />
          </Form.Item>
          <Form.Item label="排序" name="sortOrder" initialValue={0}>
            <InputNumber className="w-full" />
          </Form.Item>
          <Form.Item label="状态" name="status" initialValue={1}>
            <Select
              options={[
                { label: "启用", value: 1 },
                { label: "禁用", value: 0 }
              ]}
            />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}
