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

function Sale(){
    const [sale, setSale] = useState([])
    const [customer, setCustomer] = useState('')
    const [product, setProduct] = useState('')
    const [user, setUser] = useState('')
    const [invoiceNumber, setInvoiceNumber] = useState('')
    const [salesDate, setSalesDate]= useState('')
    const [paymentMethod, setPaymentMethod] = useState('')
    const [totalAmountPaid, setTotalAmountPaid] = useState('')
    const [editId, setEditId] = useState(null)
    const [error, setError] = useState('')

    // --- NEW: dropdown data ---
    const [customers, setCustomers] = useState([])
    const [products, setProducts] = useState([])
    const [users, setUsers] = useState([])

    const fetchSale = async () => {
        try{
            const res = await axios.get('http://localhost:5000/api/sale');
            setSale(res.data);
        }catch(error){
            setError("failed to get Sale")
        }
    }

    // --- NEW: fetch dropdown data ---
    const fetchDropdowns = async () => {
        try {
            const [custRes, prodRes, userRes] = await Promise.all([
                axios.get('http://localhost:5000/api/customer'),
                axios.get('http://localhost:5000/api/product'),
                axios.get('http://localhost:5000/api/user'),
            ]);
            setCustomers(custRes.data);
            setProducts(prodRes.data);
            setUsers(userRes.data);
        } catch (error) {
            setError("Failed to load dropdown data")
        }
    }

    useEffect(() => {
        fetchSale()
        fetchDropdowns()   // --- NEW ---
    },[])

    const handleSale = async (e) => {
        e.preventDefault()
        setError('')
       try{
            if(editId){
                await axios.put(`http://localhost:5000/api/sale/${editId}`,{
                    invoiceNumber:Number(invoiceNumber),
                    salesDate,
                    paymentMethod,
                    totalAmountPaid:Number(totalAmountPaid),
                    user,
                    product,
                    customer
                });
                setEditId(null)
            }else {
                await axios.post('http://localhost:5000/api/sale',{
                    invoiceNumber:Number(invoiceNumber),
                    salesDate,
                    paymentMethod,
                    totalAmountPaid:Number(totalAmountPaid),
                    user,
                    product,
                    customer
                });
            }
            setInvoiceNumber('')
            setSalesDate('')
            setPaymentMethod('')
            setTotalAmountPaid('')
            setUser('')
            setCustomer('')
            setProduct('')
            fetchSale()
       }catch(error){
            setError("failed ")
       }
    };

    const handleDelete = async (id) =>{
        try{
            await axios.delete(`http://localhost:5000/api/sale/${id}`);
            fetchSale()
        }catch(error){
            setError("faild to delete")
        }
    };

    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">Sales</h2>
                
                <form onSubmit={handleSale} 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">Invoice Number</label>
                        <input type="number" value={invoiceNumber} required className="border border-slate-300 p-2 rounded" onChange={(e) => setInvoiceNumber(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Sales Date</label>
                        <input type="date" value={salesDate} required className="border border-slate-300 p-2 rounded" onChange={(e) => setSalesDate(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Payment Method</label>
                        <input type="text" value={paymentMethod} required className="border border-slate-300 p-2 rounded" onChange={(e) => setPaymentMethod(e.target.value)} />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Toatal amount Paid</label>
                        <input type="number" value={totalAmountPaid} required className="border border-slate-300 p-2 rounded" onChange={(e) => setTotalAmountPaid(e.target.value)} />
                    </div>

                    {/* --- CHANGED: Customer select --- */}
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Customer</label>
                        <select value={customer} required className="border border-slate-300 p-2 rounded bg-white" onChange={(e) => setCustomer(e.target.value)}>
                            <option value="">-- Select Customer --</option>
                            {customers.map((c) => (
                                <option key={c._id} value={c._id}>{c.firstName} {c.lastName}</option>
                            ))}
                        </select>
                    </div>

                    {/* --- CHANGED: Product select --- */}
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Product</label>
                        <select value={product} required className="border border-slate-300 p-2 rounded bg-white" onChange={(e) => setProduct(e.target.value)}>
                            <option value="">-- Select Product --</option>
                            {products.map((p) => (
                                <option key={p._id} value={p._id}>{p.productName}</option>
                            ))}
                        </select>
                    </div>

                    {/* --- CHANGED: User select --- */}
                    <div className="flex flex-col gap-1 lg:col-span-2">
                        <label className="text-sm font-semibold text-slate-600">User</label>
                        <select value={user} required className="border border-slate-300 p-2 rounded bg-white" onChange={(e) => setUser(e.target.value)}>
                            <option value="">-- Select User --</option>
                            {users.map((u) => (
                                <option key={u._id} value={u._id}>{u.username}</option>
                            ))}
                        </select>
                    </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">
                            {editId ? 'Update' : 'Add'}
                        </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">InvoiceNumber</th>
                            <th className="p-3">Sales Date</th>
                            <th className="p-3">PaymentMethod</th>
                            <th className="p-3">totalAmountPaid</th>
                            <th className="p-3">User</th>
                            <th className="p-3">customer</th>
                            <th className="p-3">product</th>
                            <th className="p-3 text-center" colSpan="2">Action</th>
                        </tr>
                    </thead>
                    <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                        {Array.isArray(sale) && sale.map((sl) => (
                            <tr key={sl._id} className="hover:bg-slate-50">
                                <td className="p-3 font-semibold">{sl.invoiceNumber}</td>
                                <td className="p-3">{sl.salesDate ? sl.salesDate.substring(0,10):""}</td>
                                <td className="p-3">{sl.paymentMethod}</td>
                                <td className="p-3">${sl.totalAmountPaid}</td>
                                <td className="p-3">{sl.user?.username || sl.user}</td>
                                <td className="p-3">{sl.customer?.firstName || sl.customer}</td>
                                <td className="p-3">{sl.product?.productName || sl.product}</td>
                                <td className="p-3 text-right">
                                    <button 
                                        onClick={() => {
                                            setEditId(sl._id);
                                            setInvoiceNumber(sl.invoiceNumber);
                                            setSalesDate(sl.salesDate ? sl.salesDate.substring(0,10): "");
                                            setPaymentMethod(sl.paymentMethod);
                                            setTotalAmountPaid(sl.totalAmountPaid);
                                            setUser(sl.user?._id || sl.user);
                                            setCustomer(sl.customer?._id || sl.customer);
                                            setProduct(sl.product?._id || sl.product);
                                        }}
                                        className="text-blue-600 hover:text-blue-800 font-semibold"
                                    >
                                        Edit
                                    </button>
                                </td>
                                <td className="p-3 text-left">
                                    <button 
                                        onClick={() => handleDelete(sl._id)}
                                        className="text-red-600 hover:text-red-800 font-semibold"
                                    >
                                        Delete
                                    </button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>

        </div>
    )
}
export default Sale