import { useCallback, useEffect, useMemo, useState } from "react";
import { Card, Button, Table, Tooltip, Tag, App, Statistic } from "antd";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router";
import CardView from "@/components/CardView";
import { SearchControls } from "@/components/SearchControls";
import TagManager from "@/components/business/TagManagement";
import useFetchData from "@/hooks/useFetchData";
import {
  deleteKnowledgeSetByIdUsingDelete,
  getKnowledgeManagementStatisticsUsingGet,
  queryKnowledgeSetsUsingGet,
} from "../knowledge-management.api";
import {
  knowledgeStatusOptions,
  mapKnowledgeSet,
  KnowledgeSetView,
} from "../knowledge-management.const";
import { KnowledgeManagementStatistics, KnowledgeSet } from "../knowledge-management.model";
import CreateKnowledgeSet from "../components/CreateKnowledgeSet";
import {
  createDatasetTagUsingPost,
  deleteDatasetTagUsingDelete,
  queryDatasetTagsUsingGet,
  updateDatasetTagUsingPut,
} from "@/pages/DataManagement/dataset.api";
import { formatBytes } from "@/utils/unit";

type StatisticsItem = {
  title: string;
  value: number | string;
};

const DEFAULT_STATISTICS: StatisticsItem[] = [
  {
    title: "知识集总数",
    value: 0,
  },
  {
    title: "知识类别",
    value: 0,
  },
  {
    title: "文件总数",
    value: 0,
  },
  {
    title: "总大小",
    value: "0 B",
  },
];

