import React, { useRef } from 'react';
import { Download, Upload, X } from 'lucide-react';

interface ImportModalProps {
  open: boolean;
  onClose: () => void;
  onImport: (file: File) => void;
}

export function ImportModal({ open, onClose, onImport }: ImportModalProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  if (!open) return null;

  const downloadTemplate = () => {
    const headers = ['车辆类型', '车牌号', '*车辆识别代码', '*品牌', '*型号', '*停放区域', '行驶公里数', '*登记所有权', '*运营公司', '*车辆来源'];
    const sample = ['运营车辆', '粤A99999F', 'LNXNEGRR0SR399999', '现代', '帕力安牌4.5吨冷链车', '平湖停车场', '12580.50', '羚牛氢能科技有限公司', '羚牛氢能科技有限公司', '自有'];
    const csv = `\uFEFF非运营车辆不做必填项校验\n${headers.join(',')}\n${sample.join(',')}`;
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '车辆导入模板.csv';
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div className="vm-modal vm-modal-sm" role="dialog" aria-modal="true" aria-labelledby="import-title" onClick={(e) => e.stopPropagation()}>
        <header className="vm-modal-header">
          <h2 id="import-title">批量导入车辆</h2>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-import-body">
          <section className="vm-import-step">
            <div className="vm-import-step-head">
              <span className="vm-step-badge">1</span>
              <span>下载导入模板</span>
            </div>
            <button type="button" className="vm-btn vm-btn-primary" onClick={downloadTemplate}>
              <Download size={16} aria-hidden />
              下载车辆导入模板
            </button>
          </section>
          <section className="vm-import-step">
            <div className="vm-import-step-head">
              <span className="vm-step-badge">2</span>
              <span>上传填写好的文件</span>
            </div>
            <button
              type="button"
              className="vm-upload-zone"
              onClick={() => inputRef.current?.click()}
            >
              <Upload size={28} aria-hidden />
              <p>点击或拖拽文件到此处上传</p>
              <p className="hint">支持 .csv、.xls、.xlsx</p>
              <input
                ref={inputRef}
                type="file"
                accept=".csv,.xls,.xlsx"
                className="sr-only"
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) onImport(file);
                }}
              />
            </button>
          </section>
        </div>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-ghost" onClick={onClose}>关闭</button>
        </footer>
      </div>
    </div>
  );
}
