import { useState, useEffect } from 'react';
import API from '../api/axios';

const initialForm = {
  productCode: '',
  productName: '',
  category: '',
  quantityInStock: '',
  unitPrice: '',
  supplierName: '',
  dateReceived: '',
};

export default function Products() {
  const [form, setForm] = useState(initialForm);
  const [products, setProducts] = useState([]);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [loading, setLoading] = useState(false);

  const fetchProducts = async () => {
    try {
      const { data } = await API.get('/products');
      setProducts(data);
    } catch {
      setMessage({ type: 'error', text: 'Failed to load products.' });
    }
  };

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setMessage({ type: '', text: '' });

    try {
      await API.post('/products', {
        ...form,
        quantityInStock: parseInt(form.quantityInStock, 10),
        unitPrice: parseFloat(form.unitPrice),
      });
      setMessage({ type: 'success', text: 'Product added successfully!' });
      setForm(initialForm);
      fetchProducts();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Failed to add product.' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-ink-900">Product Management</h2>
        <p className="text-ink-500 mt-1">Add new products to inventory (Insert only)</p>
      </div>

      {message.text && (
        <div className={`mb-6 p-4 rounded-lg text-sm ${
          message.type === 'success' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' : 'bg-rose-50 text-rose-700 border border-rose-200'
        }`}>
          {message.text}
        </div>
      )}

      <div className="grid lg:grid-cols-2 gap-8">
        <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6">
          <h3 className="text-lg font-semibold mb-4">Add New Product</h3>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-ink-700 mb-1">Product Code</label>
                <input name="productCode" value={form.productCode} onChange={handleChange} required
                  className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-ink-700 mb-1">Product Name</label>
                <input name="productName" value={form.productName} onChange={handleChange} required
                  className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-ink-700 mb-1">Category</label>
                <input name="category" value={form.category} onChange={handleChange} required
                  className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-ink-700 mb-1">Quantity in Stock</label>
                <input name="quantityInStock" type="number" min="0" value={form.quantityInStock} onChange={handleChange} required
                  className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-ink-700 mb-1">Unit Price (RWF)</label>
                <input name="unitPrice" type="number" min="0" step="0.01" value={form.unitPrice} onChange={handleChange} required
                  className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
              </div>
              <div>
                <label className="block text-sm font-medium text-ink-700 mb-1">Supplier Name</label>
                <input name="supplierName" value={form.supplierName} onChange={handleChange} required
                  className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
              </div>
              <div className="sm:col-span-2">
                <label className="block text-sm font-medium text-ink-700 mb-1">Date Received</label>
                <input name="dateReceived" type="date" value={form.dateReceived} onChange={handleChange} required
                  className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
              </div>
            </div>
            <button type="submit" disabled={loading}
              className="w-full py-2.5 bg-primary-600 text-white font-semibold rounded-lg hover:bg-primary-700 shadow-sm shadow-primary-900/20 disabled:opacity-50">
              {loading ? 'Saving...' : 'Add Product'}
            </button>
          </form>
        </div>

        <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6 overflow-hidden">
          <h3 className="text-lg font-semibold mb-4">Product List</h3>
          <div className="overflow-x-auto">
            <table className="min-w-full text-sm">
              <thead className="bg-ink-100">
                <tr>
                  <th className="px-3 py-2 text-left font-medium text-ink-700">Code</th>
                  <th className="px-3 py-2 text-left font-medium text-ink-700">Name</th>
                  <th className="px-3 py-2 text-left font-medium text-ink-700">Stock</th>
                  <th className="px-3 py-2 text-left font-medium text-ink-700">Price</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-ink-100">
                {products.map((p) => (
                  <tr key={p.productCode} className="hover:bg-primary-50/60">
                    <td className="px-3 py-2 font-medium">{p.productCode}</td>
                    <td className="px-3 py-2">{p.productName}</td>
                    <td className="px-3 py-2">{p.quantityInStock}</td>
                    <td className="px-3 py-2">{Number(p.unitPrice).toLocaleString()} RWF</td>
                  </tr>
                ))}
                {products.length === 0 && (
                  <tr><td colSpan="4" className="px-3 py-8 text-center text-ink-500">No products yet</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
