import { useState, useEffect } from "react";
import {
  Modal,
  Form,
  Select,
  Checkbox,
  Spin,
  Statistic,
  Row,
  Col,
  message,
  Alert,
} from "antd";
import { FileTextOutlined, CheckCircleOutlined, InfoCircleOutlined } from "@ant-design/icons";
import {
  getExportStatsUsingGet,
  downloadAnnotationsUsingGet,
  ExportFormat,
} from "../annotation.api";

interface ExportAnnotationDialogProps {
  open: boolean;
  projectId: string;
  projectName: string;
  datasetType?: string;
  labelingType?: string;
  onClose: () => void;
}

const FORMAT_OPTIONS: { label: string; value: ExportFormat; description: string }[] = [
  {
    label: "JSON",
    value: "json",
    description: "Label Studio 原生格式，包含完整标注结构",
  },
  {
    label: "JSON Lines",
    value: "jsonl",
    description: "每行一条记录，适合大数据处理",
  },
  {
    label: "CSV",
    value: "csv",
    description: "表格格式，可用 Excel 打开",
  },
  {
    label: "COCO",
    value: "coco",
    description: "目标检测通用格式，适用于图像标注",
  },
  {
    label: "YOLO",
    value: "yolo",
    description: "YOLO 格式（ZIP），适用于目标检测训练",
  },
];

export default function ExportAnnotationDialog({
  open,
  projectId,
  projectName,
  datasetType,
  labelingType,
  onClose,
}: ExportAnnotationDialogProps) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [stats, setStats] = useState<{
    totalFiles: number;
    annotatedFiles: number;
  } | null>(null);

  const normalizedDatasetType = datasetType?.toUpperCase().replace(/-/g, "_") || "";
  const normalizedLabelingType = labelingType?.toUpperCase().replace(/-/g, "_") || "";
  const hasDatasetType = Boolean(normalizedDatasetType);
  const isTextDataset = normalizedDatasetType === "TEXT";
  const isDetectionCompatible =
    normalizedDatasetType === "IMAGE" ||
    normalizedDatasetType === "OBJECT_DETECTION" ||
    normalizedLabelingType === "OBJECT_DETECTION";

  // 加载导出统计信息
  useEffect(() => {
    if (open && projectId) {
      setLoading(true);
      getExportStatsUsingGet(projectId)
        .then((res: any) => {
          const data = res?.data || res;
          setStats({
            // 兼容 snake_case 和 camelCase
            totalFiles: data?.totalFiles ?? data?.total_files ?? 0,
            annotatedFiles: data?.annotatedFiles ?? data?.annotated_files ?? 0,
          });
        })
        .catch((err) => {
          console.error("Failed to get export stats:", err);
          message.error("获取导出统计失败");
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [open, projectId]);

  // 重置表单
  useEffect(() => {
    if (open) {
      form.setFieldsValue({
        format: "json",
        onlyAnnotated: true,
        includeData: false,
      });
    }
  }, [open, form]);

  const handleExport = async () => {
    try {
      const values = await form.validateFields();
      setExporting(true);

      // 获取文件名
      const formatExt: Record<ExportFormat, string> = {
        json: "json",
        jsonl: "jsonl",
        csv: "csv",
        coco: "json",
        yolo: "zip",
      };
      const ext = formatExt[values.format as ExportFormat] || "json";
      const filename = `${projectName}_annotations.${ext}`;

      // 下载文件（download函数内部已处理下载逻辑）
      await downloadAnnotationsUsingGet(
        projectId,
        values.format,
        values.onlyAnnotated,
        values.includeData,
        filename
      );

      message.success("导出成功");
      onClose();
    } catch (err: any) {
      console.error("Export failed:", err);
      message.error(err?.message || "导出失败，请稍后重试");
    } finally {
      setExporting(false);
    }
  };

  return (
    <Modal
      title="导出标注数据"
      open={open}
      onCancel={onClose}
      onOk={handleExport}
      okText="导出"
      cancelText="取消"
      confirmLoading={exporting}
      width={520}
    >
      <Spin spinning={loading}>
        {/* 统计信息 */}
        <div className="mb-4 p-4 bg-gray-50 rounded-lg">
          <Row gutter={16}>
            <Col span={12}>
              <Statistic
                title="总文件数"
                value={stats?.totalFiles || 0}
                prefix={<FileTextOutlined />}
              />
            </Col>
            <Col span={12}>
              <Statistic
                title="已标注文件数"
                value={stats?.annotatedFiles || 0}
                prefix={<CheckCircleOutlined style={{ color: "#52c41a" }} />}
              />
            </Col>
          </Row>
        </div>

        {/* 导出选项 */}
        <Form form={form} layout="vertical">
          <Form.Item
            name="format"
            label="导出格式"
            rules={[{ required: true, message: "请选择导出格式" }]}
          >
            <Select
              options={FORMAT_OPTIONS.map((opt) => {
                const isDetectionFormat = opt.value === "coco" || opt.value === "yolo";
                const isDisabledForText = isDetectionFormat && isTextDataset;
                const isDisabledForIncompatibleType =
                  isDetectionFormat && hasDatasetType && !isTextDataset && !isDetectionCompatible;
                const isDisabled = isDisabledForText || isDisabledForIncompatibleType;
                return {
                  label: (
                    <div className="py-1 relative">
                      <div className={`font-medium ${isDisabled ? "text-gray-400" : ""}`}>{opt.label}</div>
                      <div className={`text-xs ${isDisabled ? "text-gray-300" : "text-gray-400"}`}>
                        {opt.description}
                        {isDisabled && (
                          <span className="block mt-1 text-orange-500">
                            <InfoCircleOutlined className="mr-1" />
                            仅适用于图像类或目标检测类数据集
                          </span>
                        )}
                      </div>
                    </div>
                  ),
                  value: opt.value,
                  simpleLabel: opt.label,
                  disabled: isDisabled,
                };
              })}
              optionLabelProp="simpleLabel"
            />
          </Form.Item>

          {(isTextDataset || (hasDatasetType && !isDetectionCompatible)) && (
            <Alert
              type="info"
              message="导出格式兼容性提示"
              description="COCO 和 YOLO 格式仅适用于图像类或目标检测类数据集，当前项目建议使用 JSON、JSON Lines 或 CSV 格式导出。"
              showIcon
              className="mt-4"
            />
          )}

          <Form.Item name="onlyAnnotated" valuePropName="checked">
            <Checkbox>仅导出已标注数据</Checkbox>
          </Form.Item>

          <Form.Item name="includeData" valuePropName="checked">
            <Checkbox>包含原始数据内容</Checkbox>
          </Form.Item>
        </Form>

        {stats && stats.annotatedFiles === 0 && (
          <Alert
            type="warning"
            message="当前项目暂无已标注数据"
            description="请先完成标注后再导出"
            showIcon
          />
        )}
      </Spin>
    </Modal>
  );
}
