import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Product() {
  const [productList, setProductList] = useState([]);
  const [categories, setCategories] = useState([]);
  const [form, setForm] = useState({ name: '', category: '', customCategory: '', price: '', quantity: 0 });
  const [editingId, setEditingId] = useState(null);

  const loadProducts = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/stock');
      setProductList(res.data);
      
      // Extract unique categories directly from the matching alias variables
      const uniqueCats = [...new Set(res.data.map(p => p.category).filter(Boolean))];
      setCategories(uniqueCats);
    } catch (err) {
      console.error("Failed to load catalog matrix:", err);
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    const finalCategory = form.category === 'CUSTOM' ? form.customCategory : form.category;

    if (!finalCategory) return alert("Category assignment is mandatory.");

    const payload = { 
      name: form.name, 
      category: finalCategory, 
      price: parseFloat(form.price) || 0,
      quantity: parseInt(form.quantity, 10) || 0
    };

    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/products/${editingId}`, payload);
        alert('Product modified successfully.');
        setEditingId(null);
      } else {
        await axios.post('http://localhost:5000/api/products', payload);
        alert('Product asset saved successfully.');
      }
      setForm({ name: '', category: '', customCategory: '', price: '', quantity: 0 });
      loadProducts();
    } catch (err) {
      alert('Operation rejected by backend data metrics.');
    }
  };

  const handleEditClick = (product) => {
    setEditingId(product.product_id);
    setForm({
      name: product.product_name || '',
      category: product.category || '',
      customCategory: '',
      price: product.unit_price || 0,
      quantity: product.stored_quantity || 0
    });
  };

  return (
    <div className="space-y-6">
      <div className="border-b border-slate-100 pb-4">
        <h2 className="text-2xl font-bold text-slate-800 tracking-tight">Products & Stock Setup</h2>
        <p className="text-sm text-slate-500">Configure base product catalog items and track live counts.</p>
      </div>

      <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-4 gap-4 bg-slate-50/60 p-5 rounded-xl border border-slate-200/50">
        <div className="md:col-span-4">
          <h3 className="text-xs font-bold uppercase tracking-wider text-indigo-500">
            {editingId ? '⚠️ Modifying Product Entry Profile' : '➕ Register New Core Asset'}
          </h3>
        </div>
        
        <div>
          <label className="block text-xs font-bold text-slate-600 mb-1">Product Name</label>
          <input 
            type="text" 
            value={form.name || ''} 
            className="w-full p-2.5 bg-white border border-slate-200 rounded-xl outline-none focus:border-indigo-500 text-sm" 
            onChange={e => setForm({...form, name: e.target.value})} 
            required 
          />
        </div>
        
        <div>
          <label className="block text-xs font-bold text-slate-600 mb-1">Product Category</label>
          <select 
            value={form.category || ''} 
            className="w-full p-2.5 bg-white border border-slate-200 rounded-xl outline-none focus:border-indigo-500 text-sm" 
            onChange={e => setForm({...form, category: e.target.value})} 
            required
          >
            <option value="">-- Choose Category --</option>
            {categories.map((c, i) => <option key={i} value={c}>{c}</option>)}
            <option value="CUSTOM">➕ Add New Category...</option>
          </select>
        </div>
        
        <div>
          <label className="block text-xs font-bold text-slate-600 mb-1">Base Price (RWF)</label>
          <input 
            type="number" 
            step="0.01" 
            value={form.price || ''} 
            className="w-full p-2.5 bg-white border border-slate-200 rounded-xl outline-none focus:border-indigo-500 text-sm" 
            onChange={e => setForm({...form, price: e.target.value})} 
            required 
          />
        </div>
        
        <div>
          <label className="block text-xs font-bold text-slate-600 mb-1">Initial Stock Quantity</label>
          <input 
            type="number" 
            min="0" 
            value={form.quantity ?? 0} 
            className="w-full p-2.5 bg-white border border-slate-200 rounded-xl outline-none focus:border-indigo-500 text-sm font-mono font-bold text-blue-600" 
            onChange={e => setForm({...form, quantity: parseInt(e.target.value, 10) || 0})} 
            required 
          />
        </div>

        {form.category === 'CUSTOM' && (
          <div className="md:col-span-4 bg-indigo-50/40 p-4 rounded-xl border border-indigo-100/60">
            <label className="block text-xs font-bold text-indigo-700 mb-1">Specify New Category Name</label>
            <input 
              type="text" 
              value={form.customCategory || ''} 
              placeholder="e.g. Mobile Phones" 
              className="w-full p-2.5 bg-white border border-indigo-200 rounded-xl text-sm" 
              onChange={e => setForm({...form, customCategory: e.target.value})} 
              required 
            />
          </div>
        )}
        
        <button type="submit" className="md:col-span-4 bg-indigo-600 hover:bg-indigo-700 text-white font-medium text-sm py-2.5 rounded-xl shadow-sm transition-all">
          {editingId ? 'Save Core Alterations' : 'Register Product Profile'}
        </button>
      </form>

      <div className="overflow-x-auto border border-slate-100 rounded-xl">
        <table className="w-full text-left border-collapse text-sm">
          <thead>
            <tr className="bg-slate-50 border-b border-slate-100 text-xs font-bold text-slate-500 uppercase">
              <th className="p-4">Product Name</th>
              <th className="p-4">Category</th>
              <th className="p-4">Unit Pricing</th>
              <th className="p-4">Current Warehouse Stock</th>
              <th className="p-4 text-center">Controls</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {productList.map(p => (
              <tr key={p.product_id} className="hover:bg-slate-50/40 transition-colors">
                <td className="p-4 font-semibold text-slate-900">{p.product_name}</td>
                <td className="p-4">
                  <span className="px-2.5 py-1 bg-indigo-50 text-indigo-700 text-xs font-bold rounded-md uppercase">
                    {p.category || 'Unassigned'}
                  </span>
                </td>
                <td className="p-4 font-mono font-bold text-indigo-600">
                  {parseFloat(p.unit_price || 0).toLocaleString()} RWF
                </td>
                <td className="p-4 font-mono font-bold text-slate-700">{p.stored_quantity || 0} Units</td>
                <td className="p-4 text-center">
                  <button onClick={() => handleEditClick(p)} className="bg-amber-500 hover:bg-amber-600 text-white px-3 py-1 rounded-lg text-xs font-bold shadow-sm">
                    Edit / Update Stock
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default Product;