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, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, Package, AlertTriangle, TrendingUp, Search } from 'lucide-react';
import { toast } from 'sonner';

interface InventoryItem {
  id: string;
  name: string;
  category: string;
  quantity: number;
  unit: string;
  minStock: number;
  supplier: string;
  lastRestocked: Date;
  cost: number;
}

const InventoryManagement = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  
  const [inventory, setInventory] = useState<InventoryItem[]>([
    {
      id: '1',
      name: 'Arroz Bomba',
      category: 'Ingredientes',
      quantity: 25,
      unit: 'kg',
      minStock: 10,
      supplier: 'Distribuciones García',
      lastRestocked: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
      cost: 3.50
    },
    {
      id: '2',
      name: 'Gambas Frescas',
      category: 'Mariscos',
      quantity: 5,
      unit: 'kg',
      minStock: 8,
      supplier: 'Pescadería El Mar',
      lastRestocked: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
      cost: 18.00
    },
    {
      id: '3',
      name: 'Vino Tinto Reserva',
      category: 'Bebidas',
      quantity: 45,
      unit: 'botellas',
      minStock: 20,
      supplier: 'Bodegas Rioja',
      lastRestocked: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000),
      cost: 8.50
    },
    {
      id: '4',
      name: 'Aceite de Oliva Virgen Extra',
      category: 'Ingredientes',
      quantity: 8,
      unit: 'litros',
      minStock: 5,
      supplier: 'Aceites del Sur',
      lastRestocked: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
      cost: 12.00
    }
  ]);

  const categories = ['all', 'Ingredientes', 'Mariscos', 'Bebidas', 'Carnes', 'Verduras'];

  const lowStockItems = inventory.filter(item => item.quantity <= item.minStock);

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

  const addStock = (itemId: string, quantity: number) => {
    setInventory(inventory.map(item =>
      item.id === itemId
        ? { ...item, quantity: item.quantity + quantity, lastRestocked: new Date() }
        : item
    ));
    toast.success('Stock actualizado correctamente');
  };

  const getDaysAgo = (date: Date) => {
    const days = Math.floor((Date.now() - date.getTime()) / (1000 * 60 * 60 * 24));
    return days === 0 ? 'Hoy' : days === 1 ? 'Ayer' : `Hace ${days} días`;
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Items</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{inventory.length}</div>
            <p className="text-xs text-muted-foreground">productos en inventario</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Stock Bajo</CardTitle>
            <AlertTriangle className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-500">{lowStockItems.length}</div>
            <p className="text-xs text-muted-foreground">items necesitan reposición</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Valor Total</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              €{inventory.reduce((sum, item) => sum + (item.quantity * item.cost), 0).toFixed(2)}
            </div>
            <p className="text-xs text-muted-foreground">valor del inventario</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Categorías</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{categories.length - 1}</div>
            <p className="text-xs text-muted-foreground">categorías activas</p>
          </CardContent>
        </Card>
      </div>

      {/* Low Stock Alert */}
      {lowStockItems.length > 0 && (
        <Card className="border-orange-500 bg-orange-50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-orange-700">
              <AlertTriangle className="h-5 w-5" />
              Alertas de Stock Bajo
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {lowStockItems.map(item => (
                <div key={item.id} className="flex justify-between items-center p-2 bg-white rounded">
                  <div>
                    <span className="font-medium">{item.name}</span>
                    <span className="text-sm text-muted-foreground ml-2">
                      Stock: {item.quantity} {item.unit}
                    </span>
                  </div>
                  <Button size="sm" onClick={() => addStock(item.id, item.minStock)}>
                    Reponer
                  </Button>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Filters and Actions */}
      <div className="flex flex-wrap gap-4 items-end">
        <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 productos o proveedores..."
            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>
        <Dialog>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              Nuevo Item
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Agregar Item al Inventario</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="item-name">Nombre del Producto</Label>
                <Input id="item-name" placeholder="Ej: Arroz Bomba" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="item-quantity">Cantidad</Label>
                  <Input id="item-quantity" type="number" placeholder="25" />
                </div>
                <div>
                  <Label htmlFor="item-unit">Unidad</Label>
                  <Select>
                    <SelectTrigger id="item-unit">
                      <SelectValue placeholder="Unidad" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="kg">Kilogramos</SelectItem>
                      <SelectItem value="litros">Litros</SelectItem>
                      <SelectItem value="unidades">Unidades</SelectItem>
                      <SelectItem value="botellas">Botellas</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div>
                <Label htmlFor="item-category">Categoría</Label>
                <Select>
                  <SelectTrigger id="item-category">
                    <SelectValue placeholder="Seleccionar categoría" />
                  </SelectTrigger>
                  <SelectContent>
                    {categories.slice(1).map(cat => (
                      <SelectItem key={cat} value={cat}>{cat}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="item-min">Stock Mínimo</Label>
                  <Input id="item-min" type="number" placeholder="10" />
                </div>
                <div>
                  <Label htmlFor="item-cost">Costo Unitario (€)</Label>
                  <Input id="item-cost" type="number" step="0.01" placeholder="3.50" />
                </div>
              </div>
              <div>
                <Label htmlFor="item-supplier">Proveedor</Label>
                <Input id="item-supplier" placeholder="Nombre del proveedor" />
              </div>
              <Button className="w-full">Agregar al Inventario</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Inventory List */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {filteredInventory.map((item) => (
          <Card key={item.id}>
            <CardContent className="p-4">
              <div className="space-y-3">
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <h4 className="font-semibold">{item.name}</h4>
                    <Badge variant="outline" className="mt-1">{item.category}</Badge>
                  </div>
                  {item.quantity <= item.minStock && (
                    <AlertTriangle className="h-5 w-5 text-orange-500" />
                  )}
                </div>

                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Stock actual:</span>
                    <span className="font-medium">
                      {item.quantity} {item.unit}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Stock mínimo:</span>
                    <span>{item.minStock} {item.unit}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Costo:</span>
                    <span>€{item.cost.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Valor total:</span>
                    <span className="font-medium">€{(item.quantity * item.cost).toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Proveedor:</span>
                    <span className="text-xs">{item.supplier}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Última reposición:</span>
                    <span className="text-xs">{getDaysAgo(item.lastRestocked)}</span>
                  </div>
                </div>

                <div className="flex gap-2 pt-2">
                  <Dialog>
                    <DialogTrigger asChild>
                      <Button size="sm" variant="outline" className="flex-1">
                        Reponer
                      </Button>
                    </DialogTrigger>
                    <DialogContent>
                      <DialogHeader>
                        <DialogTitle>Reponer Stock - {item.name}</DialogTitle>
                      </DialogHeader>
                      <div className="space-y-4">
                        <div>
                          <Label>Cantidad a agregar ({item.unit})</Label>
                          <Input type="number" defaultValue={item.minStock} />
                        </div>
                        <div className="p-4 bg-muted rounded-lg">
                          <div className="text-sm text-muted-foreground">Nuevo stock será:</div>
                          <div className="text-2xl font-bold text-primary">
                            {item.quantity + item.minStock} {item.unit}
                          </div>
                        </div>
                        <Button 
                          className="w-full" 
                          onClick={() => addStock(item.id, item.minStock)}
                        >
                          Confirmar Reposición
                        </Button>
                      </div>
                    </DialogContent>
                  </Dialog>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredInventory.length === 0 && (
        <div className="text-center py-12 text-muted-foreground">
          No se encontraron productos
        </div>
      )}
    </div>
  );
};

export default InventoryManagement;
