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, User, Plus, Check } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { toast } from 'sonner';

interface Order {
  id: string;
  tableNumber: number;
  items: OrderItem[];
  status: 'pending' | 'preparing' | 'ready' | 'served';
  timestamp: Date;
  waiter: string;
  total: number;
}

interface OrderItem {
  name: string;
  quantity: number;
  price: number;
  notes?: string;
}

const TableOrders = () => {
  const [orders, setOrders] = useState<Order[]>([
    {
      id: '1',
      tableNumber: 5,
      items: [
        { name: 'Paella Valenciana', quantity: 2, price: 18.50 },
        { name: 'Gazpacho', quantity: 2, price: 6.50 }
      ],
      status: 'preparing',
      timestamp: new Date(Date.now() - 15 * 60000),
      waiter: 'Carlos M.',
      total: 50.00
    },
    {
      id: '2',
      tableNumber: 3,
      items: [
        { name: 'Pulpo a la Gallega', quantity: 1, price: 16.00, notes: 'Sin pimentón' }
      ],
      status: 'pending',
      timestamp: new Date(Date.now() - 5 * 60000),
      waiter: 'Ana L.',
      total: 16.00
    },
    {
      id: '3',
      tableNumber: 8,
      items: [
        { name: 'Tarta de Santiago', quantity: 3, price: 5.50 }
      ],
      status: 'ready',
      timestamp: new Date(Date.now() - 20 * 60000),
      waiter: 'Carlos M.',
      total: 16.50
    }
  ]);

  const getStatusColor = (status: Order['status']) => {
    switch (status) {
      case 'pending': return 'secondary';
      case 'preparing': return 'default';
      case 'ready': return 'default';
      case 'served': return 'outline';
      default: return 'secondary';
    }
  };

  const getStatusLabel = (status: Order['status']) => {
    switch (status) {
      case 'pending': return 'Pendiente';
      case 'preparing': return 'En Cocina';
      case 'ready': return 'Listo';
      case 'served': return 'Servido';
      default: return status;
    }
  };

  const updateOrderStatus = (orderId: string, newStatus: Order['status']) => {
    setOrders(orders.map(order => 
      order.id === orderId ? { ...order, status: newStatus } : order
    ));
    toast.success('Estado actualizado correctamente');
  };

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

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div className="flex gap-2">
          <Button variant="outline" size="sm">Todas</Button>
          <Button variant="ghost" size="sm">Pendientes</Button>
          <Button variant="ghost" size="sm">En Cocina</Button>
          <Button variant="ghost" size="sm">Listas</Button>
        </div>
        <Dialog>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              Nuevo Pedido
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Nuevo Pedido</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="order-table">Mesa</Label>
                <Input id="order-table" type="number" placeholder="Número de mesa" />
              </div>
              <div>
                <Label htmlFor="order-waiter">Mesero</Label>
                <Input id="order-waiter" placeholder="Nombre del mesero" />
              </div>
              <div>
                <Label htmlFor="order-item">Plato</Label>
                <Select>
                  <SelectTrigger id="order-item">
                    <SelectValue placeholder="Seleccionar plato" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="paella">Paella Valenciana - €18.50</SelectItem>
                    <SelectItem value="gazpacho">Gazpacho - €6.50</SelectItem>
                    <SelectItem value="pulpo">Pulpo a la Gallega - €16.00</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="order-quantity">Cantidad</Label>
                <Input id="order-quantity" type="number" min="1" defaultValue="1" />
              </div>
              <Button className="w-full">Crear Pedido</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {orders.map((order) => (
          <Card key={order.id}>
            <CardHeader className="pb-3">
              <div className="flex justify-between items-start">
                <CardTitle className="text-lg">Mesa {order.tableNumber}</CardTitle>
                <Badge variant={getStatusColor(order.status)}>
                  {getStatusLabel(order.status)}
                </Badge>
              </div>
              <div className="flex gap-4 text-sm text-muted-foreground mt-2">
                <div className="flex items-center gap-1">
                  <User className="h-3 w-3" />
                  {order.waiter}
                </div>
                <div className="flex items-center gap-1">
                  <Clock className="h-3 w-3" />
                  {getTimeSince(order.timestamp)}
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="space-y-2">
                {order.items.map((item, idx) => (
                  <div key={idx} className="flex justify-between text-sm">
                    <span>
                      {item.quantity}x {item.name}
                      {item.notes && (
                        <span className="text-xs text-muted-foreground block">
                          Nota: {item.notes}
                        </span>
                      )}
                    </span>
                    <span className="font-medium">€{(item.quantity * item.price).toFixed(2)}</span>
                  </div>
                ))}
              </div>
              
              <div className="pt-2 border-t flex justify-between items-center">
                <span className="font-bold">Total:</span>
                <span className="font-bold text-lg">€{order.total.toFixed(2)}</span>
              </div>

              <div className="flex gap-2 pt-2">
                {order.status === 'pending' && (
                  <Button 
                    size="sm" 
                    className="flex-1"
                    onClick={() => updateOrderStatus(order.id, 'preparing')}
                  >
                    Enviar a Cocina
                  </Button>
                )}
                {order.status === 'ready' && (
                  <Button 
                    size="sm" 
                    className="flex-1 gap-2"
                    onClick={() => updateOrderStatus(order.id, 'served')}
                  >
                    <Check className="h-4 w-4" />
                    Marcar Servido
                  </Button>
                )}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default TableOrders;
