import { useState } from 'react';
import { Modal, Upload, Alert, Button, message } from 'antd';
import { importPluginData, type ImportResult } from '../../api/pluginData';

interface ImportModalProps {
  open: boolean;
  pluginId: string;
  entityName: string;
  onClose: () => void;
  onSuccess: () => void;
}

export default function ImportModal({ open, pluginId, entityName, onClose, onSuccess }: ImportModalProps) {
  const [importing, setImporting] = useState(false);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);

  const handleClose = () => {
    onClose();
    setImportResult(null);
  };

  return (
    <Modal
      title="导入数据"
      open={open}
      onCancel={handleClose}
      footer={importResult ? (
        <Button onClick={handleClose}>关闭</Button>
      ) : null}
      destroyOnHidden
    >
      {importResult ? (
        <div>
          <Alert
            type={importResult.error_count > 0 ? 'warning' : 'success'}
            message={`导入完成：成功 ${importResult.success_count} 条，失败 ${importResult.error_count} 条`}
            style={{ marginBottom: 16 }}
          />
          {importResult.errors.length > 0 && (
            <div>
              <h4>错误详情</h4>
              {importResult.errors.map((err, i) => (
                <Alert
                  key={i}
                  type="error"
                  message={`第 ${err.row + 1} 行`}
                  description={err.errors.join('; ')}
                  style={{ marginBottom: 8 }}
                />
              ))}
            </div>
          )}
        </div>
      ) : (
        <Upload.Dragger
          accept=".json"
          maxCount={1}
          beforeUpload={(file) => {
            const reader = new FileReader();
            reader.onload = async (e) => {
              try {
                const text = e.target?.result as string;
                const rows = JSON.parse(text);
                if (!Array.isArray(rows)) {
                  message.error('文件格式错误：需要 JSON 数组');
                  return;
                }
                setImporting(true);
                const result = await importPluginData(pluginId, entityName, rows);
                setImportResult(result);
                if (result.success_count > 0) onSuccess();
              } catch {
                message.error('文件解析失败，请确认格式为 JSON 数组');
              }
              setImporting(false);
            };
            reader.readAsText(file);
            return false;
          }}
          showUploadList={false}
          disabled={importing}
        >
          <p style={{ fontSize: 16, padding: '24px 0' }}>
            {importing ? '导入中...' : '点击或拖拽 JSON 文件到此处'}
          </p>
          <p style={{ color: '#999' }}>支持 JSON 数组格式，单次上限 1000 行</p>
        </Upload.Dragger>
      )}
    </Modal>
  );
}
