import React, { useState, useEffect } from 'react';
import { Calendar, Users, Clock, CheckCircle, XCircle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { apiClient } from '@/services/adminApi';

const CommerceReservations = () => {
  const [reservations, setReservations] = useState<any[]>([]);
  const [filter, setFilter] = useState('all');
  const { toast } = useToast();

  useEffect(() => {
    loadReservations();
  }, []);

  const loadReservations = async () => {
    try {
      const response = await apiClient.get('/commerce/reservations');
      setReservations(Array.isArray(response) ? response : (response as any)?.reservations || []);
    } catch (error) {
      console.error('Error loading reservations:', error);
    }
  };

  const handleUpdateReservation = async (id: number, status: string) => {
    try {
      await apiClient.patch(`/commerce/reservations/${id}`, { status });
      toast({ title: 'Éxito', description: 'Reservación actualizada' });
      loadReservations();
    } catch (error) {
      toast({ title: 'Error', description: 'No se pudo actualizar', variant: 'destructive' });
    }
  };

  const handleCancelReservation = async (id: number) => {
    try {
      await apiClient.patch(`/commerce/reservations/${id}/cancel`);
      toast({ title: 'Éxito', description: 'Reservación cancelada' });
      loadReservations();
    } catch (error) {
      toast({ title: 'Error', description: 'No se pudo cancelar', variant: 'destructive' });
    }
  };

  const filteredReservations = reservations.filter(res => 
    filter === 'all' || res.status === filter
  );

  const getStatusBadge = (status: string) => {
    const variants: Record<string, any> = {
      pending: 'secondary',
      confirmed: 'default',
      cancelled: 'destructive',
      completed: 'outline'
    };
    return <Badge variant={variants[status] || 'default'}>{status}</Badge>;
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold">Gestión de Reservaciones</h3>
        <Select value={filter} onValueChange={setFilter}>
          <SelectTrigger className="w-48">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Todas</SelectItem>
            <SelectItem value="pending">Pendientes</SelectItem>
            <SelectItem value="confirmed">Confirmadas</SelectItem>
            <SelectItem value="cancelled">Canceladas</SelectItem>
            <SelectItem value="completed">Completadas</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="grid gap-4">
        {filteredReservations.map((reservation) => (
          <Card key={reservation.id}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <div className="flex items-center space-x-4">
                <Calendar className="w-8 h-8 text-primary" />
                <div>
                  <CardTitle className="text-base">
                    {reservation.establishment?.name || 'Establecimiento'}
                  </CardTitle>
                  <p className="text-sm text-muted-foreground">
                    Reserva #{reservation.id}
                  </p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                {getStatusBadge(reservation.status)}
                {reservation.status === 'pending' && (
                  <>
                    <Button
                      size="sm"
                      onClick={() => handleUpdateReservation(reservation.id, 'confirmed')}
                    >
                      <CheckCircle className="w-4 h-4 mr-1" />
                      Confirmar
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleCancelReservation(reservation.id)}
                    >
                      <XCircle className="w-4 h-4 mr-1" />
                      Cancelar
                    </Button>
                  </>
                )}
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-3 gap-4 text-sm">
                <div className="flex items-center gap-2">
                  <Calendar className="w-4 h-4 text-muted-foreground" />
                  <span>{new Date(reservation.date).toLocaleDateString()}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Clock className="w-4 h-4 text-muted-foreground" />
                  <span>{reservation.time}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Users className="w-4 h-4 text-muted-foreground" />
                  <span>{reservation.guests} personas</span>
                </div>
              </div>
              {reservation.specialRequests && (
                <p className="text-sm text-muted-foreground mt-2">
                  Notas: {reservation.specialRequests}
                </p>
              )}
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default CommerceReservations;
