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

const API_URL = import.meta.env.VITE_API_URL;

function AddCategories() {
    // State to manage the category name input
    const [categoryName, setCategoryName] = useState("");
    const [editCategoryName, setEditCategoryName] = useState("");
    const [categoryList, setCategoryList] = useState([]);
    const [categoryID, setcategoryID] = useState("");
    const [loading, setLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    // Function to handle form submission
    const handleSubmit = async (e) => {
        e.preventDefault(); // Prevent default form submission behavior

        try {
            // Prepare the data to be sent
            const requestData = {
                Category_name: categoryName,
            };
            // Send a POST request to the API endpoint
            const response = await axios.post(
                `${API_URL}/itemCategories/store`,
                requestData
            );

            // Handle successful response
            showSuccessToast(
                "Category saved successfully",
                response.data.message
            );

            // Optionally, reset the input field after successful submission
            setCategoryName("");
            handleGetCategories();
        } catch (error) {
            // Handle errors (e.g., network issues, server errors)
            showErrorToast("An error occurred", error.message);
        }
    };

    const handleGetCategories = async () => {
        setLoading(true);
        try {
            const response = await axios.get(`${API_URL}/itemCategories/index`);
            setCategoryList(response.data);
        } catch (error) {
            console.error("Error getting company data:", error);
        } finally {
            setLoading(false);
        }
    };

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

    const handleOpenModal = (category) => {
        setIsModalOpen(true);
        setcategoryID(category.id);
        setEditCategoryName(category.Category_name)
    };

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

    const handleUpdate = async (e) => {
        e.preventDefault();
        const requestData = {
            Category_name: editCategoryName,
        };

        try {
            const response = await axios.put(
                `${API_URL}/itemCategories/update/${categoryID}`,
                requestData
            );
            showSuccessToast(
                response.data.message || "Category updated successfully!"
            );
            handleCloseModal();
            handleGetCategories();
        } catch (error) {
            showErrorToast(
                error.response?.data?.message || "Error updating Category!"
            );
        }
    };

    const handleNewEntry = () => {
        setCategoryName("");
    }

    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 Categories
                        </h2>
                    </div>
                    <div className="mb-4">
                        <div className="flex justify-between">
                            <div>
                                <h3 className="text-base font-semibold mb-2">
                                    Add New Category
                                </h3>
                            </div>
                            <div>
                                <button
                                    type="button"
                                    onClick={handleNewEntry}
                                    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>

                        <form onSubmit={handleSubmit}>
                            <div className="flex flex-col space-y-2">
                                <label htmlFor="name">Category name</label>
                                <input
                                    type="text"
                                    id="Categoryname"
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                    placeholder="Enter Category name"
                                    value={categoryName}
                                    onChange={(e) =>
                                        setCategoryName(e.target.value)
                                    } // Update state on input change
                                    required
                                />
                            </div>
                            <div className="flex justify-center mt-10">
                                <button
                                    type="submit"
                                    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>
                    <div className=" bg-slate-100 rounded-lg p-4 shadow-lg">
                        <div>
                            <h2 className="text-lg font-bold mb-4">
                                List of Exesisting Categories
                            </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-[280px]">
                                        <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"
                                                    >
                                                        Category Name
                                                    </th>
                                                    <th
                                                        scope="col"
                                                        className="px-6 py-3 text-end text-xs font-medium text-gray-500 uppercase"
                                                    >
                                                        Action
                                                    </th>
                                                </tr>
                                            </thead>
                                            {loading ? (
                                                <AddCategoriesTableSkeleton
                                                    rows={5}
                                                />
                                            ) : (
                                                <tbody className="divide-y divide-gray-200">
                                                    {categoryList.map(
                                                        (category) => (
                                                            <tr
                                                                key={
                                                                    category.id
                                                                }
                                                            >
                                                                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                                    {
                                                                        category.id
                                                                    }
                                                                </td>
                                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                                    {
                                                                        category.Category_name
                                                                    }
                                                                </td>
                                                                <td className="px-6 py-4 whitespace-nowrap text-end text-sm font-medium">
                                                                    <button
                                                                        type="button"
                                                                        onClick={() =>
                                                                            handleOpenModal(
                                                                                category
                                                                            )
                                                                        }
                                                                        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>
            </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 Company
                                </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">Category name</label>
                                    <input
                                        type="text"
                                        id="name"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        placeholder="Enter company name"
                                        value={editCategoryName}
                                        onChange={(e) =>
                                            setEditCategoryName(e.target.value)
                                        }
                                    />
                                </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={handleUpdate}
                                    className="py-2 px-3 rounded-lg bg-blue-600 text-white hover:bg-blue-700"
                                >
                                    Save changes
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </>
        </>
    );
}

export default AddCategories;
