import RadioCard from "@/components/RadioCard";
import { Input, Select, Form } from "antd";
import { datasetTypes } from "../../dataset.const";
import { useCallback, useEffect, useState } from "react";
import type { Dispatch, SetStateAction } from "react";
import { queryDatasetTagsUsingGet, queryDatasetsUsingGet } from "../../dataset.api";
import { queryTasksUsingGet } from "@/pages/DataCollection/collection.apis.ts";
import type { Dataset, TagItem } from "../../dataset.model";

export default function BasicInformation({
  data,
  setData,
  hidden = [],
}: {
  data: DatasetFormData;
  setData: Dispatch<SetStateAction<DatasetFormData>>;
  hidden?: string[];
}) {
  const [tagOptions, setTagOptions] = useState<DatasetTagOption[]>([]);
  const [collectionOptions, setCollectionOptions] = useState<SelectOption[]>([]);
  const [parentDatasetOptions, setParentDatasetOptions] = useState<
    { label: string; value: string }[]
  >([]);
  // 获取标签
  const fetchTags = useCallback(async () => {
    if (hidden.includes("tags")) return;
    try {
      const { data } = await queryDatasetTagsUsingGet();
      const tags = Array.isArray(data) ? (data as TagItem[]) : [];
      const customTags = tags.map((tag) => ({
        label: tag.name,
        value: tag.name,
      }));
      setTagOptions(customTags);
    } catch (error) {
      console.error("Error fetching tags: ", error);
    }
  }, [hidden]);

  // 获取归集任务
  const fetchCollectionTasks = useCallback(async () => {
    try {
      const res = await queryTasksUsingGet({ page: 0, size: 100 });
      const tasks = Array.isArray(res?.data?.content)
        ? (res.data.content as CollectionTask[])
        : [];
      const options = tasks.map((task) => ({
        label: task.name,
        value: task.id,
      }));
      setCollectionOptions(options);
    } catch (error) {
      console.error("Error fetching collection tasks:", error);
    }
  }, []);

  const fetchParentDatasets = useCallback(async () => {
    if (hidden.includes("parentDatasetId")) return;
    try {
      const { data: resData } = await queryDatasetsUsingGet({
        parentDatasetId: "",
        page: 1,
        size: 1000,
      });
      const currentDatasetId = data?.id;
      const rootDatasets = Array.isArray(resData?.content)
        ? (resData.content as DatasetSummary[])
        : [];
      const options = rootDatasets
        .filter((dataset) => dataset.id !== currentDatasetId)
        .map((dataset) => ({
          label: dataset.name,
          value: dataset.id,
        }));
      setParentDatasetOptions([
        { label: "根数据集", value: "" },
        ...options,
      ]);
    } catch (error) {
      console.error("Error fetching parent datasets:", error);
    }
  }, [data?.id, hidden]);

  useEffect(() => {
    fetchTags();
    fetchCollectionTasks();
    fetchParentDatasets();
  }, [fetchTags, fetchCollectionTasks, fetchParentDatasets]);
  return (
    <>
      <Form.Item
        label="名称"
        name="name"
        rules={[{ required: true, message: "请输入数据集名称" }]}
      >
        <Input placeholder="输入数据集名称" />
      </Form.Item>
      {!hidden.includes("description") && (
        <Form.Item name="description" label="描述">
          <Input.TextArea placeholder="描述数据集的用途和内容" rows={3} />
        </Form.Item>
      )}
      {!hidden.includes("parentDatasetId") && (
        <Form.Item name="parentDatasetId" label="父数据集">
          <Select
            className="w-full"
            options={parentDatasetOptions}
            placeholder="选择父数据集（仅支持一层）"
          />
        </Form.Item>
      )}

      {/* 数据集类型选择 - 使用卡片形式 */}
      {!hidden.includes("datasetType") && (
        <Form.Item
          label="类型"
          name="datasetType"
          rules={[{ required: true, message: "请选择数据集类型" }]}
        >
          <RadioCard
            options={datasetTypes}
            value={data.type}
            onChange={(datasetType) => setData({ ...data, datasetType })}
          />
        </Form.Item>
      )}
      {!hidden.includes("tags") && (
        <Form.Item label="标签" name="tags">
          <Select
            className="w-full"
            mode="tags"
            options={tagOptions}
            placeholder="请选择标签"
          />
        </Form.Item>
      )}
      {!hidden.includes("dataSource") && (
        <Form.Item name="dataSource" label="关联归集任务">
          <Select placeholder="请选择归集任务" options={collectionOptions} />
        </Form.Item>
      )}
    </>
  );
}

type DatasetFormData = Partial<Dataset> & {
  type?: string;
  parentDatasetId?: string;
};

type DatasetTagOption = {
  label: string;
  value: string;
};

type SelectOption = {
  label: string;
  value: string;
};

type CollectionTask = {
  id: string;
  name: string;
};

type DatasetSummary = {
  id: string;
  name: string;
};
