import { useState } from 'react';
import { useEquipmentStore } from '@/stores/equipmentStore';
import { useUIStore } from '@/stores/uiStore';
import { EmptyState } from '@/components/common';
import { Package, Plus, AlertTriangle, Pencil, Trash2, ShoppingCart, ShoppingBag } from 'lucide-react';

const categories = ['All', 'skates', 'helmets', 'knee_pads', 'elbow_pads', 'wrist_guards', 'wheels', 'bearings', 'other'];

export default function EquipmentListScreen() {
  const { items, deleteEquipment, getLowStockItems } = useEquipmentStore();
  const { navigateTo, showToast } = useUIStore();
  const [activeCategory, setActiveCategory] = useState('All');
  const [deleteId, setDeleteId] = useState<number | null>(null);

  const filtered = activeCategory === 'All' ? items : items.filter(i => i.category === activeCategory);
  const lowStock = getLowStockItems();

  const handleDelete = async (id: number) => {
    await deleteEquipment(id);
    setDeleteId(null);
    showToast({ type: 'success', message: 'Equipment deleted' });
  };

  const getStockColor = (stock: number) => {
    if (stock >= 10) return 'bg-emerald-500';
    if (stock >= 5) return 'bg-amber-500';
    return 'bg-red-500';
  };

  return (
    <div className="px-4 pt-4 pb-4">
      {/* Low Stock Alert */}
      {lowStock.length > 0 && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-3 flex items-center gap-3 mb-4">
          <AlertTriangle className="w-5 h-5 text-amber-500 flex-shrink-0" />
          <p className="text-xs font-medium text-amber-800">{lowStock.length} items running low on stock</p>
        </div>
      )}

      {/* Category Tabs */}
      <div className="flex gap-2 overflow-x-auto no-scrollbar mb-4">
        {categories.map(cat => (
          <button key={cat} onClick={() => setActiveCategory(cat)}
            className={`px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all ${activeCategory === cat ? 'brand-gradient text-white shadow-sm' : 'bg-gray-100 text-gray-500'}`}>
            {cat === 'All' ? 'All' : cat.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
          </button>
        ))}
      </div>

      {/* Buy / Sell / Add Quick Actions */}
      <div className="grid grid-cols-3 gap-2 mb-4">
        <button onClick={() => navigateTo('recordBuy')} className="h-10 bg-blue-500 text-white text-xs font-semibold rounded-xl flex items-center justify-center gap-1.5 shadow-md shadow-blue-500/20 active:scale-95 transition-transform">
          <ShoppingCart className="w-3.5 h-3.5" /> Buy
        </button>
        <button onClick={() => navigateTo('recordSell')} className="h-10 bg-emerald-500 text-white text-xs font-semibold rounded-xl flex items-center justify-center gap-1.5 shadow-md shadow-emerald-500/20 active:scale-95 transition-transform">
          <ShoppingBag className="w-3.5 h-3.5" /> Sell
        </button>
        <button onClick={() => navigateTo('addEquipment')} className="h-10 brand-gradient text-white text-xs font-semibold rounded-xl flex items-center justify-center gap-1.5 button-shadow active:scale-95 transition-transform">
          <Plus className="w-3.5 h-3.5" /> Add
        </button>
      </div>

      {/* Summary */}
      <div className="flex items-center justify-between mb-3">
        <p className="text-xs text-gray-400">{filtered.length} items</p>
        <p className="text-xs text-gray-400">Total Stock: {filtered.reduce((s, i) => s + i.currentStock, 0)}</p>
      </div>

      {/* Equipment Cards */}
      <div className="space-y-3">
        {filtered.map(item => (
          <div key={item.id} className="bg-white rounded-xl p-4 card-shadow">
            <div className="flex items-center gap-3">
              <div className="w-14 h-14 bg-gray-100 rounded-xl flex items-center justify-center flex-shrink-0">
                <Package className="w-6 h-6 text-orange-500" />
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="text-sm font-semibold text-gray-900 truncate">{item.name}</h3>
                <p className="text-xs text-gray-400 capitalize">{item.category.replace('_', ' ')}</p>
                <div className="flex items-center gap-2 mt-1.5">
                  <div className="flex-1 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                    <div className={`h-full rounded-full ${getStockColor(item.currentStock)}`} style={{ width: `${Math.min((item.currentStock / 20) * 100, 100)}%` }} />
                  </div>
                  <span className={`text-xs font-bold ${item.currentStock < 5 ? 'text-red-500' : item.currentStock < 10 ? 'text-amber-500' : 'text-emerald-600'}`}>
                    {item.currentStock}
                  </span>
                </div>
              </div>
              <div className="flex flex-col gap-1">
                <button onClick={() => navigateTo('editEquipment')} className="p-1.5 rounded-lg hover:bg-gray-100"><Pencil className="w-3.5 h-3.5 text-gray-400" /></button>
                <button onClick={() => setDeleteId(item.id)} className="p-1.5 rounded-lg hover:bg-red-50"><Trash2 className="w-3.5 h-3.5 text-red-400" /></button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {filtered.length === 0 && (
        <EmptyState icon={<Package className="w-16 h-16 text-gray-300" />} title="No equipment found" description="Add your first equipment item" />
      )}

      {/* Delete Confirmation */}
      {deleteId && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center px-6">
          <div className="absolute inset-0 bg-black/50" onClick={() => setDeleteId(null)} />
          <div className="relative bg-white rounded-2xl p-6 max-w-xs w-full text-center animate-scale-in">
            <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-3">
              <Trash2 className="w-6 h-6 text-red-500" />
            </div>
            <h3 className="text-lg font-bold text-gray-900">Delete Equipment?</h3>
            <p className="text-sm text-gray-500 mt-1">This action cannot be undone.</p>
            <div className="flex gap-3 mt-5">
              <button onClick={() => setDeleteId(null)} className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm font-semibold text-gray-600">Cancel</button>
              <button onClick={() => handleDelete(deleteId)} className="flex-1 py-2.5 bg-red-500 text-white rounded-xl text-sm font-semibold">Delete</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
