import { useEffect, useState } from 'react';
import axios from 'axios';
import AppLayout from '../components/AppLayout';

const API_BASE = 'http://localhost:1000/api/product';

function Product() {
  const [products, setProducts] = useState([]);
  const [productCode, setProductCode] = useState('');
  const [productName, setProductName] = useState('');
  const [category, setCategory] = useState('');
  const [unitPrice, setUnitPrice] = useState('');
  const [quantityInStock, setQuantityInStock] = useState('');
  const [supplierName, setSupplierName] = useState('');
  const [dateReceived, setDateReceived] = useState('');
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [editingId, setEditingId] = useState(null);

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const clearForm = () => {
    setProductCode('');
    setProductName('');
    setCategory('');
    setUnitPrice('');
    setQuantityInStock('');
    setSupplierName('');
    setDateReceived('');
    setEditingId(null);
  };

  const fetchProducts = async () => {
    try {
      const response = await axios.get(`${API_BASE}/getproduct`, { headers });
      setProducts(response.data);
    } catch (err) {
      setError('Failed to load products');
      console.error(err);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setMessage('');

    try {
      if (editingId) {
        await axios.put(
          `${API_BASE}/updateproduct/${editingId}`,
          {
            productCode,
            productName,
            category,
            unitPrice,
            quantityInStock,
            supplierName,
            dateReceived,
          },
          { headers }
        );
        setMessage('Product updated successfully');
      } else {
        await axios.post(
          `${API_BASE}/addproduct`,
          {
            productCode,
            productName,
            category,
            unitPrice,
            quantityInStock,
            supplierName,
            dateReceived,
          },
          { headers }
        );
        setMessage('Product added successfully');
      }
      clearForm();
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to save product');
      console.error(err);
    }
  };

  const handleEdit = (product) => {
    setEditingId(product._id);
    setProductCode(product.productCode || '');
    setProductName(product.productName || '');
    setCategory(product.category || '');
    setUnitPrice(product.unitPrice || '');
    setQuantityInStock(product.quantityInStock || '');
    setSupplierName(product.supplierName || '');
    setDateReceived(product.dateReceived ? product.dateReceived.split('T')[0] : '');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`${API_BASE}/deleteproduct/${id}`, { headers });
      setMessage('Product deleted successfully');
      fetchProducts();
    } catch (err) {
      setError('Failed to delete product');
      console.error(err);
    }
  };

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

  return (
    <AppLayout title="Product management" subtitle="Inventory">
      <div className="mx-auto max-w-6xl space-y-6">
        <div className="card space-y-4 p-5">
          {message && <p className="alert-success">{message}</p>}
          {error && <p className="alert-error">{error}</p>}

          <form onSubmit={handleSubmit} className="space-y-3">
            <h2 className="text-lg font-semibold text-slate-800">
              {editingId ? 'Edit product' : 'Add new product'}
            </h2>
            <div className="grid gap-4 sm:grid-cols-2">
              <input
                type="text"
                placeholder="Product code"
                value={productCode}
                onChange={(e) => setProductCode(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="text"
                placeholder="Product name"
                value={productName}
                onChange={(e) => setProductName(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="text"
                placeholder="Category"
                value={category}
                onChange={(e) => setCategory(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="number"
                placeholder="Unit price"
                value={unitPrice}
                onChange={(e) => setUnitPrice(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="number"
                placeholder="Quantity in stock"
                value={quantityInStock}
                onChange={(e) => setQuantityInStock(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="text"
                placeholder="Supplier name"
                value={supplierName}
                onChange={(e) => setSupplierName(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="date"
                value={dateReceived}
                onChange={(e) => setDateReceived(e.target.value)}
                className="input-field"
                required
              />
            </div>
            <div className="flex flex-wrap gap-3">
              <button type="submit" className="btn-primary">
                {editingId ? 'Save changes' : 'Add product'}
              </button>
              {editingId && (
                <button type="button" onClick={clearForm} className="btn-secondary">
                  Cancel
                </button>
              )}
            </div>
          </form>
        </div>

        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-800">Products</h2>
          {products.length === 0 ? (
            <p className="mt-4 text-sm text-slate-500">No products available yet.</p>
          ) : (
            <div className="mt-4 overflow-x-auto">
              <table className="min-w-full divide-y divide-slate-200 text-sm">
                <thead>
                  <tr className="bg-slate-50 text-left text-slate-600">
                    <th className="px-4 py-3">Code</th>
                    <th className="px-4 py-3">Name</th>
                    <th className="px-4 py-3">Category</th>
                    <th className="px-4 py-3">Price</th>
                    <th className="px-4 py-3">Stock</th>
                    <th className="px-4 py-3">Supplier</th>
                    <th className="px-4 py-3">Received</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} className="hover:bg-slate-50">
                      <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.category}</td>
                      <td className="px-4 py-3">{product.unitPrice}</td>
                      <td className="px-4 py-3">{product.quantityInStock}</td>
                      <td className="px-4 py-3">{product.supplierName}</td>
                      <td className="px-4 py-3">{product.dateReceived?.split('T')[0] || '-'}</td>
                      <td className="px-4 py-3 space-x-2">
                        <button
                          type="button"
                          onClick={() => handleEdit(product)}
                          className="btn-secondary"
                        >
                          Edit
                        </button>
                        <button
                          type="button"
                          onClick={() => handleDelete(product._id)}
                          className="btn-danger"
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </AppLayout>
  );
}

export default Product;
