"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { parseISO, format } from "date-fns";
import { fr } from "date-fns/locale";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "../ui/alert-dialog";

interface EventDialogProps {
  open: boolean;
  event?: any;
  onClose: () => void;
  onSave: (event: any) => void;
  onDelete?: (eventId: string) => void;
}

export function EventDialog({
  open,
  event,
  onClose,
  onSave,
  onDelete,
}: EventDialogProps) {
  const [title, setTitle] = useState(event?.title || "");
  const [description, setDescription] = useState(event?.description || "");
  const [location, setLocation] = useState(event?.location || "");
  const [start, setStart] = useState(event?.start || "");
  const [end, setEnd] = useState(event?.end || "");
  const [allDay, setAllDay] = useState(event?.allDay || false);
  const [confirmDelete, setConfirmDelete] = useState(false);

  // Formater les dates pour l'affichage
  const formatDate = (dateStr: string) => {
    if (!dateStr) return "";
    try {
      const date = parseISO(dateStr);
      return format(date, allDay ? "yyyy-MM-dd" : "yyyy-MM-dd'T'HH:mm", {
        locale: fr,
      });
    } catch (e) {
      return dateStr;
    }
  };

  // Gérer le changement de l'option "Toute la journée"
  const handleAllDayChange = (checked: boolean) => {
    setAllDay(checked);

    // Ajuster les dates si nécessaire
    if (checked && start) {
      const startDate = parseISO(start);
      setStart(format(startDate, "yyyy-MM-dd"));

      if (end) {
        const endDate = parseISO(end);
        setEnd(format(endDate, "yyyy-MM-dd"));
      }
    }
  };

  // Enregistrer l'événement
  const handleSave = () => {
    onSave({
      id: event?.id,
      title,
      description,
      location,
      start,
      end,
      isAllDay: allDay,
    });
  };

  // Supprimer l'événement
  const handleDelete = () => {
    if (onDelete && event?.id) {
      onDelete(event.id);
    }
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onClose}>
        <DialogContent className='sm:max-w-[550px]'>
          <DialogHeader>
            <DialogTitle>
              {event?.id ? "Modifier l'événement" : "Nouvel événement"}
            </DialogTitle>
          </DialogHeader>

          <div className='grid gap-4 py-4'>
            <div className='grid gap-2'>
              <Label htmlFor='title'>Titre *</Label>
              <Input
                id='title'
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder='Ajouter un titre'
                required
              />
            </div>

            <div className='grid gap-2'>
              <Label htmlFor='description'>Description</Label>
              <Textarea
                id='description'
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Description de l'événement"
                className='min-h-[100px]'
              />
            </div>

            <div className='grid gap-2'>
              <Label htmlFor='location'>Lieu</Label>
              <Input
                id='location'
                value={location}
                onChange={(e) => setLocation(e.target.value)}
                placeholder='Emplacement'
              />
            </div>

            <div className='flex items-center space-x-2'>
              <Checkbox
                id='allDay'
                checked={allDay}
                onCheckedChange={handleAllDayChange}
              />
              <Label htmlFor='allDay'>Toute la journée</Label>
            </div>

            <div className='grid grid-cols-2 gap-4'>
              <div className='grid gap-2'>
                <Label htmlFor='start'>Début *</Label>
                <Input
                  id='start'
                  type={allDay ? "date" : "datetime-local"}
                  value={formatDate(start)}
                  onChange={(e) => setStart(e.target.value)}
                  required
                />
              </div>
              <div className='grid gap-2'>
                <Label htmlFor='end'>Fin *</Label>
                <Input
                  id='end'
                  type={allDay ? "date" : "datetime-local"}
                  value={formatDate(end)}
                  onChange={(e) => setEnd(e.target.value)}
                  required
                />
              </div>
            </div>
          </div>

          <DialogFooter className='flex justify-between'>
            <div>
              {event?.id && onDelete && (
                <Button
                  variant='destructive'
                  onClick={() => setConfirmDelete(true)}
                >
                  Supprimer
                </Button>
              )}
            </div>
            <div className='flex space-x-2'>
              <Button variant='outline' onClick={onClose}>
                Annuler
              </Button>
              <Button onClick={handleSave} disabled={!title || !start || !end}>
                Enregistrer
              </Button>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Dialogue de confirmation de suppression */}
      <AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Confirmer la suppression</AlertDialogTitle>
            <AlertDialogDescription>
              Êtes-vous sûr de vouloir supprimer cet événement ? Cette action
              est irréversible.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete}>
              Supprimer
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
