 import { useState, useEffect } from "react";
import axios from '../axiosInstance';

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

    const fetchProducts = async () => {
        try {
            const res = await axios.get('http://localhost:5000/api/product');
            setProducts(res.data);
        } catch(error) {
            setError("Failed to fetch product data.");
        }
    };

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

    const handleProduct = async (e) => {
        e.preventDefault();
        try {
            await axios.post('http://localhost:5000/api/product', {
                productCode,
                productName,
                category,
                quantityInStock: Number(quantityInStock),
                unitPrice: Number(unitPrice),
                supplierName,
                dateReceived
            });
            
            // Fixed: Set back to an empty string instead of clearing the state type
            setProductCode(''); 
            setProductName('');
            setCategory('');
            setQuantityInStock('');
            setUnitPrice('');
            setSupplierName('');
            setDateReceived('');
            fetchProducts();
        } catch(error) {
            setError("Failed to add product.");
        }
    };

    return (
        <div className="p-6 bg-slate-50 min-h-screen flex flex-col gap-6">
            
            {/* Form Section */}
            <div className="bg-white p-6 rounded shadow-sm border border-slate-200">
                <h2 className="text-xl font-bold text-slate-700 mb-4">Add New Product</h2>
                
                <form onSubmit={handleProduct} className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Product Code</label>
                        <input type="text" value={productCode} required className="border border-slate-300 p-2 rounded" onChange={(e) => setProductCode(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Product Name</label>
                        <input type="text" value={productName} required className="border border-slate-300 p-2 rounded" onChange={(e) => setProductName(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Category</label>
                        <input type="text" value={category} required className="border border-slate-300 p-2 rounded" onChange={(e) => setCategory(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Quantity In Stock</label>
                        <input type="number" value={quantityInStock} required className="border border-slate-300 p-2 rounded" onChange={(e) => setQuantityInStock(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Unit Price</label>
                        <input type="number" value={unitPrice} required className="border border-slate-300 p-2 rounded" onChange={(e) => setUnitPrice(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Supplier Name</label>
                        <input type="text" value={supplierName} required className="border border-slate-300 p-2 rounded" onChange={(e) => setSupplierName(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1 lg:col-span-2">
                        <label className="text-sm font-semibold text-slate-600">Date Received</label>
                        <input type="date" value={dateReceived} required className="border border-slate-300 p-2 rounded" onChange={(e) => setDateReceived(e.target.value)} />
                    </div>
                    <div className="flex items-end">
                        <button type="submit" className="w-full bg-blue-500 text-white font-bold p-2 rounded hover:bg-blue-600 transition h-10">Add Product</button>
                    </div>
                </form>

                {error && (
                    <p className="text-red-500 bg-red-100 p-2 rounded text-sm font-semibold mt-4 text-center">{error}</p>
                )}
            </div>

            {/* Table Section */}
            <div className="bg-white rounded shadow-sm border border-slate-200 overflow-x-auto">
                <table className="w-full text-left border-collapse">
                    <thead>
                        <tr className="bg-slate-100 border-b border-slate-200 text-slate-700 text-sm font-bold">
                            <th className="p-3">Product Code</th>
                            <th className="p-3">Product Name</th>
                            <th className="p-3">Category</th>
                            <th className="p-3">Quantity</th>
                            <th className="p-3">Unit Price</th>
                            <th className="p-3">Supplier Name</th>
                            <th className="p-3">Date</th>
                        </tr>
                    </thead>
                    <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                        {Array.isArray(products) && products.map((prod) => (
                            <tr key={prod._id} className="hover:bg-slate-50">
                                <td className="p-3 font-semibold">{prod.productCode}</td>
                                <td className="p-3">{prod.productName}</td>
                                <td className="p-3">{prod.category}</td>
                                <td className="p-3">{prod.quantityInStock}</td>
                                <td className="p-3">${prod.unitPrice}</td>
                                <td className="p-3">{prod.supplierName}</td>
                                {/* Fixed typo: substring instead of subString */}
                                <td className="p-3">{prod.dateReceived ? prod.dateReceived.substring(0, 10) : (prod.date ? prod.date.substring(0, 10) : "")}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>

        </div>
    );
}
export default Product;
