import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { 
  UtensilsCrossed, 
  Coffee, 
  Pizza,
  Wine,
  Salad,
  Clock,
  CheckCircle,
  AlertCircle,
  ChefHat,
  Bell,
  DollarSign,
  Search
} from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';

interface Order {
  id: string;
  roomNumber: string;
  guestName: string;
  items: { name: string; quantity: number; price: number }[];
  status: 'pending' | 'preparing' | 'delivering' | 'completed';
  orderTime: string;
  total: number;
}

const RoomService = () => {
  const { toast } = useToast();
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [orders, setOrders] = useState<Order[]>([
    {
      id: 'ORD-001',
      roomNumber: '305',
      guestName: 'Juan Pérez',
      items: [
        { name: 'Desayuno Continental', quantity: 2, price: 25 },
        { name: 'Café Americano', quantity: 2, price: 5 }
      ],
      status: 'preparing',
      orderTime: '08:15 AM',
      total: 60
    },
    {
      id: 'ORD-002',
      roomNumber: '412',
      guestName: 'María González',
      items: [
        { name: 'Club Sandwich', quantity: 1, price: 18 },
        { name: 'Ensalada César', quantity: 1, price: 15 },
        { name: 'Limonada', quantity: 2, price: 6 }
      ],
      status: 'delivering',
      orderTime: '12:30 PM',
      total: 39
    },
    {
      id: 'ORD-003',
      roomNumber: '208',
      guestName: 'Carlos Martínez',
      items: [
        { name: 'Botella de Vino', quantity: 1, price: 45 }
      ],
      status: 'pending',
      orderTime: '07:45 PM',
      total: 45
    }
  ]);

  const statusConfig = {
    pending: { label: 'Pendiente', color: 'bg-yellow-100 text-yellow-800', icon: Bell },
    preparing: { label: 'Preparando', color: 'bg-blue-100 text-blue-800', icon: ChefHat },
    delivering: { label: 'En Camino', color: 'bg-purple-100 text-purple-800', icon: Clock },
    completed: { label: 'Completado', color: 'bg-green-100 text-green-800', icon: CheckCircle }
  };

  const updateOrderStatus = (orderId: string, newStatus: Order['status']) => {
    setOrders(orders.map(order => 
      order.id === orderId ? { ...order, status: newStatus } : order
    ));
    toast({
      title: "Estado Actualizado",
      description: `Orden ${orderId} actualizada a ${statusConfig[newStatus].label}`,
    });
  };

  const filteredOrders = orders.filter(order => {
    const matchesSearch = 
      order.roomNumber.includes(searchTerm) ||
      order.guestName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.id.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = filterStatus === 'all' || order.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const stats = {
    pending: orders.filter(o => o.status === 'pending').length,
    preparing: orders.filter(o => o.status === 'preparing').length,
    delivering: orders.filter(o => o.status === 'delivering').length,
    completed: orders.filter(o => o.status === 'completed').length
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Pendientes</p>
                <p className="text-2xl font-bold">{stats.pending}</p>
              </div>
              <Bell className="w-8 h-8 text-yellow-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Preparando</p>
                <p className="text-2xl font-bold">{stats.preparing}</p>
              </div>
              <ChefHat className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">En Camino</p>
                <p className="text-2xl font-bold">{stats.delivering}</p>
              </div>
              <Clock className="w-8 h-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Completados</p>
                <p className="text-2xl font-bold">{stats.completed}</p>
              </div>
              <CheckCircle className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="p-6">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                placeholder="Buscar por habitación, huésped o ID..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-full md:w-48">
                <SelectValue placeholder="Estado" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos</SelectItem>
                <SelectItem value="pending">Pendientes</SelectItem>
                <SelectItem value="preparing">Preparando</SelectItem>
                <SelectItem value="delivering">En Camino</SelectItem>
                <SelectItem value="completed">Completados</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Orders List */}
      <div className="grid grid-cols-1 gap-4">
        {filteredOrders.map((order) => {
          const StatusIcon = statusConfig[order.status].icon;
          return (
            <Card key={order.id} className="hover:shadow-md transition-shadow">
              <CardContent className="p-6">
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center font-bold text-blue-600">
                        {order.roomNumber}
                      </div>
                      <div>
                        <h3 className="font-semibold text-lg">{order.guestName}</h3>
                        <p className="text-sm text-gray-600">Orden #{order.id}</p>
                      </div>
                      <Badge className={statusConfig[order.status].color}>
                        <StatusIcon className="w-3 h-3 mr-1" />
                        {statusConfig[order.status].label}
                      </Badge>
                    </div>

                    <div className="space-y-1 mb-3">
                      {order.items.map((item, idx) => (
                        <div key={idx} className="flex items-center justify-between text-sm">
                          <span className="text-gray-700">
                            {item.quantity}x {item.name}
                          </span>
                          <span className="font-medium">${item.price * item.quantity}</span>
                        </div>
                      ))}
                    </div>

                    <div className="flex items-center gap-4 text-sm text-gray-600">
                      <div className="flex items-center gap-1">
                        <Clock className="w-4 h-4" />
                        {order.orderTime}
                      </div>
                      <div className="flex items-center gap-1 font-semibold text-green-600">
                        <DollarSign className="w-4 h-4" />
                        Total: ${order.total}
                      </div>
                    </div>
                  </div>

                  <div className="flex flex-col gap-2">
                    {order.status === 'pending' && (
                      <Button 
                        onClick={() => updateOrderStatus(order.id, 'preparing')}
                        className="w-full md:w-auto"
                      >
                        <ChefHat className="w-4 h-4 mr-2" />
                        Preparar
                      </Button>
                    )}
                    {order.status === 'preparing' && (
                      <Button 
                        onClick={() => updateOrderStatus(order.id, 'delivering')}
                        className="w-full md:w-auto bg-purple-600 hover:bg-purple-700"
                      >
                        <Clock className="w-4 h-4 mr-2" />
                        Entregar
                      </Button>
                    )}
                    {order.status === 'delivering' && (
                      <Button 
                        onClick={() => updateOrderStatus(order.id, 'completed')}
                        className="w-full md:w-auto bg-green-600 hover:bg-green-700"
                      >
                        <CheckCircle className="w-4 h-4 mr-2" />
                        Completar
                      </Button>
                    )}
                    {order.status === 'completed' && (
                      <Badge variant="outline" className="bg-green-50">
                        ✓ Completado
                      </Badge>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {filteredOrders.length === 0 && (
        <Card>
          <CardContent className="p-12 text-center">
            <UtensilsCrossed className="w-16 h-16 mx-auto text-gray-300 mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              No hay órdenes
            </h3>
            <p className="text-gray-600">
              No se encontraron órdenes con los filtros aplicados
            </p>
          </CardContent>
        </Card>
      )}

      {/* Popular Menu Items */}
      <Card>
        <CardHeader>
          <CardTitle>Menú Más Solicitado</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[
              { name: 'Desayuno Continental', icon: Coffee, orders: 45 },
              { name: 'Club Sandwich', icon: Pizza, orders: 32 },
              { name: 'Vino Tinto', icon: Wine, orders: 28 },
              { name: 'Ensalada César', icon: Salad, orders: 21 }
            ].map((item, idx) => (
              <div key={idx} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                <item.icon className="w-8 h-8 text-blue-600" />
                <div>
                  <p className="font-medium text-sm">{item.name}</p>
                  <p className="text-xs text-gray-600">{item.orders} pedidos</p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default RoomService;
