"use client";

import { useState, useEffect } from 'react';
import { useAutenticacion } from '@/proveedores/autenticacion';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';
import { useToast } from '@/hooks/use-toast';
import { Card, CardContent } from '@/components/ui/card';
import { apiClient } from '@/servicios/api-client';

export default function ReservationsPage() {
  const { usuario, cargando } = useAutenticacion();
  const { toast } = useToast();
  const [reservations, setReservations] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const loadReservations = async () => {
      if (!usuario) return;
      try {
        // TODO: Fetch user reservations from API
        // const response = await apiClient.get(`/reservaciones/usuario/${usuario.id}`);
        // setReservations(response.data);
        setReservations([]);
      } catch (error) {
        toast({
          title: 'Error',
          description: 'No se pudieron cargar tus reservas.',
          variant: 'destructive',
        });
      } finally {
        setIsLoading(false);
      }
    };
    loadReservations();
  }, [usuario]);
  
  const getStatus = (startTime: string) => {
    return new Date() > new Date(startTime) ? 'Completada' : 'Confirmada';
  }

  const handleCancelReservation = async (reservationId: string) => {
    try {
      // TODO: Call API to delete reservation
      // await apiClient.delete(`/reservaciones/${reservationId}`);
      setReservations(reservations.filter(r => r.id !== reservationId));
      toast({
        title: 'Reserva Cancelada',
        description: 'Tu reserva ha sido cancelada exitosamente.',
        variant: 'default',
      });
    } catch (error) {
      toast({
        title: 'Error',
        description: 'No se pudo cancelar la reserva.',
        variant: 'destructive',
      });
    }
  };

  if (isLoading) {
    return (
        <div className="container mx-auto px-4 py-12">
            <h1 className="text-3xl md:text-4xl font-bold font-headline mb-8">Mis Reservas</h1>
            <p>Cargando tus reservas...</p>
        </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-12">
      <div className="mb-8">
        <h1 className="text-3xl md:text-4xl font-bold font-headline">Mis Reservas</h1>
        <p className="mt-2 text-muted-foreground">Gestiona tus próximas y pasadas reservas.</p>
      </div>
      <Card className="border-border/60">
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[40%]">Artículo</TableHead>
                <TableHead>Fecha</TableHead>
                <TableHead>Hora</TableHead>
                <TableHead>Estado</TableHead>
                <TableHead className="text-right">Acciones</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {reservations && reservations.map((res) => {
                const status = getStatus(res.fecha_inicio);
                return (
                    <TableRow key={res.id}>
                    <TableCell className="font-medium">{res.titulo}</TableCell>
                    <TableCell>{format(new Date(res.fecha_inicio), 'PPP', { locale: es })}</TableCell>
                    <TableCell>{format(new Date(res.fecha_inicio), 'p', { locale: es })}</TableCell>
                    <TableCell>
                        <Badge
                        variant={status === 'Confirmada' ? 'default' : 'secondary'}
                        className={cn(
                            status === 'Confirmada' && 'bg-green-500/20 text-green-300 border-green-500/30 hover:bg-green-500/30',
                            status === 'Completada' && 'bg-gray-500/20 text-gray-300 border-gray-500/30'
                        )}
                        >
                        {status}
                        </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                        <AlertDialog>
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-8 w-8 p-0">
                                <span className="sr-only">Abrir menú</span>
                                <MoreHorizontal className="h-4 w-4" />
                            </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                            <DropdownMenuItem disabled={status !== 'Confirmada'}>
                                <Pencil className="mr-2 h-4 w-4" />
                                Modificar
                            </DropdownMenuItem>
                            <AlertDialogTrigger asChild>
                                <DropdownMenuItem 
                                className="text-red-400 focus:text-red-400 focus:bg-red-500/10"
                                disabled={status !== 'Confirmada'}
                                >
                                <Trash2 className="mr-2 h-4 w-4" />
                                Cancelar
                                </DropdownMenuItem>
                            </AlertDialogTrigger>
                            </DropdownMenuContent>
                        </DropdownMenu>

                        <AlertDialogContent>
                            <AlertDialogHeader>
                            <AlertDialogTitle>¿Estás seguro?</AlertDialogTitle>
                            <AlertDialogDescription>
                                Esta acción no se puede deshacer. Esto cancelará permanentemente tu reserva.
                            </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                            <AlertDialogCancel>Volver</AlertDialogCancel>
                            <AlertDialogAction 
                                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                                onClick={() => handleCancelReservation(res.id)}
                            >
                                Sí, cancelar
                            </AlertDialogAction>
                            </AlertDialogFooter>
                        </AlertDialogContent>
                        </AlertDialog>
                    </TableCell>
                    </TableRow>
                )
              })}
              {reservations && reservations.length === 0 && (
                <TableRow>
                    <TableCell colSpan={5} className="text-center h-24">No tienes ninguna reserva.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
