import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Search, Plus, Minus, Trash2, CreditCard, DollarSign, Printer } from 'lucide-react';
import { toast } from 'sonner';

interface MenuItem {
  id: string;
  name: string;
  price: number;
  category: string;
}

interface CartItem extends MenuItem {
  quantity: number;
  notes?: string;
}

const POSTerminal = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [selectedTable, setSelectedTable] = useState<number | null>(null);
  const [cart, setCart] = useState<CartItem[]>([]);

  const menuItems: MenuItem[] = [
    { id: '1', name: 'Paella Valenciana', price: 18.50, category: 'Platos Principales' },
    { id: '2', name: 'Gazpacho Andaluz', price: 6.50, category: 'Entrantes' },
    { id: '3', name: 'Pulpo a la Gallega', price: 16.00, category: 'Platos Principales' },
    { id: '4', name: 'Tarta de Santiago', price: 5.50, category: 'Postres' },
    { id: '5', name: 'Vino Tinto Reserva', price: 12.00, category: 'Bebidas' },
    { id: '6', name: 'Ensalada Mixta', price: 7.50, category: 'Entrantes' },
    { id: '7', name: 'Café Espresso', price: 2.00, category: 'Bebidas' },
    { id: '8', name: 'Crema Catalana', price: 4.50, category: 'Postres' }
  ];

  const categories = ['all', 'Entrantes', 'Platos Principales', 'Postres', 'Bebidas'];

  const filteredItems = menuItems.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || item.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  const addToCart = (item: MenuItem) => {
    const existingItem = cart.find(i => i.id === item.id);
    if (existingItem) {
      setCart(cart.map(i =>
        i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
      ));
    } else {
      setCart([...cart, { ...item, quantity: 1 }]);
    }
    toast.success(`${item.name} agregado`);
  };

  const updateQuantity = (itemId: string, delta: number) => {
    setCart(cart.map(item => {
      if (item.id === itemId) {
        const newQuantity = item.quantity + delta;
        return newQuantity > 0 ? { ...item, quantity: newQuantity } : item;
      }
      return item;
    }).filter(item => item.quantity > 0));
  };

  const removeFromCart = (itemId: string) => {
    setCart(cart.filter(item => item.id !== itemId));
  };

  const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
  const tax = subtotal * 0.10; // 10% IVA
  const total = subtotal + tax;

  const processPayment = (method: 'cash' | 'card') => {
    if (!selectedTable) {
      toast.error('Por favor selecciona una mesa');
      return;
    }
    if (cart.length === 0) {
      toast.error('El carrito está vacío');
      return;
    }

    toast.success(`Pago procesado - Mesa ${selectedTable}`);
    setCart([]);
    setSelectedTable(null);
  };

  const printReceipt = () => {
    toast.success('Imprimiendo recibo...');
  };

  return (
    <div className="grid lg:grid-cols-3 gap-6 h-[calc(100vh-300px)]">
      {/* Left: Menu Items */}
      <div className="lg:col-span-2 space-y-4 overflow-y-auto">
        {/* Table Selection */}
        <Card>
          <CardContent className="p-4">
            <div className="flex flex-wrap gap-2">
              <span className="text-sm font-medium self-center">Mesa:</span>
              {[1, 2, 3, 4, 5, 6, 7, 8].map(num => (
                <Button
                  key={num}
                  size="sm"
                  variant={selectedTable === num ? 'default' : 'outline'}
                  onClick={() => setSelectedTable(num)}
                >
                  {num}
                </Button>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Search and Categories */}
        <div className="space-y-3">
          <div className="relative">
            <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Buscar productos..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>

          <div className="flex flex-wrap gap-2">
            {categories.map(cat => (
              <Button
                key={cat}
                size="sm"
                variant={selectedCategory === cat ? 'default' : 'outline'}
                onClick={() => setSelectedCategory(cat)}
              >
                {cat === 'all' ? 'Todo' : cat}
              </Button>
            ))}
          </div>
        </div>

        {/* Menu Grid */}
        <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
          {filteredItems.map(item => (
            <Card
              key={item.id}
              className="cursor-pointer hover:border-primary transition-colors"
              onClick={() => addToCart(item)}
            >
              <CardContent className="p-4">
                <div className="space-y-2">
                  <h4 className="font-medium text-sm leading-tight">{item.name}</h4>
                  <Badge variant="outline" className="text-xs">{item.category}</Badge>
                  <div className="text-lg font-bold text-primary">
                    €{item.price.toFixed(2)}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>

      {/* Right: Cart and Checkout */}
      <div className="space-y-4">
        <Card className="h-full flex flex-col">
          <CardHeader>
            <CardTitle className="flex justify-between items-center">
              <span>Pedido Actual</span>
              {selectedTable && (
                <Badge>Mesa {selectedTable}</Badge>
              )}
            </CardTitle>
          </CardHeader>
          
          <CardContent className="flex-1 flex flex-col space-y-4">
            {/* Cart Items */}
            <div className="flex-1 overflow-y-auto space-y-2">
              {cart.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  Carrito vacío
                </div>
              ) : (
                cart.map(item => (
                  <div key={item.id} className="p-2 border rounded-lg space-y-2">
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="font-medium text-sm">{item.name}</div>
                        <div className="text-xs text-muted-foreground">
                          €{item.price.toFixed(2)} × {item.quantity}
                        </div>
                      </div>
                      <div className="font-bold">
                        €{(item.price * item.quantity).toFixed(2)}
                      </div>
                    </div>
                    
                    <div className="flex gap-1">
                      <Button
                        size="icon"
                        variant="outline"
                        className="h-7 w-7"
                        onClick={() => updateQuantity(item.id, -1)}
                      >
                        <Minus className="h-3 w-3" />
                      </Button>
                      <Button
                        size="icon"
                        variant="outline"
                        className="h-7 w-7"
                        onClick={() => updateQuantity(item.id, 1)}
                      >
                        <Plus className="h-3 w-3" />
                      </Button>
                      <Button
                        size="icon"
                        variant="ghost"
                        className="h-7 w-7 ml-auto"
                        onClick={() => removeFromCart(item.id)}
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  </div>
                ))
              )}
            </div>

            <Separator />

            {/* Totals */}
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">Subtotal:</span>
                <span>€{subtotal.toFixed(2)}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">IVA (10%):</span>
                <span>€{tax.toFixed(2)}</span>
              </div>
              <Separator />
              <div className="flex justify-between text-lg font-bold">
                <span>Total:</span>
                <span className="text-primary">€{total.toFixed(2)}</span>
              </div>
            </div>

            {/* Payment Buttons */}
            <div className="space-y-2">
              <Button
                className="w-full gap-2"
                size="lg"
                onClick={() => processPayment('card')}
                disabled={cart.length === 0 || !selectedTable}
              >
                <CreditCard className="h-5 w-5" />
                Pagar con Tarjeta
              </Button>
              <Button
                className="w-full gap-2"
                size="lg"
                variant="outline"
                onClick={() => processPayment('cash')}
                disabled={cart.length === 0 || !selectedTable}
              >
                <DollarSign className="h-5 w-5" />
                Pagar en Efectivo
              </Button>
              <Button
                className="w-full gap-2"
                size="sm"
                variant="ghost"
                onClick={printReceipt}
                disabled={cart.length === 0}
              >
                <Printer className="h-4 w-4" />
                Imprimir Recibo
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};

export default POSTerminal;
