import { useEffect, useState } from 'react';
import { LoaderCircle, Upload } from 'lucide-react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { parseStandardizedImportFile } from '@/lib/standardizedImportParser';
import { importStandardizedRows, type ImportStandardizedResult } from '@/services/standardizedService';

const ACCEPTED_EXTENSIONS = '.xlsx,.xls';
const MAX_FILE_SIZE_BYTES = 20 * 1024 * 1024;

interface StandardizedUploadDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  defaultBatchId?: string;
  allowedMaterialIds?: string[];
  onUploaded?: (result: ImportStandardizedResult) => void | Promise<void>;
}

export function StandardizedUploadDialog({
  open,
  onOpenChange,
  defaultBatchId,
  allowedMaterialIds,
  onUploaded,
}: StandardizedUploadDialogProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [defaultBatch, setDefaultBatch] = useState('');
  const [uploading, setUploading] = useState(false);
  const [inputKey, setInputKey] = useState(0);

  useEffect(() => {
    if (!open) return;
    setSelectedFile(null);
    setDefaultBatch(defaultBatchId ?? '');
    setInputKey(key => key + 1);
  }, [defaultBatchId, open]);

  function handleFileChange(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0] ?? null;
    if (!file) {
      setSelectedFile(null);
      return;
    }

    const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
    if (!['xlsx', 'xls'].includes(ext)) {
      toast.error('仅支持上传 Excel 文件（.xlsx / .xls）。');
      event.target.value = '';
      return;
    }

    if (file.size > MAX_FILE_SIZE_BYTES) {
      toast.error('上传文件不能超过 20MB。');
      event.target.value = '';
      return;
    }

    setSelectedFile(file);
  }

  async function handleSubmit() {
    if (!selectedFile) {
      toast.error('请先选择需要上传的 Excel 文件。');
      return;
    }

    setUploading(true);
    try {
      const parsed = await parseStandardizedImportFile(selectedFile, defaultBatch);
      const allowedMaterialIdSet = new Set((allowedMaterialIds ?? []).filter(Boolean));
      const importRows = allowedMaterialIdSet.size > 0
        ? parsed.rows.filter(row => row.material_id && allowedMaterialIdSet.has(row.material_id))
        : parsed.rows;

      if (parsed.rows.length === 0) {
        throw new Error('未识别到可导入的数据行，请优先使用本页导出的 Excel 进行回传。');
      }

      if (importRows.length === 0) {
        throw new Error('所选 Excel 中没有当前处理范围内的物料记录，请使用本页下载的补充卡回传。');
      }

      const result = await importStandardizedRows(importRows);
      const skippedSuffix = parsed.skippedCount > 0 ? `，跳过 ${parsed.skippedCount} 行` : '';
      const batchSuffix = result.batchIds.length === 1 ? `，批次 ${result.batchIds[0]}` : '';
      toast.success(`已导入 ${result.importedCount} 条标准化结果${batchSuffix}${skippedSuffix}`);
      await Promise.resolve(onUploaded?.(result));
      onOpenChange(false);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '上传标准化结果失败');
    } finally {
      setUploading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[520px]">
        <DialogHeader>
          <DialogTitle>上传标准化结果</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="space-y-1.5">
            <Label htmlFor="standardized-upload-batch">默认批次ID</Label>
            <Input
              id="standardized-upload-batch"
              value={defaultBatch}
              onChange={event => setDefaultBatch(event.target.value)}
              placeholder="文件内没有批次ID时使用"
            />
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="standardized-upload-file">Excel 文件</Label>
            <Input
              key={inputKey}
              id="standardized-upload-file"
              type="file"
              accept={ACCEPTED_EXTENSIONS}
              onChange={handleFileChange}
            />

            {selectedFile ? (
              <p className="text-xs text-foreground">已选择：{selectedFile.name}</p>
            ) : null}
          </div>


        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={uploading}>取消</Button>
          <Button onClick={handleSubmit} disabled={uploading || !selectedFile}>
            {uploading ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : <Upload className="mr-2 h-4 w-4" />}
            开始上传
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
