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

function StockTransaction () {
    const [stockTransaction, setStocktransaction] = useState([]);
    const [transactionDate, setTransactionDate] = useState('');
    const [quantityMoved, setQuantityMoved] = useState('');
    const [transactionType, setTransactionType] = useState('');
    const [editId, setEditId] = useState(null);
    const [error, setError] = useState('');

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

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

    const handleStockTransaction = async (e) => {
        e.preventDefault();
        setError('');
        try {
            if(editId) {
                await axios.put(`http://localhost:5000/api/stockTransaction/${editId}`, {
                    quantityMoved: Number(quantityMoved), 
                    transactionDate,
                    transactionType
                });
                setEditId(null);
            } else {
                await axios.post('http://localhost:5000/api/stockTransaction', {
                    transactionDate,
                    quantityMoved: Number(quantityMoved),
                    transactionType
                });
            }

            setQuantityMoved('');
            setTransactionDate('');
            setTransactionType('');
            fetchStockTransaction();
        } catch(error) {
            setError("Failed to save transaction");
        }
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`http://localhost:5000/api/stockTransaction/${id}`);
            fetchStockTransaction();
        } catch(error) {
            setError("Failed to delete stock record");
        }
    };

    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">
                    {editId ? "Edit Transaction" : "Stock Transaction Management"}
                </h2>
                
                <form onSubmit={handleStockTransaction} className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Transaction Date</label>
                        <input 
                            type="date" 
                            value={transactionDate ? transactionDate.substring(0, 10) : ''} 
                            required
                            className="border border-slate-300 p-2 rounded focus:outline-none focus:border-blue-500"
                            onChange={(e) => setTransactionDate(e.target.value)} 
                        />
                    </div>

                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Quantity Moved</label>
                        <input 
                            type="number" 
                            placeholder="Enter quantity" 
                            required 
                            value={quantityMoved} 
                            className="border border-slate-300 p-2 rounded focus:outline-none focus:border-blue-500"
                            onChange={(e) => setQuantityMoved(e.target.value)} 
                        />
                    </div>

                    <div className="flex flex-col gap-1">
                        <label className="text-sm font-semibold text-slate-600">Transaction Type</label>
                        <input 
                            type="text" 
                            placeholder="Stock In or Stock Out" 
                            required
                            value={transactionType} 
                            className="border border-slate-300 p-2 rounded focus:outline-none focus:border-blue-500"
                            onChange={(e) => setTransactionType(e.target.value)} 
                        />
                    </div>

                    <div className="md:col-span-3 flex justify-between items-center mt-2">
                        {editId && (
                            <button 
                                type="button" 
                                className="bg-slate-400 text-white px-4 py-2 rounded hover:bg-slate-500 text-sm"
                                onClick={() => {
                                    setEditId(null);
                                    setQuantityMoved('');
                                    setTransactionDate('');
                                    setTransactionType('');
                                }}
                            >
                                Cancel Edit
                            </button>
                        )}
                        <button 
                            type="submit" 
                            className={`px-6 py-2 rounded font-bold text-white ml-auto ${editId ? 'bg-orange-500 hover:bg-orange-600' : 'bg-blue-500 hover:bg-blue-600'}`}
                        >
                            {editId ? "Update Transaction" : "Add Transaction"}
                        </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">Transaction Date</th>
                            <th className="p-3">Quantity Moved</th>
                            <th className="p-3">Transaction Type</th>
                            <th className="p-3 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                        {Array.isArray(stockTransaction) && stockTransaction.map((tx) => (
                            <tr key={tx._id} className="hover:bg-slate-50">
                                <td className="p-3">{tx.transactionDate ? tx.transactionDate.substring(0, 10) : ""}</td>
                                <td className="p-3 font-semibold">{tx.quantityMoved}</td>
                                <td className="p-3">
                                    <span className={`px-2 py-0.5 rounded text-xs font-bold ${tx.transactionType?.toLowerCase().includes('in') ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'}`}>
                                        {tx.transactionType}
                                    </span>
                                </td>
                                <td className="p-3 text-right flex justify-end gap-2">
                                    <button 
                                        className="bg-slate-200 text-slate-700 px-3 py-1 rounded text-xs font-semibold hover:bg-slate-300"
                                        onClick={() => {
                                            setEditId(tx._id);
                                            setTransactionDate(tx.transactionDate);
                                            setTransactionType(tx.transactionType);
                                            setQuantityMoved(tx.quantityMoved);
                                        }}
                                    >
                                        Edit
                                    </button>
                                    <button 
                                        className="bg-red-100 text-red-600 px-3 py-1 rounded text-xs font-semibold hover:bg-red-200"
                                        onClick={() => handleDelete(tx._id)}
                                    >
                                        Delete
                                    </button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>

        </div>
    );
}
export default StockTransaction;
