"use client";

import { useState } from "react";
import { Check, X, Trash2, Mail, Phone } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Tabs,
  TabsList,
  TabsTrigger,
} from "@/components/ui/tabs";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useAdmin, Reservation } from "@/contexts/AdminContext";
import { toast } from "sonner";

const statusConfig: Record<Reservation["status"], { label: string; variant: "default" | "secondary" | "destructive" }> = {
  pending: { label: "En attente", variant: "secondary" },
  confirmed: { label: "Confirmé", variant: "default" },
  cancelled: { label: "Annulé", variant: "destructive" },
};

export default function AdminReservations() {
  const { reservations, updateReservationStatus, deleteReservation } = useAdmin();
  const [filter, setFilter] = useState<"all" | Reservation["status"]>("all");
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const filtered = reservations
    .filter((r) => filter === "all" || r.status === filter)
    .sort((a, b) => `${b.date}${b.time}`.localeCompare(`${a.date}${a.time}`));

  const handleConfirm = (id: string) => {
    updateReservationStatus(id, "confirmed");
    toast.success("Réservation confirmée");
  };

  const handleCancel = (id: string) => {
    updateReservationStatus(id, "cancelled");
    toast.success("Réservation annulée");
  };

  const handleDelete = () => {
    if (deleteId) {
      deleteReservation(deleteId);
      toast.success("Réservation supprimée");
      setDeleteId(null);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="font-serif text-2xl font-semibold">Réservations</h2>
        <p className="text-sm text-muted-foreground mt-1">{reservations.length} réservation{reservations.length > 1 ? "s" : ""} au total</p>
      </div>

      <Tabs value={filter} onValueChange={(v) => setFilter(v as typeof filter)}>
        <TabsList>
          <TabsTrigger value="all">Toutes</TabsTrigger>
          <TabsTrigger value="pending">En attente</TabsTrigger>
          <TabsTrigger value="confirmed">Confirmées</TabsTrigger>
          <TabsTrigger value="cancelled">Annulées</TabsTrigger>
        </TabsList>
      </Tabs>

      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Cliente</TableHead>
              <TableHead>Contact</TableHead>
              <TableHead>Service</TableHead>
              <TableHead>Date & Heure</TableHead>
              <TableHead>Statut</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filtered.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  Aucune réservation
                </TableCell>
              </TableRow>
            ) : (
              filtered.map((r) => (
                <TableRow key={r.id}>
                  <TableCell className="font-medium">{r.clientName}</TableCell>
                  <TableCell>
                    <div className="text-xs space-y-1">
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <Mail className="h-3 w-3" /> {r.email}
                      </div>
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <Phone className="h-3 w-3" /> {r.phone}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{r.service}</TableCell>
                  <TableCell>
                    <div className="text-sm">
                      {new Date(r.date).toLocaleDateString("fr-FR", { day: "2-digit", month: "short", year: "numeric" })}
                    </div>
                    <div className="text-xs text-muted-foreground">{r.time}</div>
                  </TableCell>
                  <TableCell>
                    <Badge variant={statusConfig[r.status].variant}>{statusConfig[r.status].label}</Badge>
                  </TableCell>
                  <TableCell className="text-right space-x-1">
                    {r.status !== "confirmed" && (
                      <Button variant="ghost" size="icon" onClick={() => handleConfirm(r.id)} title="Confirmer">
                        <Check className="h-4 w-4 text-primary" />
                      </Button>
                    )}
                    {r.status !== "cancelled" && (
                      <Button variant="ghost" size="icon" onClick={() => handleCancel(r.id)} title="Annuler">
                        <X className="h-4 w-4 text-muted-foreground" />
                      </Button>
                    )}
                    <Button variant="ghost" size="icon" onClick={() => setDeleteId(r.id)} title="Supprimer">
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      <AlertDialog open={!!deleteId} onOpenChange={(o) => !o && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Supprimer cette réservation ?</AlertDialogTitle>
            <AlertDialogDescription>Cette action est irréversible.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete}>Supprimer</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};
