import React, { useState, useEffect } from 'react';
import api from '../utils/api';

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

const catBadge = cat => {
  const map = { Phones: 'badge-phones', Laptops: 'badge-laptops', Televisions: 'badge-televisions', Accessories: 'badge-accessories' };
  return <span className={`badge ${map[cat] || ''}`}>{cat}</span>;
};

const emptyForm = { product_name: '', category: 'Phones', price: '', stock: '' };

export default function Products() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState(emptyForm);
  const [search, setSearch] = useState('');
  const [filterCat, setFilterCat] = useState('');
  const [error, setError] = useState('');
  const [saving, setSaving] = useState(false);

  const load = () => {
    setLoading(true);
    api.get('/products').then(r => setProducts(r.data)).finally(() => setLoading(false));
  };

  useEffect(load, []);

  const openAdd = () => { setEditing(null); setForm(emptyForm); setError(''); setShowModal(true); };
  const openEdit = p => { setEditing(p); setForm({ product_name: p.product_name, category: p.category, price: p.price, stock: p.stock }); setError(''); setShowModal(true); };
  const closeModal = () => { setShowModal(false); setEditing(null); setError(''); };

  const handleChange = e => setForm(f => ({ ...f, [e.target.name]: e.target.value }));

  const handleSubmit = async e => {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      if (editing) {
        await api.put(`/products/${editing.product_id}`, form);
      } else {
        await api.post('/products', form);
      }
      closeModal();
      load();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to save product.');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async id => {
    if (!window.confirm('Delete this product? This cannot be undone.')) return;
    try {
      await api.delete(`/products/${id}`);
      load();
    } catch (err) {
      alert(err.response?.data?.message || 'Failed to delete.');
    }
  };

  const filtered = products.filter(p => {
    const q = search.toLowerCase();
    return (
      (!search || p.product_name.toLowerCase().includes(q)) &&
      (!filterCat || p.category === filterCat)
    );
  });

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Products</h1>
          <p className="page-subtitle">{products.length} products in inventory</p>
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div className="search-bar">
            🔍
            <input placeholder="Search products..." value={search} onChange={e => setSearch(e.target.value)} />
          </div>
          <select value={filterCat} onChange={e => setFilterCat(e.target.value)} style={{ minWidth: 140 }}>
            <option value="">All Categories</option>
            {CATEGORIES.map(c => <option key={c}>{c}</option>)}
          </select>
          <button className="btn btn-primary" onClick={openAdd}>+ Add Product</button>
        </div>
      </div>

      <div className="card">
        <div className="table-wrapper">
          {loading ? <div className="spinner" /> : filtered.length === 0 ? (
            <div className="empty-state">
              <div className="empty-icon">📦</div>
              <div className="empty-title">No products found</div>
            </div>
          ) : (
            <table>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Product Name</th>
                  <th>Category</th>
                  <th>Price (RWF)</th>
                  <th>Stock</th>
                  <th>Added</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(p => (
                  <tr key={p.product_id}>
                    <td><span style={{ color: 'var(--text-muted)', fontWeight: 600 }}>#{p.product_id}</span></td>
                    <td style={{ fontWeight: 600 }}>{p.product_name}</td>
                    <td>{catBadge(p.category)}</td>
                    <td style={{ fontWeight: 700, color: 'var(--primary)' }}>{Number(p.price).toLocaleString()}</td>
                    <td>
                      <span style={{
                        fontWeight: 700,
                        color: p.stock === 0 ? 'var(--danger)' : p.stock < 5 ? 'var(--warning)' : 'var(--success)'
                      }}>
                        {p.stock}
                      </span>
                    </td>
                    <td style={{ color: 'var(--text-muted)' }}>{new Date(p.created_date).toLocaleDateString()}</td>
                    <td>
                      <div style={{ display: 'flex', gap: 6 }}>
                        <button className="btn btn-ghost btn-sm" onClick={() => openEdit(p)}>✏️ Edit</button>
                        <button className="btn btn-danger btn-sm" onClick={() => handleDelete(p.product_id)}>🗑️</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {showModal && (
        <div className="modal-overlay" onClick={e => e.target === e.currentTarget && closeModal()}>
          <div className="modal">
            <div className="modal-header">
              <span className="modal-title">{editing ? '✏️ Edit Product' : '📦 Add New Product'}</span>
              <button className="modal-close" onClick={closeModal}>✕</button>
            </div>
            <form onSubmit={handleSubmit}>
              <div className="modal-body">
                {error && <div className="alert alert-error" style={{ marginBottom: 16 }}>⚠️ {error}</div>}
                <div className="form-grid">
                  <div className="form-group full">
                    <label>Product Name</label>
                    <input name="product_name" placeholder="e.g. Samsung Galaxy S24" value={form.product_name} onChange={handleChange} required />
                  </div>
                  <div className="form-group">
                    <label>Category</label>
                    <select name="category" value={form.category} onChange={handleChange} required>
                      {CATEGORIES.map(c => <option key={c}>{c}</option>)}
                    </select>
                  </div>
                  <div className="form-group">
                    <label>Price (RWF)</label>
                    <input type="number" name="price" placeholder="0" min="0" value={form.price} onChange={handleChange} required />
                  </div>
                  <div className="form-group">
                    <label>Stock Quantity</label>
                    <input type="number" name="stock" placeholder="0" min="0" value={form.stock} onChange={handleChange} required />
                  </div>
                </div>
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-ghost" onClick={closeModal}>Cancel</button>
                <button type="submit" className="btn btn-primary" disabled={saving}>
                  {saving ? '⏳ Saving...' : editing ? '💾 Update Product' : '✅ Add Product'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
