import { useState } from "react";
import { router, usePage } from "@inertiajs/react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/Components/ui/dialog";
import { Upload, FileUp } from "lucide-react";

export function UploadDrawModal() {
  const { drawNames } = usePage().props as any;
  const names = drawNames || [];

  const [open, setOpen] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [name, setName] = useState(names[0] || "");
  const [replaceAll, setReplaceAll] = useState(true);
  const [isUploading, setIsUploading] = useState(false);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!file) return;

    setIsUploading(true);
    const formData = new FormData();
    formData.append("file", file);
    formData.append("name", name);
    if (replaceAll) {
      formData.append("replace_all", "1");
    }

    router.post("/import-draws", formData, {
      onSuccess: () => {
        setOpen(false);
        setFile(null);
        setIsUploading(false);
        // You could add a toast notification here
      },
      onError: () => {
        setIsUploading(false);
        // Add toast error
      }
    });
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" className="gap-2">
          <Upload className="h-4 w-4" />
          Importer un fichier CSV
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Importer des tirages</DialogTitle>
          <DialogDescription>
            Importez un fichier CSV contenant l'historique des tirages (date, premiers, derniers).
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="grid gap-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="name">Nom du tirage</Label>
            <select
              id="name"
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
            >
              {names.map((drawName: string) => (
                <option key={drawName} value={drawName}>{drawName}</option>
              ))}
            </select>
          </div>
          <div className="grid gap-2">
            <Label htmlFor="file">Fichier CSV</Label>
            <Input
              id="file"
              type="file"
              accept=".csv"
              onChange={(e) => setFile(e.target.files?.[0] || null)}
              required
            />
          </div>
          <div className="flex items-center gap-2">
            <input 
              type="checkbox" 
              id="replace" 
              checked={replaceAll} 
              onChange={(e) => setReplaceAll(e.target.checked)} 
              className="rounded border-input text-primary focus:ring-ring"
            />
            <Label htmlFor="replace" className="text-sm font-normal">
              Remplacer les anciennes données de ce tirage
            </Label>
          </div>
          <DialogFooter>
            <Button type="submit" disabled={!file || isUploading} className="gap-2">
              {isUploading ? "Importation..." : "Importer"}
              {!isUploading && <FileUp className="h-4 w-4" />}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
