/**
 * Two folder-targeted upload buttons for a dataset:
 *   • "Tải ảnh gốc"  → original images, stored under imagesTr/
 *   • "Tải nhãn"     → labels / masks,   stored under labelsTr/
 *
 * Both persist via uploadDatasetFiles(id, files, folder) (folder_path, migration 026) and refresh
 * the dataset's file queries so the folder tree reflects the upload immediately.
 */
import { useRef, type ChangeEvent } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { ImagePlus, Tag } from 'lucide-react';
import { toast } from 'sonner';

import { Button, detailFromApiError, uploadDatasetFiles } from '@ump/shared';

export function FolderUploadButtons({ datasetId }: { datasetId: string }) {
  const qc = useQueryClient();
  const imagesInput = useRef<HTMLInputElement>(null);
  const labelsInput = useRef<HTMLInputElement>(null);

  const upload = useMutation({
    mutationFn: ({ files, folder }: { files: File[]; folder: 'imagesTr' | 'labelsTr' }) =>
      uploadDatasetFiles(datasetId, files, folder),
    onSuccess: (res, vars) => {
      const what = vars.folder === 'imagesTr' ? 'ảnh gốc' : 'nhãn';
      const dups = res.files.filter((f) => f.deduped).length;
      toast.success(
        `Đã tải lên ${res.files.length} tệp ${what}${dups ? ` (${dups} trùng nội dung)` : ''}`,
      );
      qc.invalidateQueries({ queryKey: ['imagehub', 'dataset', datasetId] });
    },
    onError: (e: unknown) => toast.error(detailFromApiError(e, 'Tải tệp thất bại')),
  });

  const onPick = (folder: 'imagesTr' | 'labelsTr') => (e: ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []);
    if (files.length) upload.mutate({ files, folder });
    e.target.value = '';
  };

  const busy = upload.isPending;
  const pending = upload.variables?.folder;

  return (
    <div className="flex flex-wrap items-center gap-2">
      <input ref={imagesInput} type="file" multiple className="hidden" onChange={onPick('imagesTr')} />
      <input ref={labelsInput} type="file" multiple className="hidden" onChange={onPick('labelsTr')} />
      <Button size="sm" disabled={busy} onClick={() => imagesInput.current?.click()}>
        <ImagePlus className="mr-1.5 h-4 w-4" />
        {busy && pending === 'imagesTr' ? 'Đang tải…' : 'Tải ảnh gốc'}
      </Button>
      <Button size="sm" variant="outline" disabled={busy} onClick={() => labelsInput.current?.click()}>
        <Tag className="mr-1.5 h-4 w-4" />
        {busy && pending === 'labelsTr' ? 'Đang tải…' : 'Tải nhãn'}
      </Button>
    </div>
  );
}
