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

export default function ProductPage() {
  const [products, setProducts] = useState([]);
  const [form, setForm] = useState({ productCode: '', productName: '', quantitySold: '', unitPrice: '' });
  const [message, setMessage] = useState('');

  const fetchProducts = async () => {
    try {
      const response = await api.get('/products');
      setProducts(response.data);
    } catch (error) {
      console.error(error);
    }
  };

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

  const [editingId, setEditingId] = useState(null);

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      const payload = {
        productCode: form.productCode,
        productName: form.productName,
        quantitySold: Number(form.quantitySold),
        unitPrice: Number(form.unitPrice),
      };

      if (editingId) {
        await api.put(`/products/${editingId}`, payload);
        setMessage('Product updated successfully');
        setEditingId(null);
      } else {
        await api.post('/products', payload);
        setMessage('Product added successfully');
      }

      setForm({ productCode: '', productName: '', quantitySold: '', unitPrice: '' });
      fetchProducts();
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to save product.');
    }
  };

  const handleEdit = (product) => {
    setEditingId(product._id);
    setForm({
      productCode: product.productCode,
      productName: product.productName,
      quantitySold: product.quantitySold,
      unitPrice: product.unitPrice,
    });
    setMessage('Editing product record. Click save to update.');
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this product?')) return;
    try {
      await api.delete(`/products/${id}`);
      setMessage('Product deleted successfully');
      fetchProducts();
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to delete product.');
    }
  };

  return (
    <div className="space-y-6">
      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <h2 className="text-xl font-semibold text-slate-900">Add Product</h2>
        <form onSubmit={handleSubmit} className="mt-5 grid gap-4 sm:grid-cols-2">
          <input
            placeholder="Product Code"
            value={form.productCode}
            onChange={(e) => setForm({ ...form, productCode: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            placeholder="Product Name"
            value={form.productName}
            onChange={(e) => setForm({ ...form, productName: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            type="number"
            min="0"
            placeholder="Quantity Sold"
            value={form.quantitySold}
            onChange={(e) => setForm({ ...form, quantitySold: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            type="number"
            min="0"
            step="0.01"
            placeholder="Unit Price"
            value={form.unitPrice}
            onChange={(e) => setForm({ ...form, unitPrice: e.target.value })}
            required
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <button className="col-span-full rounded-2xl bg-slate-900 px-5 py-3 text-white hover:bg-slate-800" type="submit">
            {editingId ? 'Update Product' : 'Save Product'}
          </button>
        </form>
        {message && <p className="mt-4 text-sm text-emerald-600">{message}</p>}
      </section>

      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <h2 className="text-xl font-semibold text-slate-900">Product Inventory</h2>
        <div className="mt-4 overflow-x-auto">
          <table className="w-full min-w-max divide-y divide-slate-200 text-left text-sm text-slate-700">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3">Code</th>
                <th className="px-4 py-3">Product</th>
                <th className="px-4 py-3">Quantity Sold</th>
                <th className="px-4 py-3">Unit Price</th>
                <th className="px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {products.map((product) => (
                <tr key={product._id}>
                  <td className="px-4 py-3">{product.productCode}</td>
                  <td className="px-4 py-3">{product.productName}</td>
                  <td className="px-4 py-3">{product.quantitySold}</td>
                  <td className="px-4 py-3">{product.unitPrice}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <button
                        type="button"
                        onClick={() => handleEdit(product)}
                        className="rounded-full bg-amber-500 px-3 py-1 text-sm font-semibold text-slate-950 hover:bg-amber-400"
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        onClick={() => handleDelete(product._id)}
                        className="rounded-full bg-red-500 px-3 py-1 text-sm font-semibold text-white hover:bg-red-400"
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
