import { useRef, useState, type ChangeEvent } from 'react';
import { Upload, X } from 'lucide-react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  Button,
  Input,
  uploadSegmentationMasks,
  type SegmentationMaskInput,
} from '@ump/shared';

interface SegmentationUploadDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  datasetId: string;
  parentFileId: string;
  parentName: string;
  /** Called after a successful link so the caller can refetch the file list. */
  onUploaded: () => void;
}

/** Default organ label from a mask filename: `liver.nii.gz` -> `liver`. */
function organFromFilename(name: string): string {
  const base = (name.split('/').pop() ?? name).replace(/\.(nii\.gz|nii|dcm|dicom)$/i, '');
  return base.replace(/[_-]+/g, ' ').trim();
}

/**
 * Pick organ-mask `.nii.gz` files and link them to a parent image. Each mask carries
 * an organ label (pre-filled from its filename, editable) — the one piece of metadata
 * the bare file picker can't collect — and all are linked to `parentFileId` on submit.
 */
export function SegmentationUploadDialog({
  open,
  onOpenChange,
  datasetId,
  parentFileId,
  parentName,
  onUploaded,
}: SegmentationUploadDialogProps) {
  const fileInput = useRef<HTMLInputElement>(null);
  const [items, setItems] = useState<{ file: File; organ: string }[]>([]);
  const [busy, setBusy] = useState(false);

  const addFiles = (e: ChangeEvent<HTMLInputElement>) => {
    const picked = Array.from(e.target.files ?? []);
    setItems((prev) => [...prev, ...picked.map((file) => ({ file, organ: organFromFilename(file.name) }))]);
    e.target.value = '';
  };
  const setOrgan = (i: number, organ: string) =>
    setItems((prev) => prev.map((it, j) => (j === i ? { ...it, organ } : it)));
  const removeItem = (i: number) => setItems((prev) => prev.filter((_, j) => j !== i));

  const submit = async () => {
    if (!items.length) return;
    if (items.some((it) => !it.organ.trim())) {
      toast.error('Hãy đặt tên cơ quan cho mỗi mặt nạ.');
      return;
    }
    setBusy(true);
    try {
      const res = await uploadSegmentationMasks(datasetId, parentFileId, items as SegmentationMaskInput[]);
      toast.success(`Đã gắn ${res.masks.length} mặt nạ phân vùng`);
      setItems([]);
      onOpenChange(false);
      onUploaded();
    } catch {
      toast.error('Gắn mặt nạ thất bại');
    } finally {
      setBusy(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(o) => { if (!busy) onOpenChange(o); }}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Gắn mặt nạ phân vùng</DialogTitle>
          <DialogDescription>
            Tải các tệp mặt nạ (.nii.gz) theo từng cơ quan và liên kết với{' '}
            <span className="font-mono text-foreground">{parentName}</span>.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3">
          <input
            ref={fileInput}
            type="file"
            accept=".nii,.nii.gz,application/gzip"
            multiple
            className="hidden"
            onChange={addFiles}
          />
          <Button variant="outline" size="sm" onClick={() => fileInput.current?.click()} disabled={busy}>
            <Upload className="mr-2 h-4 w-4" /> Chọn tệp mặt nạ…
          </Button>

          {items.length === 0 ? (
            <p className="text-sm text-muted-foreground">Chưa chọn tệp nào.</p>
          ) : (
            <div className="max-h-72 space-y-2 overflow-y-auto">
              {items.map((it, i) => (
                <div key={`${it.file.name}-${i}`} className="flex items-center gap-2">
                  <span
                    className="w-40 shrink-0 truncate font-mono text-xs text-muted-foreground"
                    title={it.file.name}
                  >
                    {it.file.name}
                  </span>
                  <Input
                    value={it.organ}
                    onChange={(e) => setOrgan(i, e.target.value)}
                    placeholder="Tên cơ quan"
                    className="h-8"
                    aria-label={`Tên cơ quan cho ${it.file.name}`}
                  />
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 shrink-0"
                    onClick={() => removeItem(i)}
                    disabled={busy}
                    title="Bỏ tệp này"
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
            Hủy
          </Button>
          <Button onClick={submit} disabled={busy || items.length === 0}>
            {busy ? 'Đang tải…' : `Gắn ${items.length || ''} mặt nạ`.trim()}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default SegmentationUploadDialog;
