import { useEffect, useState } from 'react';
import {
  createProduct,
  getAllProducts,
  updateProduct,
  deleteProduct,
} from '../services/apiService';

const emptyForm = () => ({
  productCode: '',
  productName: '',
  category: '',
  quantityInStock: '',
  unitPrice: '',
  supplierName: '',
  dateReceived: new Date().toISOString().split('T')[0],
});

const ProductPage = () => {
  const [formData, setFormData] = useState(emptyForm());
  const [products, setProducts] = useState([]);

  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);

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

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

  const fetchProducts = async () => {
    try {
      const response = await getAllProducts();
      setProducts(response.data);
    } catch (err) {
      setError(err.response?.data?.message || 'Error fetching products');
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;

    setFormData((prev) => ({
      ...prev,
      [
        name === 'quantityInStock' || name === 'unitPrice'
          ? name
          : name
      ]: name === 'quantityInStock' || name === 'unitPrice' ? (parseFloat(value) || '') : value,
    }));
  };

  const resetForm = () => {
    setFormData(emptyForm());
    setEditingId(null);
    setError('');
    setSuccess('');
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setSuccess('');

    try {
      if (editingId) {
        await updateProduct(editingId, formData);
        setSuccess('Product updated successfully!');
      } else {
        await createProduct(formData);
        setSuccess('Product created successfully!');
      }

      resetForm();
      await fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Error saving product');
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (product) => {
    setEditingId(product._id);
    setFormData({
      productCode: product.productCode || '',
      productName: product.productName || '',
      category: product.category || '',
      quantityInStock: product.quantityInStock ?? '',
      unitPrice: product.unitPrice ?? '',
      supplierName: product.supplierName || '',
      dateReceived: product.dateReceived
        ? new Date(product.dateReceived).toISOString().split('T')[0]
        : new Date().toISOString().split('T')[0],
    });
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Are you sure you want to delete this product?')) return;

    setLoading(true);
    setError('');
    setSuccess('');

    try {
      await deleteProduct(id);
      setSuccess('Product deleted successfully!');
      resetForm();
      await fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Error deleting product');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-7xl mx-auto p-4 sm:p-6">
      <h2 className="text-2xl sm:text-3xl font-bold mb-6 text-gray-800">Product Management</h2>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-1">
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-xl font-bold mb-4 text-gray-800">
              {editingId ? 'Edit Product' : 'Add New Product'}
            </h3>

            {error && (
              <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">{error}</div>
            )}
            {success && (
              <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">{success}</div>
            )}

            <form onSubmit={handleSubmit} className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Product Code</label>
                <input
                  type="text"
                  name="productCode"
                  value={formData.productCode}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                  required
                />
              </div>
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Product Name</label>
                <input
                  type="text"
                  name="productName"
                  value={formData.productName}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                  required
                />
              </div>
              <div className="sm:col-span-2">
                <label className="block text-gray-700 text-sm font-bold mb-2">Category</label>
                <input
                  type="text"
                  name="category"
                  value={formData.category}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                  required
                />
              </div>

              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Quantity</label>
                <input
                  type="number"
                  name="quantityInStock"
                  value={formData.quantityInStock}
                  onChange={handleChange}
                  min="0"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                  required
                />
              </div>
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Unit Price (RWF)</label>
                <input
                  type="number"
                  name="unitPrice"
                  value={formData.unitPrice}
                  onChange={handleChange}
                  step="0.01"
                  min="0"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                  required
                />
              </div>

              <div className="sm:col-span-2">
                <label className="block text-gray-700 text-sm font-bold mb-2">Supplier Name</label>
                <input
                  type="text"
                  name="supplierName"
                  value={formData.supplierName}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                  required
                />
              </div>

              <div className="sm:col-span-2">
                <label className="block text-gray-700 text-sm font-bold mb-2">Date Received</label>
                <input
                  type="date"
                  name="dateReceived"
                  value={formData.dateReceived}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                  required
                />
              </div>

              <div className="sm:col-span-2">
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full bg-blue-600 text-white font-bold py-2 rounded-lg hover:bg-blue-700 transition disabled:opacity-50"
                >
                  {loading ? 'Saving...' : editingId ? 'Update Product' : 'Create Product'}
                </button>
              </div>

              {editingId && (
                <div className="sm:col-span-2">
                  <button
                    type="button"
                    onClick={resetForm}
                    disabled={loading}
                    className="w-full bg-gray-600 text-white font-bold py-2 rounded-lg hover:bg-gray-700 transition disabled:opacity-50"
                  >
                    Cancel
                  </button>
                </div>
              )}
            </form>
          </div>
        </div>

        <div className="lg:col-span-2">
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-xl font-bold mb-4 text-gray-800">Product Records</h3>

            {products.length ? (
              <div className="overflow-x-auto">
                <table className="w-full border-collapse text-sm">
                  <thead>
                    <tr className="bg-gray-200">
                      <th className="border px-3 py-2 text-left">Code</th>
                      <th className="border px-3 py-2 text-left">Name</th>
                      <th className="border px-3 py-2 text-left">Category</th>
                      <th className="border px-3 py-2 text-right">Qty</th>
                      <th className="border px-3 py-2 text-right">Unit Price</th>
                      <th className="border px-3 py-2 text-left">Supplier</th>
                      <th className="border px-3 py-2">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {products.map((p) => (
                      <tr key={p._id} className="hover:bg-gray-100">
                        <td className="border px-3 py-2">{p.productCode}</td>
                        <td className="border px-3 py-2">{p.productName}</td>
                        <td className="border px-3 py-2">{p.category}</td>
                        <td className="border px-3 py-2 text-right font-bold">{p.quantityInStock}</td>
                        <td className="border px-3 py-2 text-right">{p.unitPrice}</td>
                        <td className="border px-3 py-2">{p.supplierName}</td>
                        <td className="border px-3 py-2 whitespace-nowrap">
                          <button
                            onClick={() => handleEdit(p)}
                            className="bg-yellow-500 text-white px-3 py-1 rounded text-xs hover:bg-yellow-600 mr-2"
                          >
                            Edit
                          </button>
                          <button
                            onClick={() => handleDelete(p._id)}
                            className="bg-red-600 text-white px-3 py-1 rounded text-xs hover:bg-red-700"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-gray-600">No products found.</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProductPage;

