import { useEffect, useState } from "react";
import { Button, DatePicker, Form, Input, message, Modal, Select } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import {
  createKnowledgeSetUsingPost,
  updateKnowledgeSetByIdUsingPut,
} from "../knowledge-management.api";
import {
  knowledgeSourceTypeOptions,
  knowledgeStatusOptions,
  // sensitivityOptions,
} from "../knowledge-management.const";
import {
  KnowledgeSet,
  KnowledgeStatusType,
} from "../knowledge-management.model";
import { queryDatasetTagsUsingGet } from "@/pages/DataManagement/dataset.api";

export default function CreateKnowledgeSet({
  isEdit,
  data,
  showBtn = true,
  onUpdate,
  onClose,
}: {
  isEdit?: boolean;
  showBtn?: boolean;
  data?: Partial<KnowledgeSet> | null;
  onUpdate: () => void;
  onClose: () => void;
}) {
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [tagOptions, setTagOptions] = useState<{ label: string; value: string }[]>([]);

  const fetchTags = async () => {
    try {
      const { data: tagData } = await queryDatasetTagsUsingGet();
      const options = Array.isArray(tagData)
        ? tagData.map((tag) => ({ label: tag.name, value: tag.name }))
        : [];
      setTagOptions(options);
    } catch (error) {
      console.error("获取标签失败", error);
    }
  };

  useEffect(() => {
    if (open) {
      fetchTags();
    }
  }, [open]);

  useEffect(() => {
    if (isEdit && data) {
      setOpen(true);
      form.setFieldsValue({
        name: data.name,
        description: data.description,
        status: data.status ?? KnowledgeStatusType.DRAFT,
        domain: data.domain,
        businessLine: data.businessLine,
        owner: data.owner,
        validFrom: data.validFrom ? dayjs(data.validFrom) : null,
        validTo: data.validTo ? dayjs(data.validTo) : null,
        sourceType: data.sourceType,
        sensitivity: data.sensitivity,
        tags: data.tags?.map((tag) => tag.name) || [],
        metadata: data.metadata,
      });
    }
  }, [isEdit, data, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const validFrom = values.validFrom ? values.validFrom.format("YYYY-MM-DD") : undefined;
      const validTo = values.validTo ? values.validTo.format("YYYY-MM-DD") : undefined;

      if (validFrom && validTo && dayjs(validFrom).isAfter(dayjs(validTo))) {
        message.warning("有效期开始不能晚于结束时间");
        return;
      }

      const payload = {
        ...values,
        validFrom,
        validTo,
        tags: values.tags || [],
      };

      if (isEdit && data?.id) {
        await updateKnowledgeSetByIdUsingPut(data.id, payload);
        message.success("知识集更新成功");
      } else {
        await createKnowledgeSetUsingPost(payload);
        message.success("知识集创建成功");
      }

      setOpen(false);
      form.resetFields();
      onUpdate();
    } catch {
      message.error("操作失败，请重试");
    }
  };

  const handleClose = () => {
    setOpen(false);
    form.resetFields();
    onClose?.();
  };

  const isReadOnly =
    data?.status === KnowledgeStatusType.ARCHIVED ||
    data?.status === KnowledgeStatusType.DEPRECATED;

  return (
    <>
      {showBtn && (
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            form.resetFields();
            form.setFieldsValue({ status: KnowledgeStatusType.DRAFT, tags: [] });
            setOpen(true);
          }}
        >
          创建知识集
        </Button>
      )}
      <Modal
        title={isEdit ? "编辑知识集" : "创建知识集"}
        open={open}
        okText="确定"
        cancelText="取消"
        onCancel={handleClose}
        onOk={handleSubmit}
        maskClosable={false}
        width={720}
        okButtonProps={{ disabled: isReadOnly }}
      >
        <Form form={form} layout="vertical" disabled={isReadOnly}>
          <div className="grid grid-cols-2 gap-4">
            <Form.Item
              label="知识集名称"
              name="name"
              rules={[{ required: true, message: "请输入知识集名称" }]}
            >
              <Input placeholder="请输入知识集名称" />
            </Form.Item>
            <Form.Item label="状态" name="status">
              <Select options={knowledgeStatusOptions} />
            </Form.Item>
          </div>
          <Form.Item label="描述" name="description">
            <Input.TextArea placeholder="请输入知识集描述" rows={3} />
          </Form.Item>
          <div className="grid grid-cols-2 gap-4">
            <Form.Item label="领域" name="domain">
              <Input placeholder="请输入领域" />
            </Form.Item>
            <Form.Item label="业务线" name="businessLine">
              <Input placeholder="请输入业务线" />
            </Form.Item>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <Form.Item label="负责人" name="owner">
              <Input placeholder="请输入负责人" />
            </Form.Item>
            {/* <Form.Item label="敏感级别" name="sensitivity">
              <Select options={sensitivityOptions} placeholder="请选择敏感级别" />
            </Form.Item> */}
          </div>
          <div className="grid grid-cols-2 gap-4">
            <Form.Item label="有效期开始" name="validFrom">
              <DatePicker className="w-full" />
            </Form.Item>
            <Form.Item label="有效期结束" name="validTo">
              <DatePicker className="w-full" />
            </Form.Item>
          </div>
          <Form.Item label="来源类型" name="sourceType">
            <Select options={knowledgeSourceTypeOptions} />
          </Form.Item>
          <Form.Item label="标签" name="tags">
            <Select
              mode="tags"
              options={tagOptions}
              placeholder="请选择或输入标签"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
