import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Clock, AlertCircle, Check } from 'lucide-react';
import { toast } from 'sonner';

interface KitchenOrder {
  id: string;
  tableNumber: number;
  items: KitchenItem[];
  timestamp: Date;
  priority: 'normal' | 'urgent';
  status: 'preparing' | 'ready';
}

interface KitchenItem {
  name: string;
  quantity: number;
  notes?: string;
  station: string;
}

const KitchenDisplay = () => {
  const [orders, setOrders] = useState<KitchenOrder[]>([
    {
      id: '1',
      tableNumber: 5,
      items: [
        { name: 'Paella Valenciana', quantity: 2, station: 'Caliente', notes: 'Extra mariscos' },
        { name: 'Gazpacho', quantity: 2, station: 'Frío' }
      ],
      timestamp: new Date(Date.now() - 15 * 60000),
      priority: 'normal',
      status: 'preparing'
    },
    {
      id: '2',
      tableNumber: 3,
      items: [
        { name: 'Pulpo a la Gallega', quantity: 1, station: 'Caliente', notes: 'Sin pimentón' }
      ],
      timestamp: new Date(Date.now() - 25 * 60000),
      priority: 'urgent',
      status: 'preparing'
    },
    {
      id: '3',
      tableNumber: 8,
      items: [
        { name: 'Tarta de Santiago', quantity: 3, station: 'Postres' }
      ],
      timestamp: new Date(Date.now() - 5 * 60000),
      priority: 'normal',
      status: 'preparing'
    }
  ]);

  const getTimeSince = (date: Date) => {
    const minutes = Math.floor((Date.now() - date.getTime()) / 60000);
    return minutes;
  };

  const markAsReady = (orderId: string) => {
    setOrders(orders.map(order => 
      order.id === orderId ? { ...order, status: 'ready' } : order
    ));
    toast.success('Pedido marcado como listo');
  };

  const getStationColor = (station: string) => {
    switch (station) {
      case 'Caliente': return 'bg-orange-500/10 text-orange-500';
      case 'Frío': return 'bg-blue-500/10 text-blue-500';
      case 'Postres': return 'bg-purple-500/10 text-purple-500';
      default: return 'bg-gray-500/10 text-gray-500';
    }
  };

  const preparingOrders = orders.filter(o => o.status === 'preparing');
  const readyOrders = orders.filter(o => o.status === 'ready');

  return (
    <div className="space-y-6">
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Preparing Orders */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold">En Preparación ({preparingOrders.length})</h3>
            <Badge variant="secondary">{preparingOrders.length} pedidos</Badge>
          </div>
          
          <div className="space-y-3">
            {preparingOrders.map((order) => {
              const timeSince = getTimeSince(order.timestamp);
              const isUrgent = timeSince > 20 || order.priority === 'urgent';
              
              return (
                <Card key={order.id} className={isUrgent ? 'border-orange-500' : ''}>
                  <CardHeader className="pb-3">
                    <div className="flex justify-between items-start">
                      <CardTitle className="text-lg flex items-center gap-2">
                        Mesa {order.tableNumber}
                        {isUrgent && (
                          <AlertCircle className="h-5 w-5 text-orange-500" />
                        )}
                      </CardTitle>
                      <div className="flex items-center gap-1 text-sm text-muted-foreground">
                        <Clock className="h-3 w-3" />
                        {timeSince} min
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {order.items.map((item, idx) => (
                      <div key={idx} className="space-y-1">
                        <div className="flex justify-between items-start">
                          <div className="flex-1">
                            <div className="font-medium">
                              {item.quantity}x {item.name}
                            </div>
                            {item.notes && (
                              <div className="text-sm text-orange-500 font-medium mt-1">
                                ⚠️ {item.notes}
                              </div>
                            )}
                          </div>
                          <Badge className={getStationColor(item.station)} variant="secondary">
                            {item.station}
                          </Badge>
                        </div>
                      </div>
                    ))}
                    
                    <Button 
                      className="w-full gap-2 mt-3"
                      onClick={() => markAsReady(order.id)}
                    >
                      <Check className="h-4 w-4" />
                      Marcar como Listo
                    </Button>
                  </CardContent>
                </Card>
              );
            })}
            
            {preparingOrders.length === 0 && (
              <Card>
                <CardContent className="py-12 text-center text-muted-foreground">
                  No hay pedidos en preparación
                </CardContent>
              </Card>
            )}
          </div>
        </div>

        {/* Ready Orders */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold">Listos para Servir ({readyOrders.length})</h3>
            <Badge variant="default">{readyOrders.length} pedidos</Badge>
          </div>
          
          <div className="space-y-3">
            {readyOrders.map((order) => {
              const timeSince = getTimeSince(order.timestamp);
              
              return (
                <Card key={order.id} className="border-green-500 bg-green-500/5">
                  <CardHeader className="pb-3">
                    <div className="flex justify-between items-start">
                      <CardTitle className="text-lg flex items-center gap-2">
                        <Check className="h-5 w-5 text-green-500" />
                        Mesa {order.tableNumber}
                      </CardTitle>
                      <div className="flex items-center gap-1 text-sm text-muted-foreground">
                        <Clock className="h-3 w-3" />
                        {timeSince} min
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    {order.items.map((item, idx) => (
                      <div key={idx} className="flex justify-between">
                        <span className="font-medium">
                          {item.quantity}x {item.name}
                        </span>
                        <Badge className={getStationColor(item.station)} variant="secondary">
                          {item.station}
                        </Badge>
                      </div>
                    ))}
                  </CardContent>
                </Card>
              );
            })}
            
            {readyOrders.length === 0 && (
              <Card>
                <CardContent className="py-12 text-center text-muted-foreground">
                  No hay pedidos listos
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default KitchenDisplay;
