import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { QrCode, Plus, Search, Edit, Trash2, Eye } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { toast } from 'sonner';

interface MenuItem {
  id: string;
  name: string;
  description: string;
  price: number;
  category: string;
  image?: string;
  available: boolean;
  allergens?: string[];
}

const DigitalMenu = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [menuItems] = useState<MenuItem[]>([
    {
      id: '1',
      name: 'Paella Valenciana',
      description: 'Arroz tradicional con mariscos y pollo',
      price: 18.50,
      category: 'Platos Principales',
      available: true,
      allergens: ['mariscos', 'gluten']
    },
    {
      id: '2',
      name: 'Gazpacho Andaluz',
      description: 'Sopa fría de tomate con verduras',
      price: 6.50,
      category: 'Entrantes',
      available: true,
      allergens: []
    },
    {
      id: '3',
      name: 'Tarta de Santiago',
      description: 'Tarta de almendra tradicional gallega',
      price: 5.50,
      category: 'Postres',
      available: true,
      allergens: ['frutos secos', 'huevo']
    },
    {
      id: '4',
      name: 'Pulpo a la Gallega',
      description: 'Pulpo cocido con pimentón y aceite de oliva',
      price: 16.00,
      category: 'Platos Principales',
      available: false,
      allergens: ['mariscos']
    }
  ]);

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

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

  const generateQR = (tableNumber: string) => {
    toast.success(`Código QR generado para mesa ${tableNumber}`);
  };

  return (
    <div className="space-y-6">
      {/* QR Generation Section */}
      <div className="flex flex-wrap gap-4 items-end">
        <div className="flex-1 min-w-[200px]">
          <Label htmlFor="table">Número de Mesa</Label>
          <Input id="table" type="number" placeholder="Ej: 5" />
        </div>
        <Button onClick={() => generateQR('5')} className="gap-2">
          <QrCode className="h-4 w-4" />
          Generar QR
        </Button>
        <Dialog>
          <DialogTrigger asChild>
            <Button variant="outline" className="gap-2">
              <Plus className="h-4 w-4" />
              Nuevo Item
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Agregar Item al Menú</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="item-name">Nombre del Plato</Label>
                <Input id="item-name" placeholder="Ej: Paella Valenciana" />
              </div>
              <div>
                <Label htmlFor="item-desc">Descripción</Label>
                <Input id="item-desc" placeholder="Descripción del plato" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="item-price">Precio (€)</Label>
                  <Input id="item-price" type="number" step="0.01" placeholder="18.50" />
                </div>
                <div>
                  <Label htmlFor="item-category">Categoría</Label>
                  <Select>
                    <SelectTrigger id="item-category">
                      <SelectValue placeholder="Seleccionar" />
                    </SelectTrigger>
                    <SelectContent>
                      {categories.slice(1).map(cat => (
                        <SelectItem key={cat} value={cat}>{cat}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <Button className="w-full">Agregar Item</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Search and Filter */}
      <div className="flex flex-wrap gap-4">
        <div className="flex-1 min-w-[200px] relative">
          <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Buscar platos..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={selectedCategory} onValueChange={setSelectedCategory}>
          <SelectTrigger className="w-[200px]">
            <SelectValue placeholder="Categoría" />
          </SelectTrigger>
          <SelectContent>
            {categories.map(cat => (
              <SelectItem key={cat} value={cat}>
                {cat === 'all' ? 'Todas las categorías' : cat}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Menu Items Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {filteredItems.map((item) => (
          <Card key={item.id} className={!item.available ? 'opacity-60' : ''}>
            <CardContent className="p-4">
              <div className="flex justify-between items-start mb-2">
                <div className="flex-1">
                  <h3 className="font-semibold text-lg">{item.name}</h3>
                  <p className="text-sm text-muted-foreground mt-1">{item.description}</p>
                </div>
                <Badge variant={item.available ? 'default' : 'secondary'}>
                  {item.available ? 'Disponible' : 'Agotado'}
                </Badge>
              </div>
              
              {item.allergens && item.allergens.length > 0 && (
                <div className="flex flex-wrap gap-1 my-2">
                  {item.allergens.map(allergen => (
                    <Badge key={allergen} variant="outline" className="text-xs">
                      {allergen}
                    </Badge>
                  ))}
                </div>
              )}

              <div className="flex justify-between items-center mt-4">
                <span className="text-xl font-bold text-primary">€{item.price.toFixed(2)}</span>
                <div className="flex gap-2">
                  <Button size="icon" variant="ghost">
                    <Eye className="h-4 w-4" />
                  </Button>
                  <Button size="icon" variant="ghost">
                    <Edit className="h-4 w-4" />
                  </Button>
                  <Button size="icon" variant="ghost">
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredItems.length === 0 && (
        <div className="text-center py-12 text-muted-foreground">
          No se encontraron platos con los filtros seleccionados
        </div>
      )}
    </div>
  );
};

export default DigitalMenu;
