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

interface ExportAnnotationDialogProps {
  open: boolean;
  projectId: string;
  projectName: 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,
  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);

  // 加载导出统计信息
  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 blob = await downloadAnnotationsUsingGet(
        projectId,
        values.format,
        values.onlyAnnotated,
        values.includeData
      );

      // 获取文件名
      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}`;

      // 下载文件
      const url = window.URL.createObjectURL(blob as Blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);

      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) => ({
                label: (
                  <div>
                    <div className="font-medium">{opt.label}</div>
                    <div className="text-xs text-gray-400">{opt.description}</div>
                  </div>
                ),
                value: opt.value,
              }))}
              optionLabelProp="label"
            />
          </Form.Item>

          <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>
  );
}
