import { useState, useEffect, useMemo } from 'react';
import { productsAPI } from '../services/api';
import './Products.css';

const CATEGORIES = ['All', 'Phones', 'Laptops', 'Televisions', 'Accessories'];

const categoryColors = {
  Phones: { bg: '#eff6ff', color: '#2563eb', border: '#bfdbfe' },
  Laptops: { bg: '#f5f3ff', color: '#7c3aed', border: '#ddd6fe' },
  Televisions: { bg: '#ecfdf5', color: '#059669', border: '#a7f3d0' },
  Accessories: { bg: '#fff7ed', color: '#ea580c', border: '#fed7aa' },
};

const Products = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingProduct, setEditingProduct] = useState(null);
  const [search, setSearch] = useState('');
  const [activeCategory, setActiveCategory] = useState('All');
  const [viewMode, setViewMode] = useState('grid');
  const [form, setForm] = useState({
    product_name: '',
    category: 'Phones',
    quantity: '',
    price: '',
  });

  useEffect(() => {
    fetchProducts();
  }, []);

  const fetchProducts = async () => {
    try {
      const { data } = await productsAPI.getAll();
      setProducts(data);
    } catch {
      setError('Failed to load products.');
    } finally {
      setLoading(false);
    }
  };

  const filteredProducts = useMemo(() => {
    return products.filter((p) => {
      const matchCategory = activeCategory === 'All' || p.category === activeCategory;
      const matchSearch =
        !search ||
        p.product_name.toLowerCase().includes(search.toLowerCase()) ||
        p.category.toLowerCase().includes(search.toLowerCase());
      return matchCategory && matchSearch;
    });
  }, [products, activeCategory, search]);

  const categoryCounts = useMemo(() => {
    const counts = { All: products.length };
    CATEGORIES.slice(1).forEach((cat) => {
      counts[cat] = products.filter((p) => p.category === cat).length;
    });
    return counts;
  }, [products]);

  const openAddModal = () => {
    setEditingProduct(null);
    setForm({ product_name: '', category: 'Phones', quantity: '', price: '' });
    setShowModal(true);
  };

  const openEditModal = (product) => {
    setEditingProduct(product);
    setForm({
      product_name: product.product_name,
      category: product.category,
      quantity: product.quantity,
      price: product.price,
    });
    setShowModal(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    const payload = {
      ...form,
      quantity: parseInt(form.quantity, 10),
      price: parseFloat(form.price),
    };

    try {
      if (editingProduct) {
        await productsAPI.update(editingProduct.product_id, payload);
        setSuccess('Product updated successfully.');
      } else {
        await productsAPI.create(payload);
        setSuccess('Product added successfully.');
      }
      setShowModal(false);
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Operation failed.');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Are you sure you want to delete this product?')) return;
    try {
      await productsAPI.delete(id);
      setSuccess('Product deleted successfully.');
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to delete product.');
    }
  };

  const formatCurrency = (amount) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);

  const getStockStatus = (qty) => {
    if (qty === 0) return { label: 'Out of stock', class: 'critical' };
    if (qty <= 5) return { label: 'Low stock', class: 'low' };
    if (qty <= 15) return { label: 'Moderate', class: 'moderate' };
    return { label: 'In stock', class: 'good' };
  };

  return (
    <div className="products-page">
      <div className="page-header">
        <div>
          <h1>Product Inventory</h1>
          <p className="page-desc">
            {products.length} products · Manage phones, laptops, TVs & accessories
          </p>
        </div>
        <button className="btn btn-primary" onClick={openAddModal}>
          Add Product
        </button>
      </div>

      {error && <div className="alert alert-error">{error}</div>}
      {success && <div className="alert alert-success">{success}</div>}

      <div className="products-toolbar card">
        <div className="search-box">
          <input
            type="text"
            placeholder="Search products by name or category..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <div className="view-toggle">
          <button
            type="button"
            className={viewMode === 'grid' ? 'active' : ''}
            onClick={() => setViewMode('grid')}
          >
            Grid
          </button>
          <button
            type="button"
            className={viewMode === 'list' ? 'active' : ''}
            onClick={() => setViewMode('list')}
          >
            List
          </button>
        </div>
      </div>

      <div className="category-filters">
        {CATEGORIES.map((cat) => (
          <button
            key={cat}
            type="button"
            className={`category-pill ${activeCategory === cat ? 'active' : ''}`}
            onClick={() => setActiveCategory(cat)}
          >
            {cat}
            <span className="pill-count">{categoryCounts[cat]}</span>
          </button>
        ))}
      </div>

      {loading ? (
        <div className="loading-spinner">
          <div className="spinner" />
          <span>Loading products...</span>
        </div>
      ) : filteredProducts.length === 0 ? (
        <div className="card products-empty">
          <h3>No products found</h3>
          <p>Try adjusting your search or add a new product.</p>
          <button className="btn btn-primary" onClick={openAddModal}>
            Add Product
          </button>
        </div>
      ) : viewMode === 'grid' ? (
        <div className="products-grid">
          {filteredProducts.map((product) => {
            const colors = categoryColors[product.category] || categoryColors.Accessories;
            const stock = getStockStatus(product.quantity);
            const stockPct = Math.min((product.quantity / 50) * 100, 100);

            return (
              <article key={product.product_id} className="product-card">
                <div className="product-card-header" style={{ background: colors.bg, borderColor: colors.border }}>
                  <span
                    className="product-category-tag"
                    style={{ color: colors.color, background: 'white' }}
                  >
                    {product.category}
                  </span>
                </div>

                <div className="product-card-body">
                  <div className="product-id">#{String(product.product_id).padStart(3, '0')}</div>
                  <h3 className="product-name">{product.product_name}</h3>
                  <div className="product-price">{formatCurrency(product.price)}</div>

                  <div className="product-stock-section">
                    <div className="stock-header">
                      <span className={`stock-badge ${stock.class}`}>{stock.label}</span>
                      <span className="stock-count">{product.quantity} units</span>
                    </div>
                    <div className="stock-progress">
                      <div
                        className={`stock-progress-bar ${stock.class}`}
                        style={{ width: `${stockPct}%` }}
                      />
                    </div>
                  </div>
                </div>

                <div className="product-card-footer">
                  <button className="btn btn-outline btn-sm" onClick={() => openEditModal(product)}>
                    Edit
                  </button>
                  <button className="btn btn-ghost btn-sm danger" onClick={() => handleDelete(product.product_id)}>
                    Delete
                  </button>
                </div>
              </article>
            );
          })}
        </div>
      ) : (
        <div className="card products-table-wrap">
          <table className="products-table">
            <thead>
              <tr>
                <th>Product</th>
                <th>Category</th>
                <th>Price</th>
                <th>Stock</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredProducts.map((product) => {
                const stock = getStockStatus(product.quantity);
                return (
                  <tr key={product.product_id}>
                    <td>
                      <div className="table-product-cell">
                        <div>
                          <strong>{product.product_name}</strong>
                          <span className="table-id">ID #{product.product_id}</span>
                        </div>
                      </div>
                    </td>
                    <td><span className="badge badge-primary">{product.category}</span></td>
                    <td className="table-price">{formatCurrency(product.price)}</td>
                    <td><strong>{product.quantity}</strong></td>
                    <td><span className={`stock-badge ${stock.class}`}>{stock.label}</span></td>
                    <td>
                      <div className="table-actions">
                        <button className="btn btn-outline btn-sm" onClick={() => openEditModal(product)}>
                          Edit
                        </button>
                        <button className="btn btn-ghost btn-sm danger" onClick={() => handleDelete(product.product_id)}>
                          Delete
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {showModal && (
        <div className="modal-overlay" onClick={() => setShowModal(false)}>
          <div className="modal product-modal" onClick={(e) => e.stopPropagation()}>
            <h2>{editingProduct ? 'Edit Product' : 'Add New Product'}</h2>
            <p className="modal-subtitle">
              {editingProduct ? 'Update product details below' : 'Fill in the details for your new inventory item'}
            </p>
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>Product Name</label>
                <input
                  value={form.product_name}
                  onChange={(e) => setForm({ ...form, product_name: e.target.value })}
                  placeholder="e.g. iPhone 15 Pro"
                  required
                />
              </div>
              <div className="form-row">
                <div className="form-group">
                  <label>Category</label>
                  <select
                    value={form.category}
                    onChange={(e) => setForm({ ...form, category: e.target.value })}
                  >
                    {CATEGORIES.slice(1).map((cat) => (
                      <option key={cat} value={cat}>{cat}</option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label>Quantity</label>
                  <input
                    type="number"
                    min="0"
                    value={form.quantity}
                    onChange={(e) => setForm({ ...form, quantity: e.target.value })}
                    placeholder="0"
                    required
                  />
                </div>
              </div>
              <div className="form-group">
                <label>Price (USD)</label>
                <input
                  type="number"
                  min="0"
                  step="0.01"
                  value={form.price}
                  onChange={(e) => setForm({ ...form, price: e.target.value })}
                  placeholder="0.00"
                  required
                />
              </div>
              <div className="modal-actions">
                <button type="button" className="btn btn-outline" onClick={() => setShowModal(false)}>
                  Cancel
                </button>
                <button type="submit" className="btn btn-primary">
                  {editingProduct ? 'Save Changes' : 'Add Product'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default Products;
