import React, { useState, useEffect } from 'react';
import { Bed, UserCheck, Bell, ClipboardCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/use-toast';
import { apiClient } from '@/services/adminApi';

const HotelManagement = () => {
  const [establishments, setEstablishments] = useState<any[]>([]);
  const [selectedEstablishment, setSelectedEstablishment] = useState<string>('');
  const [rooms, setRooms] = useState<any[]>([]);
  const [housekeeping, setHousekeeping] = useState<any[]>([]);
  const [stats, setStats] = useState<any>(null);
  const { toast } = useToast();

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

  useEffect(() => {
    if (selectedEstablishment) {
      loadHotelData();
    }
  }, [selectedEstablishment]);

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

  const loadHotelData = async () => {
    if (!selectedEstablishment) return;
    try {
      const [roomsData, housekeepingData, statsData] = await Promise.all([
        apiClient.get(`/hotel/establishments/${selectedEstablishment}/rooms`),
        apiClient.get(`/hotel/establishments/${selectedEstablishment}/housekeeping`),
        apiClient.get(`/hotel/establishments/${selectedEstablishment}/stats`)
      ]);
      
      setRooms(Array.isArray(roomsData) ? roomsData : (roomsData as any)?.rooms || []);
      setHousekeeping(Array.isArray(housekeepingData) ? housekeepingData : (housekeepingData as any)?.tasks || []);
      setStats(statsData);
    } catch (error) {
      console.error('Error loading hotel data:', error);
    }
  };

  const handleUpdateRoomAvailability = async (roomId: number, isAvailable: boolean) => {
    try {
      await apiClient.patch(`/hotel/rooms/${roomId}/availability`, { isAvailable });
      toast({ title: 'Éxito', description: 'Disponibilidad actualizada' });
      loadHotelData();
    } catch (error) {
      toast({ title: 'Error', description: 'No se pudo actualizar', variant: 'destructive' });
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <Select value={selectedEstablishment} onValueChange={setSelectedEstablishment}>
          <SelectTrigger className="w-64">
            <SelectValue placeholder="Selecciona un hotel" />
          </SelectTrigger>
          <SelectContent>
            {establishments.map((est) => (
              <SelectItem key={est.id} value={est.id.toString()}>
                {est.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {selectedEstablishment && (
        <>
          {stats && (
            <div className="grid gap-4 md:grid-cols-4">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Ocupación</CardTitle>
                  <Bed className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.occupancyRate}%</div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Check-ins Hoy</CardTitle>
                  <UserCheck className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.todayCheckins || 0}</div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Room Service</CardTitle>
                  <Bell className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.pendingRoomService || 0}</div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Limpieza Pendiente</CardTitle>
                  <ClipboardCheck className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.pendingHousekeeping || 0}</div>
                </CardContent>
              </Card>
            </div>
          )}

          <Tabs defaultValue="rooms" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="rooms">Habitaciones</TabsTrigger>
              <TabsTrigger value="housekeeping">Housekeeping</TabsTrigger>
            </TabsList>

            <TabsContent value="rooms" className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {rooms.map((room) => (
                  <Card key={room.id}>
                    <CardHeader>
                      <CardTitle className="flex items-center justify-between">
                        <span>Habitación {room.roomNumber}</span>
                        <Bed className="w-5 h-5" />
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-2">
                        <p className="text-sm text-muted-foreground">
                          Tipo: {room.roomType}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          Precio: ${room.pricePerNight}/noche
                        </p>
                        <div className="flex items-center justify-between">
                          <Badge variant={room.isAvailable ? "default" : "secondary"}>
                            {room.isAvailable ? 'Disponible' : 'Ocupada'}
                          </Badge>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleUpdateRoomAvailability(room.id, !room.isAvailable)}
                          >
                            Cambiar Estado
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </TabsContent>

            <TabsContent value="housekeeping" className="space-y-4">
              <div className="grid gap-4">
                {housekeeping.map((task: any) => (
                  <Card key={task.id}>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <div className="flex items-center space-x-4">
                        <ClipboardCheck className="w-8 h-8 text-primary" />
                        <div>
                          <CardTitle>Habitación {task.roomNumber}</CardTitle>
                          <p className="text-sm text-muted-foreground">{task.taskType}</p>
                        </div>
                      </div>
                      <Badge variant={task.status === 'completed' ? 'default' : 'secondary'}>
                        {task.status}
                      </Badge>
                    </CardHeader>
                  </Card>
                ))}
              </div>
            </TabsContent>
          </Tabs>
        </>
      )}
    </div>
  );
};

export default HotelManagement;
