import { useState, useEffect } from 'react';
import './styles.css';

interface InventoryItem {
  id: string;
  name: string;
  category: string;
  currentStock: number;
  parLevel: number;
  unit: string;
  costPerUnit: number;
  supplier: string;
  lastRestocked: string;
}

export default function InventoryTracker() {
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [filter, setFilter] = useState<'all' | 'low' | 'critical'>('all');
  const [categoryFilter, setCategoryFilter] = useState('all');

  useEffect(() => {
    // Mock data
    setItems([
      { id: '1', name: 'Ground Beef', category: 'Meats', currentStock: 45, parLevel: 100, unit: 'lbs', costPerUnit: 5.99, supplier: 'Premium Meats Co', lastRestocked: '2024-02-14' },
      { id: '2', name: 'Chicken Breast', category: 'Meats', currentStock: 12, parLevel: 80, unit: 'lbs', costPerUnit: 4.50, supplier: 'Premium Meats Co', lastRestocked: '2024-02-13' },
      { id: '3', name: 'Romaine Lettuce', category: 'Produce', currentStock: 8, parLevel: 30, unit: 'heads', costPerUnit: 1.25, supplier: 'Fresh Farms', lastRestocked: '2024-02-15' },
      { id: '4', name: 'Tomatoes', category: 'Produce', currentStock: 18, parLevel: 40, unit: 'lbs', costPerUnit: 2.75, supplier: 'Fresh Farms', lastRestocked: '2024-02-15' },
      { id: '5', name: 'Cheddar Cheese', category: 'Dairy', currentStock: 25, parLevel: 50, unit: 'lbs', costPerUnit: 6.25, supplier: 'Dairy Direct', lastRestocked: '2024-02-14' },
      { id: '6', name: 'Milk', category: 'Dairy', currentStock: 5, parLevel: 20, unit: 'gallons', costPerUnit: 3.99, supplier: 'Dairy Direct', lastRestocked: '2024-02-12' },
      { id: '7', name: 'Flour', category: 'Dry Goods', currentStock: 85, parLevel: 100, unit: 'lbs', costPerUnit: 0.89, supplier: 'Bulk Foods Inc', lastRestocked: '2024-02-10' },
      { id: '8', name: 'Olive Oil', category: 'Dry Goods', currentStock: 6, parLevel: 15, unit: 'bottles', costPerUnit: 12.99, supplier: 'Bulk Foods Inc', lastRestocked: '2024-02-11' },
      { id: '9', name: 'Bacon', category: 'Meats', currentStock: 22, parLevel: 40, unit: 'lbs', costPerUnit: 7.50, supplier: 'Premium Meats Co', lastRestocked: '2024-02-14' },
      { id: '10', name: 'Onions', category: 'Produce', currentStock: 15, parLevel: 35, unit: 'lbs', costPerUnit: 1.50, supplier: 'Fresh Farms', lastRestocked: '2024-02-15' },
    ]);
  }, []);

  const getStockStatus = (item: InventoryItem) => {
    const percentage = (item.currentStock / item.parLevel) * 100;
    if (percentage < 25) return 'critical';
    if (percentage < 50) return 'low';
    return 'good';
  };

  const filteredItems = items.filter((item) => {
    const status = getStockStatus(item);
    const matchesFilter = filter === 'all' || status === filter;
    const matchesCategory = categoryFilter === 'all' || item.category === categoryFilter;
    return matchesFilter && matchesCategory;
  });

  const categories = Array.from(new Set(items.map(i => i.category)));
  const lowStockCount = items.filter(i => getStockStatus(i) === 'low').length;
  const criticalCount = items.filter(i => getStockStatus(i) === 'critical').length;
  const totalValue = items.reduce((sum, i) => sum + (i.currentStock * i.costPerUnit), 0);

  return (
    <div className="app">
      <header className="app-header">
        <h1>📦 Inventory Tracker</h1>
        <p>Stock levels and alerts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Items</div>
          <div className="stat-value">{items.length}</div>
        </div>
        <div className="stat-card critical-card">
          <div className="stat-label">Critical Stock</div>
          <div className="stat-value critical">{criticalCount}</div>
        </div>
        <div className="stat-card low-card">
          <div className="stat-label">Low Stock</div>
          <div className="stat-value low">{lowStockCount}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Inventory Value</div>
          <div className="stat-value value">${totalValue.toFixed(2)}</div>
        </div>
      </div>

      <div className="filters">
        <div className="filter-group">
          {['all', 'low', 'critical'].map((status) => (
            <button
              key={status}
              className={`filter-btn ${filter === status ? 'active' : ''}`}
              onClick={() => setFilter(status as any)}
            >
              {status.charAt(0).toUpperCase() + status.slice(1)} Stock
            </button>
          ))}
        </div>
        <select
          className="category-select"
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
        >
          <option value="all">All Categories</option>
          {categories.map((cat) => (
            <option key={cat} value={cat}>{cat}</option>
          ))}
        </select>
        <button className="btn-primary">+ Add Item</button>
      </div>

      <div className="inventory-grid">
        {filteredItems.map((item) => {
          const status = getStockStatus(item);
          const percentage = Math.min((item.currentStock / item.parLevel) * 100, 100);

          return (
            <div key={item.id} className={`inventory-card ${status}`}>
              <div className="item-header">
                <div>
                  <h3>{item.name}</h3>
                  <span className="category-badge">{item.category}</span>
                </div>
                <span className={`status-badge ${status}`}>
                  {status === 'critical' && '🚨'}
                  {status === 'low' && '⚠️'}
                  {status === 'good' && '✓'}
                </span>
              </div>

              <div className="stock-bar">
                <div
                  className={`stock-fill ${status}`}
                  style={{ width: `${percentage}%` }}
                ></div>
              </div>

              <div className="stock-info">
                <span className="current-stock">
                  {item.currentStock} {item.unit}
                </span>
                <span className="par-level">
                  Par: {item.parLevel} {item.unit}
                </span>
              </div>

              <div className="item-details">
                <div className="detail-row">
                  <span>Cost/Unit:</span>
                  <span className="value">${item.costPerUnit.toFixed(2)}</span>
                </div>
                <div className="detail-row">
                  <span>Total Value:</span>
                  <span className="value">${(item.currentStock * item.costPerUnit).toFixed(2)}</span>
                </div>
                <div className="detail-row">
                  <span>Supplier:</span>
                  <span className="value">{item.supplier}</span>
                </div>
                <div className="detail-row">
                  <span>Last Restocked:</span>
                  <span className="value">
                    {new Date(item.lastRestocked).toLocaleDateString()}
                  </span>
                </div>
              </div>

              <div className="item-actions">
                <button className="action-btn">Restock</button>
                <button className="action-btn">Adjust</button>
              </div>
            </div>
          );
        })}
      </div>

      {filteredItems.length === 0 && (
        <div className="no-results">No items found</div>
      )}
    </div>
  );
}
