import { useState, useEffect } from "react";
import { router } from "@inertiajs/react";
import { Button } from "@/Components/ui/button";
import { Label } from "@/Components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/Components/ui/dialog";
import { Trash2, AlertTriangle } from "lucide-react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";

interface DeleteDrawModalProps {
  history: any[];
  onDeleteLocal?: (id: string) => void;
}

export function DeleteDrawModal({ history, onDeleteLocal }: DeleteDrawModalProps) {
  const [open, setOpen] = useState(false);
  const [selectedDrawId, setSelectedDrawId] = useState<string>("");
  const [isDeleting, setIsDeleting] = useState(false);

  // Reset when modal opens
  useEffect(() => {
    if (open) {
      setSelectedDrawId(history.length > 0 ? (history[0].db_id || history[0].drawNo).toString() : "");
    }
  }, [open, history]);

  const handleDelete = () => {
    if (!selectedDrawId) return;

    const draw = history.find(d => (d.db_id?.toString() === selectedDrawId || d.drawNo?.toString() === selectedDrawId));
    if (!draw) return;

    if (!confirm("Êtes-vous sûr de vouloir supprimer définitivement ce tirage ? Cette action est irréversible.")) {
      return;
    }

    if (!draw.db_id) {
      if (onDeleteLocal) {
        onDeleteLocal(selectedDrawId);
      }
      setOpen(false);
      return;
    }

    setIsDeleting(true);
    
    router.delete(`/draws/${draw.db_id}`, {
      onSuccess: () => {
        setOpen(false);
        setIsDeleting(false);
      },
      onError: () => {
        setIsDeleting(false);
      }
    });
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" className="gap-2 bg-red-50 text-red-600 border-red-200 hover:bg-red-100 hover:text-red-700">
          <Trash2 className="h-4 w-4" />
          Supprimer
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-red-600">
            <AlertTriangle className="h-5 w-5" />
            Supprimer un tirage
          </DialogTitle>
          <DialogDescription>
            Sélectionnez un tirage dans l'historique pour le supprimer définitivement de la base de données.
          </DialogDescription>
        </DialogHeader>
        
        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="delete-draw-select">Sélectionner un tirage</Label>
            <select
              id="delete-draw-select"
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
              value={selectedDrawId}
              onChange={(e) => setSelectedDrawId(e.target.value)}
              required
            >
              {history.length === 0 ? (
                <option value="" disabled>-- Aucun tirage --</option>
              ) : (
                <option value="" disabled>-- Choisir un tirage --</option>
              )}
              {history.map((draw) => (
                <option key={draw.db_id || draw.drawNo} value={draw.db_id || draw.drawNo}>
                  {draw.date} - Numéros : {draw.first ? draw.first.join('-') : ''} {!draw.db_id ? "(Non enregistré)" : ""}
                </option>
              ))}
            </select>
          </div>
          
          <Button 
            variant="destructive"
            onClick={handleDelete}
            className="mt-4 gap-2" 
            disabled={isDeleting || !selectedDrawId}
          >
            <Trash2 className="h-4 w-4" />
            {isDeleting ? "Suppression en cours..." : "Supprimer définitivement"}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
