 import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

function Product() {

    const [products, setProducts] = useState([]);

    const [productCode, setProductCode] = useState('');
    const [productName, setProductName] = useState('');
    const [category, setCategory] = useState('');
    const [unitPrice, setUnitPrice] = useState('');
    const [quantity, setQuantity] = useState('');
    const [reorderLevel, setReorderLevel] = useState('5');

    const [editId, setEditId] = useState(null);
    const [message, setMessage] = useState('');

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

    // CLEAR FORM
    const clearForm = () => {
        setProductCode('');
        setProductName('');
        setCategory('');
        setUnitPrice('');
        setQuantity('');
        setReorderLevel('5');
    };

    // GET PRODUCTS
    const getProducts = async () => {
        try {

            const res = await axios.get(
                'http://localhost:5001/api/spareparts/list',
                { headers }
            );

            setProducts(res.data);

        } catch (err) {
            console.log(err);
        }
    };

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

    // CREATE + UPDATE
    const handleSubmit = async (e) => {
        e.preventDefault();
        try {

            if (editId) {
                // UPDATE
                await axios.put(
                    `http://localhost:5001/api/spareparts/${editId}`,
                    { partCode: productCode, partName: productName, category, unitPrice, quantity, reorderLevel },
                    { headers }
                );
                setMessage('Spare part updated');
            } else {
                // CREATE (Added missing else block and API request)
                await axios.post(
                    'http://localhost:5001/api/spareparts/add',
                    { partCode: productCode, partName: productName, category, unitPrice, quantity, reorderLevel },
                    { headers }
                );
                setMessage('Spare part added');
            }

            clearForm();
            setEditId(null);
            getProducts();

        } catch (err) {
            console.log(err);
        }
    };

    // DELETE
    const handleDelete = async (id) => {
        try {

            await axios.delete(
                `http://localhost:5001/api/spareparts/${id}`,
                { headers }
            );

            getProducts();

        } catch (err) {
            console.log(err);
        }
    };

    // EDIT
    const handleEdit = (product) => {

        setProductCode(product.partCode);
        setProductName(product.partName);
        setCategory(product.category);
        setUnitPrice(product.unitPrice);
        setQuantity(product.quantity);
        setReorderLevel(product.reorderLevel || '5');
        setEditId(product._id);
    };

    return (
        <div className="max-w-2xl mx-auto p-4">
            <div className='mt-3 mb-6 '>
                <Link to="/dashboard"
                    type="button"
                    className=" font-medium hover:text-white border border-slate-600 rounded-lg px-3 py-2 hover:bg-slate-800 transition-colors"
                >
                    BACK
                </Link>
            </div>
            <h1 className="text-2xl font-bold mb-4">
                Spare Part Management
            </h1>

            {message && (
                <p className="mb-3 text-green-600">
                    {message}
                </p>
            )}

            {/* FORM */}
            <form
                onSubmit={handleSubmit}
                className="border p-4 rounded space-y-3"
            >

                <input
                    type="text"
                    placeholder="Spare Part Code"
                    value={productCode}
                    onChange={(e) =>
                        setProductCode(e.target.value)
                    }
                    className="w-full border p-2 rounded"
                    required
                />

                <input
                    type="text"
                    placeholder="Spare Part Name"
                    value={productName}
                    onChange={(e) =>
                        setProductName(e.target.value)
                    }
                    className="w-full border p-2 rounded"
                    required
                />

                <input
                    type="text"
                    placeholder="Category"
                    value={category}
                    onChange={(e) =>
                        setCategory(e.target.value)
                    }
                    className="w-full border p-2 rounded"
                    required
                />

                <input
                    type="text"
                    placeholder="Unit Price"
                    value={unitPrice}
                    onChange={(e) =>
                        setUnitPrice(e.target.value)
                    }
                    className="w-full border p-2 rounded"
                    required
                />

                <input
                    type="number"
                    placeholder="Quantity"
                    value={quantity}
                    onChange={(e) =>
                        setQuantity(e.target.value)
                    }
                    className="w-full border p-2 rounded"
                    required
                />

                <input
                    type="number"
                    placeholder="Reorder Level"
                    value={reorderLevel}
                    onChange={(e) =>
                        setReorderLevel(e.target.value)
                    }
                    className="w-full border p-2 rounded"
                    required
                />


                <button
                    type="submit"
                    className="bg-blue-500 text-white px-4 py-2 rounded"
                >
                    {editId ? 'Update' : 'Add'}
                </button>

            </form>

            {/* PRODUCTS */}
            <div className="mt-6 space-y-3">

                {products.map((product) => (

                    <div
                        key={product._id}
                        className="border p-3 rounded"
                    >

                        <p>Code: {product.partCode}</p>
                        <p>Name: {product.partName}</p>
                        <p>Category: {product.category}</p>
                        <p>Price: {product.unitPrice}</p>
                        <p>Quantity: {product.quantity}</p>

                        <p>Reorder Level: {product.reorderLevel}</p>

                        <div className="flex gap-3 mt-2">

                            <button
                                onClick={() => handleEdit(product)}
                                className="text-blue-500"
                            >
                                Edit
                            </button>

                            <button
                                onClick={() => handleDelete(product._id)}
                                className="text-red-500"
                            >
                                Delete
                            </button>

                        </div>

                    </div>

                ))}

            </div>

        </div>
    );
}

export default Product;
