import React, { useState, useEffect } from "react";
import ToastNotification, {
    showSuccessToast,
    showErrorToast,
} from "@/Components/Notification/ToastNotification";

const API_URL = import.meta.env.VITE_API_URL;

function AddSupplierModal({ handleCloseModal, isModalOpen,onClose  }) {
    const [items, setItems] = useState([]);
    const [suppliers, setSuppliers] = useState([]);
    const [formData, setFormData] = useState({
        item_id: "",
        supplierName: "",
        supplierAddress: "",
        supplierTelephone: "",
        supplierMobile: "",
        supplierEmail: "",
    });
    const [currentSupplierId, setCurrentSupplierId] = useState(null);

    const handleChanges = (e) => {
        const { id, value } = e.target;
        setFormData({
            ...formData,
            [id]: value,
        });
    };

    const handleGetSuppierData = async () => {
        try {
            const response = await axios.get(`${API_URL}/suppliers/index`);
            setSuppliers(response.data);
            if (response.data.length > 0) {
                const maxID = response.data.reduce(
                    (max, item) => (item.id > max ? item.id : max),
                    response.data[0].id
                );
                setCurrentSupplierId(maxID);
            } else {
                console.error("The items array is empty.");
            }
        } catch (error) {
            console.error("Error getting company data:", error);
        }
    };



    const handleGetItems = async () => {
        try {
            const response = await axios.get(`${API_URL}/items/index`);
            setItems(response.data);
        } catch (error) {
            console.error("Error getting company data:", error);
        }
    };

    useEffect(() => {
        handleGetSuppierData();
        handleGetItems();
    }, []);

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await axios.post(
                `${API_URL}/suppliers/store`,
                formData,
                {
                    headers: {
                        "Content-Type": "application/json",
                    },
                }
            );
            showSuccessToast(
                response.data.message || "Supplier saved successfully!"
            );
            handleGetSuppierData();
            handleResetForm();
            handleModalClose ();
        } catch (error) {
            console.error("Error saving company:", error);
            showErrorToast("Error saving supplier!", error);
        }
    };

    const handleModalClose = () => {
        handleCloseModal(); // Close the modal
        handleResetForm();
        if (onClose) {
            onClose(); // Trigger parent function
        }
    };

    const handleResetForm = () => {
        setFormData({
            item_id: "",
            supplierName: "",
            supplierAddress: "",
            supplierTelephone: "",
            supplierMobile: "",
            supplierEmail: "",
        });
    };

    return (
        <>
            {/* Modal */}
            <ToastNotification />{" "}
            {isModalOpen && (
                <div className="fixed inset-0 flex items-center justify-center z-50 bg-black bg-opacity-50">
                    <div className="bg-white border border-gray-200 shadow-lg rounded-lg w-96">
                        <div className="flex justify-between items-center py-3 px-4 border-b">
                            <h3 className="font-bold text-gray-800">
                                Add New Selected Supplier
                            </h3>
                            <button
                                onClick={handleModalClose}
                                className="size-8 inline-flex justify-center items-center rounded-full bg-gray-100 text-gray-800 hover:bg-gray-200"
                            >
                                ✕
                            </button>
                        </div>
                        <div className="p-4">
                            <div className="flex flex-col space-y-2">
                                <label htmlFor="name">Suppliers ID</label>
                                <input
                                    type="text"
                                    id="supplierID"
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                                    value={currentSupplierId + 1 || ""}
                                    disabled
                                />
                                <label htmlFor="name">Select Items</label>
                                <select
                                    id="item_id"
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                    value={formData.item_id || ""}
                                    onChange={handleChanges}
                                    required
                                >
                                    <option>Select Item</option>
                                    {items.map((item) => (
                                        <option key={item.id} value={item.id}>
                                            {" "}
                                            {item.item_name}{" "}
                                        </option>
                                    ))}
                                </select>
                                <label htmlFor="name">Name</label>
                                <input
                                    type="text"
                                    id="supplierName"
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                    placeholder="Enter Supplier Name"
                                    value={formData.supplierName || ""}
                                    onChange={handleChanges}
                                    required
                                />
                                <label htmlFor="name">Address</label>
                                <input
                                    type="text"
                                    id="supplierAddress"
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                    placeholder="Enter Supplier Address"
                                    value={formData.supplierAddress}
                                    onChange={handleChanges}
                                    required
                                />
                                <div className="grid lg:grid-cols-2 md:grid-cols-2 mobile:grid-cols-1 lg:space-x-5 md:space-x-5 mobile:space-x-0 ">
                                    <div>
                                        <label htmlFor="name">Telephone</label>
                                        <input
                                            type="text"
                                            id="supplierTelephone"
                                            className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm mt-2"
                                            placeholder="Enter Supplier Telephone"
                                            value={formData.supplierTelephone}
                                            onChange={handleChanges}
                                            required
                                        />
                                    </div>
                                    <div>
                                        <label htmlFor="name">Mobile</label>
                                        <input
                                            type="text"
                                            id="supplierMobile"
                                            className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm mt-2"
                                            placeholder="Enter Supplier Mobile"
                                            value={formData.supplierMobile}
                                            onChange={handleChanges}
                                            required
                                        />
                                    </div>
                                </div>
                                <label htmlFor="name">Email</label>
                                <input
                                    type="email"
                                    id="supplierEmail"
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                    placeholder="Enter Supplier Email"
                                    value={formData.supplierEmail}
                                    onChange={handleChanges}
                                />
                            </div>
                        </div>
                        <div className="flex justify-end items-center gap-x-2 py-3 px-4 border-t">
                            <button
                                onClick={handleModalClose}
                                className="py-2 px-3 rounded-lg bg-gray-200 text-gray-800 hover:bg-gray-300"
                            >
                                Close
                            </button>
                            <button
                                type="button"
                                onClick={handleSubmit}
                                className="py-2 px-3 rounded-lg bg-blue-600 text-white hover:bg-blue-700"
                            >
                                Save changes
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}

export default AddSupplierModal;