export default function KnowledgeManagementPage() {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const [viewMode, setViewMode] = useState<"card" | "list">("card");
  const [isEdit, setIsEdit] = useState(false);
  const [currentSet, setCurrentSet] = useState<KnowledgeSet | null>(null);
  const [tags, setTags] = useState<string[]>([]);
  const [statisticsData, setStatisticsData] = useState<StatisticsItem[]>(
    DEFAULT_STATISTICS
  );

  useEffect(() => {
    const fetchTags = async () => {
      const { data } = await queryDatasetTagsUsingGet();
      setTags(Array.isArray(data) ? data.map((tag) => tag.name) : []);
    };
    fetchTags();
  }, []);

  const filterOptions = useMemo(
    () => [
      {
        key: "status",
        label: "状态",
        options: knowledgeStatusOptions,
      },
      {
        key: "tags",
        label: "标签",
        mode: "multiple",
        options: tags.map((tag) => ({ label: tag, value: tag })),
      },
    ],
    [tags]
  );

  const {
    loading,
    tableData,
    searchParams,
    pagination,
    fetchData,
    setSearchParams,
    handleFiltersChange,
    handleKeywordChange,
  } = useFetchData<KnowledgeSetView>(
    queryKnowledgeSetsUsingGet,
    mapKnowledgeSet,
    30000,
    false,
    [],
    0
  );

  const fetchStatistics = useCallback(async () => {
    try {
      const { data } = await getKnowledgeManagementStatisticsUsingGet();
      const stats = data as KnowledgeManagementStatistics | undefined;
      setStatisticsData([
        {
          title: "知识集总数",
          value: stats?.totalKnowledgeSets ?? 0,
        },
        {
          title: "知识类别",
          value: stats?.totalTags ?? 0,
        },
        {
          title: "文件总数",
          value: stats?.totalFiles ?? 0,
        },
        {
          title: "总大小",
          value: formatBytes(stats?.totalSize ?? 0),
        },
      ]);
    } catch {
      message.error("统计数据加载失败");
      setStatisticsData(DEFAULT_STATISTICS);
    }
  }, [message]);

  const refreshAll = useCallback(
    async (extraParams: Record<string, unknown> = {}) => {
      await Promise.all([fetchData(extraParams), fetchStatistics()]);
    },
    [fetchData, fetchStatistics]
  );

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

  const handleDeleteSet = async (setId: string) => {
    await deleteKnowledgeSetByIdUsingDelete(setId);
    message.success("知识集删除成功");
    await refreshAll({ pageOffset: 0 });
  };

  const operations = [
    {
      key: "edit",
      label: "编辑",
      icon: <EditOutlined />,
      onClick: (item: KnowledgeSetView) => {
        setIsEdit(true);
        setCurrentSet({
          ...(item as unknown as KnowledgeSet),
          status: item.rawStatus,
        });
      },
    },
    {
      key: "delete",
      label: "删除",
      danger: true,
      icon: <DeleteOutlined />,
      confirm: {
        title: "确认删除",
        description: "此操作不可撤销，是否继续？",
        okText: "删除",
        okType: "danger",
        cancelText: "取消",
      },
      onClick: (item: KnowledgeSetView) => handleDeleteSet(item.id),
    },
  ];

  const columns = [
    {
      title: "知识集",
      dataIndex: "name",
      key: "name",
      fixed: "left" as const,
      width: 200,
      ellipsis: true,
      render: (_: unknown, record: KnowledgeSetView) => (
        <Button
          type="link"
          onClick={() => navigate(`/data/knowledge-management/detail/${record.id}`)}
        >
          {record.name}
        </Button>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 120,
      render: (status: KnowledgeSetView["status"]) => (
        <Tag color={status?.color}>{status?.label}</Tag>
      ),
    },
    {
      title: "领域",
      dataIndex: "domain",
      key: "domain",
      width: 120,
      ellipsis: true,
    },
    {
      title: "业务线",
      dataIndex: "businessLine",
      key: "businessLine",
      width: 120,
      ellipsis: true,
    },
    {
      title: "负责人",
      dataIndex: "owner",
      key: "owner",
      width: 120,
      ellipsis: true,
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
      width: 180,
      ellipsis: true,
    },
    {
      title: "操作",
      key: "actions",
      fixed: "right" as const,
      width: 140,
      render: (_: unknown, record: KnowledgeSetView) => (
        <div className="flex items-center gap-2">
          {operations.map((op) => (
            <Tooltip key={op.key} title={op.label}>
              <Button
                type="text"
                icon={op.icon}
                danger={op.danger}
                onClick={() => op.onClick(record)}
              />
            </Tooltip>
          ))}
        </div>
      ),
    },
  ];

  return (
    <div className="h-full flex flex-col gap-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">知识集</h1>
        <div className="flex gap-2 items-center">
          <Button onClick={() => navigate("/data/knowledge-management/search")}>
            全库搜索
          </Button>
          <TagManager
            onCreate={createDatasetTagUsingPost}
            onDelete={(ids: string) => deleteDatasetTagUsingDelete({ ids })}
            onUpdate={updateDatasetTagUsingPut}
            onFetch={queryDatasetTagsUsingGet}
          />
          <CreateKnowledgeSet
            isEdit={isEdit}
            data={currentSet}
            onUpdate={() => {
              refreshAll();
            }}
            onClose={() => {
              setIsEdit(false);
              setCurrentSet(null);
            }}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4">
        <Card>
          <div className="grid grid-cols-4">
            {statisticsData.map((item) => (
              <Statistic
                title={item.title}
                key={item.title}
                value={`${item.value}`}
              />
            ))}
          </div>
        </Card>
      </div>

      <SearchControls
        searchTerm={searchParams.keyword}
        onSearchChange={handleKeywordChange}
        searchPlaceholder="搜索知识集名称、描述"
        filters={filterOptions}
        onFiltersChange={handleFiltersChange}
        onClearFilters={() => setSearchParams({ ...searchParams, filter: {} })}
        viewMode={viewMode}
        onViewModeChange={setViewMode}
        showViewToggle
        onReload={refreshAll}
      />

      {viewMode === "card" ? (
        <CardView
          loading={loading}
          data={tableData}
          operations={operations}
          pagination={pagination}
          onView={(item) => navigate(`/data/knowledge-management/detail/${item.id}`)}
        />
      ) : (
        <Card>
          <Table
            loading={loading}
            scroll={{ x: "max-content", y: "calc(100vh - 20rem)" }}
            columns={columns}
            dataSource={tableData}
            rowKey="id"
            pagination={pagination}
          />
        </Card>
      )}
    </div>
  );
}
