import React, {
    useState,
    useEffect,
    useRef,
    forwardRef,
    useImperativeHandle,
} from "react";

import axios from "axios";

const API_URL = import.meta.env.VITE_API_URL;

const ItemComboBox = forwardRef(({ onSelectItem }, ref) => {
    const [inputValue, setInputValue] = useState("");
    const [isOpen, setIsOpen] = useState(false);
    const [getItem, setGetItems] = useState([]);
    const [selectedItem, setSelectedItem] = useState(null);
    const [formValues, setFormValues] = useState({
        qty: "",
        initialCost: "",
        vatAmount: "",
        ssclAmount: "",
        finalCost: "",
        salesPrice: "",
        margin: "",
        marginPercentage: "",
    });
    const [sscl_percentage, setSsclPercentage] = useState(0);
    const [vat_percentage, setVatPercentage] = useState(0);
    const [errors, setErrors] = useState({
        itemName: false,
        qty: false,
        initialCost: false,
        salesPrice: false,
    });
    const comboRef = useRef(null);

    useImperativeHandle(ref, () => ({
        resetFields() {
            setInputValue("");
            setFormValues({
                itemName: "",
                qty: "",
                initialCost: "",
                vatAmount: "",
                ssclAmount: "",
                finalCost: "",
                salesPrice: "",
                margin: "",
                marginPercentage: "",
            });
            setSelectedItem(null);
            setErrors({
                qty: false,
                itemName: false,
                initialCost: false,
                salesPrice: false,
            });
        },
        validateFields() {
            const newErrors = {
                itemName: !inputValue.trim(),
                qty: !formValues.qty || parseFloat(formValues.qty) <= 0,
                initialCost: !formValues.initialCost || parseFloat(formValues.initialCost) <= 0,
                salesPrice: !formValues.salesPrice || parseFloat(formValues.salesPrice) <= 0,
            };
    
            setErrors(newErrors);
    
            // Return true if valid
            return !Object.values(newErrors).some(Boolean);
        },
    }));
    

    // Fetch items from the API
    useEffect(() => {
        if (inputValue.trim().length < 2) {
            setGetItems([]); // Clear list when input has less than 2 characters
            return;
        }

        const fetchItems = async () => {
            try {
                const response = await axios.post(
                    `${API_URL}/items/searchbox`,
                    {
                        search: inputValue,
                    }
                );
                setGetItems(response.data);
            } catch (error) {
                console.error("Error fetching items:", error);
            }
        };

        // Debounce API calls
        const delayDebounce = setTimeout(fetchItems, 300);

        return () => clearTimeout(delayDebounce);
    }, [inputValue]);

    const handleInputChange = (event) => {
        setInputValue(event.target.value);
        setIsOpen(true);

        if (event.target.value.trim() !== "") {
            setErrors((prevErrors) => ({
                ...prevErrors,
                itemName: false, // Clear the error for itemName
            }));
        }
    };

    const getVariableSettings = async () => {
        try {
            const response = await axios.get(
                `${API_URL}/variableSettings/index`
            );
            if (response.data) {
                setSsclPercentage(response.data.sscl_percentage);
                setVatPercentage(response.data.vat_percentage);
            }
        } catch (error) {
            console.error("Error fetching variable settings:", error);
        }
    };

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

    const handleFormChange = (e) => {
        const { id, value } = e.target;
        const updatedForm = { ...formValues, [id]: value };

        // Validation: check required fields
        const updatedErrors = { ...errors };
        if (["itemName", "qty", "initialCost", "salesPrice"].includes(id)) {
            updatedErrors[id] =
                value.trim() === "" || isNaN(value) || parseFloat(value) <= 0;
            setErrors(updatedErrors);
        }

        // Parse values for calculation
        const initialCost = parseFloat(updatedForm.initialCost) || 0;
        const salesPrice = parseFloat(updatedForm.salesPrice) || 0;

        // Perform calculations
        const vatAmount = +((initialCost * vat_percentage) / 100).toFixed(4);
        const ssclAmount = +((initialCost * sscl_percentage) / 100).toFixed(4);
        const finalCost = +(initialCost + vatAmount + ssclAmount).toFixed(4);
        const margin = +(salesPrice - finalCost).toFixed(4);
        const marginPercentage =
            salesPrice > 0 ? +((margin / salesPrice) * 100).toFixed(2) : 0;

        updatedForm.vatAmount = vatAmount;
        updatedForm.ssclAmount = ssclAmount;
        updatedForm.finalCost = finalCost;
        updatedForm.margin = margin;
        updatedForm.marginPercentage = marginPercentage;

        setFormValues(updatedForm);

        if (selectedItem) {
            onSelectItem({
                ...selectedItem,
                ...updatedForm,
            });
        }
    };

    

    const handleSelect = (option) => {
        setInputValue(option);
        setIsOpen(false);
        setSelectedItem(
            getItem.find((item) => item.bar_code === option.split(" - ")[0])
        );
        setFormValues({
            qty: "",
            initialCost: "",
            vatAmount: "",
            ssclAmount: "",
            finalCost: "",
            salesPrice: "",
            margin: "",
            marginPercentage: "",
        });
    };

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (comboRef.current && !comboRef.current.contains(event.target)) {
                setIsOpen(false);
            }
        };

        document.addEventListener("mousedown", handleClickOutside);
        return () =>
            document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    return (
        <>
            <div className="flex flex-col bg-gray-100" ref={comboRef}>
                <div className="relative w-full">
                    <input
                        type="text"
                        id="itemName"
                        value={inputValue}
                        onChange={handleInputChange}
                        placeholder="Type or select an item..."
                        className={`py-2.5 px-4 block w-full border ${
                            errors.itemName ? "border-red-500" : "border-gray-200"
                        } rounded-lg sm:text-sm`}
                        onFocus={() => setIsOpen(true)}
                        required
                    />
                    {errors.itemName && (
                        <p className="text-red-500 text-xs mt-1">
                            Item Name is required
                        </p>
                    )}

                    {isOpen && getItem.length > 0 && (
                        <div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto">
                            {/* Table Header */}
                            <div className="flex px-4 py-2 text-sm font-semibold text-gray-500 bg-blue-200 border-b border-blue-300">
                                <div className="w-20">Barcode</div>
                                <div className="w-3/6">Item Name</div>
                            </div>

                            {/* List of Items */}
                            <ul>
                                {getItem.map((item, index) => (
                                    <li
                                        key={index}
                                        onClick={() =>
                                            handleSelect(
                                                `${item.bar_code} - ${item.item_name}`
                                            )
                                        }
                                        className="flex px-4 py-2 cursor-pointer hover:bg-gray-100"
                                    >
                                        <div className="w-20">
                                            {item.bar_code}
                                        </div>
                                        <div className="w-3/6">
                                            {item.item_name}
                                        </div>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    )}
                </div>
            </div>
            <div className="grid lg:grid-cols-4 md:grid-cols-4 mobile:grid-cols-2 gap-4 mt-4">
                <div>
                    <label className="text-sm" htmlFor="name">
                        Qty
                    </label>
                    <input
                        type="number"
                        id="qty"
                        className={`py-2.5 px-4 block w-full border ${
                            errors.qty ? "border-red-500" : "border-gray-200"
                        } rounded-lg sm:text-sm`}
                        placeholder="0.0000"
                        value={formValues.qty}
                        onChange={handleFormChange}
                    />
                    {errors.qty && (
                        <p className="text-red-500 text-xs mt-1">
                            Quantity is required
                        </p>
                    )}
                </div>
                <div>
                    <label className="text-sm" htmlFor="name">
                        Initial Cost
                    </label>
                    <input
                        type="number"
                        id="initialCost"
                        className={`py-2.5 px-4 block w-full border ${
                            errors.initialCost ? "border-red-500" : "border-gray-200"
                        } rounded-lg sm:text-sm`}
                        placeholder="0.0000"
                        value={formValues.initialCost}
                        onChange={handleFormChange}
                        required
                    />
                    {errors.initialCost && (
                        <p className="text-red-500 text-xs mt-1">
                            Initial Cost is required
                        </p>
                    )}
                </div>
                <div>
                    <label className="text-sm" htmlFor="name">
                        VAT Amount
                    </label>
                    <input
                        type="number"
                        id="vatAmount"
                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                        placeholder="0.0000"
                        value={formValues.vatAmount}
                        onChange={handleFormChange}
                        readOnly
                    />
                </div>
                <div>
                    <label className="text-sm" htmlFor="name">
                        SSCL Amount
                    </label>
                    <input
                        type="number"
                        id="ssclAmount"
                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                        placeholder="0.0000"
                        value={formValues.ssclAmount}
                        onChange={handleFormChange}
                        readOnly
                    />
                </div>
                <div>
                    <label className="text-sm" htmlFor="name">
                        Final Cost
                    </label>
                    <input
                        type="number"
                        id="finalCost"
                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                        placeholder="0.0000"
                        value={formValues.finalCost}
                        onChange={handleFormChange}
                        readOnly
                    />
                </div>
                <div>
                    <label className="text-sm" htmlFor="name">
                        Sales Price
                    </label>
                    <input
                        type="number"
                        id="salesPrice"
                        className={`py-2.5 px-4 block w-full border ${
                            errors.salesPrice ? "border-red-500" : "border-gray-200"
                        } rounded-lg sm:text-sm`}
                        placeholder="0.0000"
                        value={formValues.salesPrice}
                        onChange={handleFormChange}
                        required
                    />
                    {errors.salesPrice && (
                        <p className="text-red-500 text-xs mt-1">
                            Sales Price is required
                        </p>
                    )}
                </div>
                <div>
                    <label className="text-sm" htmlFor="name">
                        Margin
                    </label>
                    <input
                        type="number"
                        id="margin"
                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                        placeholder="0.0000"
                        value={formValues.margin}
                        onChange={handleFormChange}
                        readOnly
                    />
                </div>
                <div>
                    <label className="text-sm" htmlFor="name">
                        Margin %
                    </label>
                    <input
                        type="number"
                        id="marginPercentage"
                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                        placeholder="0.0000"
                        value={formValues.marginPercentage}
                        onChange={handleFormChange}
                        readOnly
                    />
                </div>
            </div>
        </>
    );
});

export default ItemComboBox;
