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

const API_URL = import.meta.env.VITE_API_URL;

function Suppliers() {
    const [items, setItems] = useState([]);
    const [formData, setFormData] = useState({
        item_id: "",
        supplierName: "",
        supplierAddress: "",
        supplierTelephone: "",
        supplierMobile: "",
        supplierEmail: "",
    });
    const [editFormData, setEditFormData] = useState({
        id: "",
        item_id: "",
        supplierName: "",
        supplierAddress: "",
        supplierTelephone: "",
        supplierMobile: "",
        supplierEmail: "",
    });
    const [suppliers, setSuppliers] = useState([]);
    const [currentSupplierId, setCurrentSupplierId] = useState(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const handleChanges = (e) => {
        const { id, value } = e.target;
        setFormData({
            ...formData,
            [id]: value,
        });
    };

    const handleEditChanges = (e) => {
        const { id, value } = e.target;
        setEditFormData({
            ...editFormData,
            [id]: value,
        });
    };

    const handleEdit = (supplier) => {
        setEditFormData({
            id: supplier.id,
            item_id: supplier.item_id,
            supplierName: supplier.supplierName,
            supplierAddress: supplier.supplierAddress,
            supplierTelephone: supplier.supplierTelephone,
            supplierMobile: supplier.supplierMobile,
            supplierEmail: supplier.supplierEmail,
        });
    };

    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);
        }
    };

    const handleGetSuppierData = async () => {
        try {
            setIsLoading(true);
            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);
        }
        setIsLoading(false);
    };

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

    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();
        } catch (error) {
            console.error("Error saving company:", error);
            showErrorToast("Error saving supplier!", error);
        }
    };

    const handleEditSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await axios.put(
                `${API_URL}/suppliers/update/${editFormData.id}`,
                editFormData,
                {
                    headers: {
                        "Content-Type": "application/json",
                    },
                }
            );
            showSuccessToast(
                response.data.message || "Supplier updated successfully!"
            );
            handleGetSuppierData();
        } catch (error) {
            console.error("Error saving company:", error);
            showErrorToast("Error updating supplier!", error);
        }
    };

    const handleOpenModal = (supplier) => {
        setIsModalOpen(true);
        handleEdit(supplier);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
    };

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

    return (
        <>
            <ToastNotification />{" "}
            <div className="grid lg:grid-cols-2 md:grid-cols-1 mobile:grid-cols-1 gap-4 bg-white p-5">
                <div className=" bg-slate-100 rounded-lg p-4 shadow-lg">
                    <div>
                        <h2 className="text-lg font-bold mb-4">
                            Add / Edit Supplier
                        </h2>
                    </div>
                    <div className="mb-4">
                        <div className="flex justify-between">
                            <div>
                                <h3 className="text-base font-semibold mb-2">
                                    Add New Supplier
                                </h3>
                            </div>
                            <div>
                                <button
                                    type="button"
                                    onClick={handleResetForm}
                                    className="py-2 px-3 inline-flex items-center gap-x-2 text-sm font-medium rounded-lg border border-transparent bg-blue-600 text-white hover:bg-blue-700 focus:outline-hidden focus:bg-blue-700 disabled:opacity-50 disabled:pointer-events-none"
                                >
                                    New
                                </button>
                            </div>
                        </div>
                    </div>
                    <div className="mb-4">
                        <form>
                            <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 className="flex justify-center mt-5">
                                <button
                                    type="submit"
                                    onClick={handleSubmit}
                                    className="bg-blue-600 px-2 py-1 rounded text-white w-32 hover:bg-blue-700 h-10"
                                >
                                    Save
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div className=" bg-slate-100 rounded-lg p-4 shadow-lg">
                    <div>
                        <h2 className="text-lg font-bold mb-4">
                            Modify Suppliers
                        </h2>
                    </div>
                    <div className="flex flex-col mt-5">
                        <div className="-m-1.5 overflow-x-auto">
                            <div className="p-1.5 min-w-full inline-block align-middle">
                                <div className="overflow-x-auto max-h-[480px]">
                                    <table className="min-w-full divide-y divide-gray-200">
                                        <thead>
                                            <tr>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    ID
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    Supplie Items
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    Name
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    Mobile
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    Email
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    Action
                                                </th>
                                            </tr>
                                        </thead>
                                        {isLoading ? (
                                            <SupplierTableSkelton rows={9} />
                                        ) : (
                                            <tbody className="divide-y divide-gray-200">
                                                {suppliers.map((supplier) => (
                                                    <tr key={supplier.id}>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                            {supplier.id}
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                            {
                                                                supplier.items
                                                                    ?.item_name
                                                            }
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                            {
                                                                supplier.supplierName
                                                            }
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                            {
                                                                supplier.supplierMobile
                                                            }
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                            {
                                                                supplier.supplierEmail
                                                            }
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-end text-sm font-medium">
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    handleOpenModal(
                                                                        supplier
                                                                    )
                                                                }
                                                                className="inline-flex items-center gap-x-2 text-sm font-semibold rounded-lg border border-transparent text-blue-600 hover:text-blue-800 focus:outline-hidden focus:text-blue-800 disabled:opacity-50 disabled:pointer-events-none"
                                                            >
                                                                Edit
                                                            </button>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        )}
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <>
                {/* Modal */}
                {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">
                                    Edit Selected Supplier
                                </h3>
                                <button
                                    onClick={handleCloseModal}
                                    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={editFormData.id || "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={editFormData.item_id || ""}
                                        onChange={handleEditChanges}
                                        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={editFormData.supplierName || ""}
                                        onChange={handleEditChanges}
                                        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={editFormData.supplierAddress}
                                        onChange={handleEditChanges}
                                        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={
                                                    editFormData.supplierTelephone
                                                }
                                                onChange={handleEditChanges}
                                                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={
                                                    editFormData.supplierMobile
                                                }
                                                onChange={handleEditChanges}
                                                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={editFormData.supplierEmail}
                                        onChange={handleEditChanges}
                                    />
                                </div>
                            </div>
                            <div className="flex justify-end items-center gap-x-2 py-3 px-4 border-t">
                                <button
                                    onClick={handleCloseModal}
                                    className="py-2 px-3 rounded-lg bg-gray-200 text-gray-800 hover:bg-gray-300"
                                >
                                    Close
                                </button>
                                <button
                                    type="button"
                                    onClick={handleEditSubmit}
                                    className="py-2 px-3 rounded-lg bg-blue-600 text-white hover:bg-blue-700"
                                >
                                    Save changes
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </>
        </>
    );
}

export default Suppliers;
