import React, { useEffect, useState } from 'react';
import { getProducts, createProduct, updateProduct, deleteProduct } from '../utils/api';

const CATEGORIES = ['Smartphones', 'Laptops', 'Tablets', 'Accessories', 'Audio', 'Cameras', 'Networking', 'Other'];

const emptyForm = { productName: '', category: 'Smartphones', quantity: '', unitPrice: '' };

export default function Products() {
  const [products, setProducts] = useState([]);
  const [form, setForm] = useState(emptyForm);
  const [editId, setEditId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [showForm, setShowForm] = useState(false);

  const fetchProducts = () => {
    setLoading(true);
    getProducts().then(r => setProducts(r.data)).catch(console.error).finally(() => setLoading(false));
  };

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

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

  const handleSubmit = async e => {
    e.preventDefault();
    setError(''); setSuccess('');
    setSubmitting(true);
    try {
      const data = { ...form, quantity: Number(form.quantity), unitPrice: Number(form.unitPrice) };
      if (editId) {
        await updateProduct(editId, data);
        setSuccess('Product updated successfully!');
      } else {
        await createProduct(data);
        setSuccess('Product added successfully!');
      }
      setForm(emptyForm); setEditId(null); setShowForm(false);
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Operation failed');
    } finally {
      setSubmitting(false);
    }
  };

  const handleEdit = p => {
    setForm({ productName: p.productName, category: p.category, quantity: p.quantity, unitPrice: p.unitPrice });
    setEditId(p._id);
    setShowForm(true);
    setError(''); setSuccess('');
  };

  const handleDelete = async id => {
    if (!window.confirm('Delete this product?')) return;
    try {
      await deleteProduct(id);
      setSuccess('Product deleted.');
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Delete failed');
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold text-slate-800">Products</h1>
          <p className="text-slate-500 text-sm mt-0.5">Manage your product inventory</p>
        </div>
        <button
          onClick={() => { setShowForm(!showForm); setEditId(null); setForm(emptyForm); setError(''); setSuccess(''); }}
          className="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
        >
          + Add Product
        </button>
      </div>

      {(error || success) && (
        <div className={`rounded-lg px-4 py-3 text-sm mb-4 ${error ? 'bg-red-50 text-red-700 border border-red-200' : 'bg-green-50 text-green-700 border border-green-200'}`}>
          {error || success}
        </div>
      )}

      {/* Form */}
      {showForm && (
        <div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
          <h2 className="font-semibold text-slate-800 mb-4">{editId ? 'Edit Product' : 'Add New Product'}</h2>
          <form onSubmit={handleSubmit} className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Product Name *</label>
              <input name="productName" value={form.productName} onChange={handleChange} required
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="e.g. Samsung Galaxy S24" />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Category *</label>
              <select name="category" value={form.category} onChange={handleChange}
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                {CATEGORIES.map(c => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Quantity *</label>
              <input type="number" name="quantity" value={form.quantity} onChange={handleChange} required min="0"
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="0" />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Unit Price (RWF) *</label>
              <input type="number" name="unitPrice" value={form.unitPrice} onChange={handleChange} required min="0"
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="0" />
            </div>
            {form.quantity && form.unitPrice && (
              <div className="sm:col-span-2 bg-blue-50 rounded-lg px-4 py-2.5">
                <span className="text-sm text-blue-700">Total Price: <strong>RWF {(Number(form.quantity) * Number(form.unitPrice)).toLocaleString()}</strong></span>
              </div>
            )}
            <div className="sm:col-span-2 flex gap-3">
              <button type="submit" disabled={submitting}
                className="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium px-6 py-2.5 rounded-lg disabled:opacity-60 transition-colors">
                {submitting ? 'Saving...' : editId ? 'Update Product' : 'Add Product'}
              </button>
              <button type="button" onClick={() => { setShowForm(false); setForm(emptyForm); setEditId(null); }}
                className="border border-slate-300 text-slate-600 hover:bg-slate-50 text-sm font-medium px-5 py-2.5 rounded-lg transition-colors">
                Cancel
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Table */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
          <h2 className="font-semibold text-slate-800 text-sm">Products List ({products.length})</h2>
        </div>
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : products.length === 0 ? (
          <div className="text-center py-12 text-slate-400 text-sm">No products added yet. Click "Add Product" to get started.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50">
                <tr>
                  {['#', 'Product Name', 'Category', 'Quantity', 'Unit Price', 'Total Price', 'Actions'].map(h => (
                    <th key={h} className="text-left px-5 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {products.map((p, i) => (
                  <tr key={p._id} className="hover:bg-slate-50">
                    <td className="px-5 py-3 text-slate-400">{i + 1}</td>
                    <td className="px-5 py-3 font-medium text-slate-800">{p.productName}</td>
                    <td className="px-5 py-3"><span className="bg-blue-50 text-blue-700 text-xs px-2 py-1 rounded-full font-medium">{p.category}</span></td>
                    <td className="px-5 py-3 text-slate-600">{p.quantity}</td>
                    <td className="px-5 py-3 text-slate-600">RWF {p.unitPrice?.toLocaleString()}</td>
                    <td className="px-5 py-3 font-semibold text-slate-800">RWF {p.totalPrice?.toLocaleString()}</td>
                    <td className="px-5 py-3">
                      <div className="flex gap-2">
                        <button onClick={() => handleEdit(p)} className="text-xs text-blue-600 hover:text-blue-800 font-medium px-2 py-1 hover:bg-blue-50 rounded">Edit</button>
                        <button onClick={() => handleDelete(p._id)} className="text-xs text-red-600 hover:text-red-800 font-medium px-2 py-1 hover:bg-red-50 rounded">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
