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

const API_URL = import.meta.env.VITE_API_URL;

function AddRoutes() {
    const [branches, setBranches] = useState([]);
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState({
        section_id: "", 
        routeName: "", 
    });
    const [editFormData, setEditFormData] = useState({
        section_id: "", 
        routeName: "", 
    });
    const[RoutesData, setRoutesData] = useState([]);
    const [currentRouteID, setCurrentRouteID] = useState("");
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleResetForm = () => {
        setFormData({
            section_id: "", 
            routeName: "", 
        });
    };
    const handleGetBranchData = async () => {
        try {
            const response = await axios.get(`${API_URL}/companyBranch/index`);
            setBranches(response.data);
        } catch (error) {
            console.error("Error getting company data:", error);
        }
    };

    const handleGetRoutesData = async () => {
        setLoading(true);
        try {
            const response = await axios.get(`${API_URL}/routes/index`);
            setRoutesData(response.data);
            if (response.data.length > 0) {
                const maxID = response.data.reduce((max, item) => (item.id > max ? item.id : max), response.data[0].id);
                setCurrentRouteID(maxID);
            }
        } catch (error) {
            console.error("Error getting Routes data:", error);
        } finally {
            setLoading(false);
        }
    };

    const handleChanges = (e) => {
        const { id, value, type, checked } = e.target;
        setFormData((prevFormData) => ({
            ...prevFormData,
            [id]: type === "checkbox" ? checked : value || "", // Prevents undefined values
        }));
    };

    const handleEditChanges = (e) => {
        const { id, value, type, checked } = e.target;
        setEditFormData((prevFormData) => ({
            ...prevFormData,
            [id]: type === "checkbox" ? checked : value || "", // Prevents undefined values
        }));
    };

    useEffect(() => {
        handleGetBranchData();
        handleGetRoutesData();
    }, []);

    const handleSubmit = async (e) => {
        e.preventDefault();
        const requestBody = {
            ...formData,
        };
        try {
            // Create a new company
            await axios.post(`${API_URL}/routes/store`, requestBody, {
                headers: {
                    "Content-Type": "application/json",
                },
            });
            showSuccessToast("Route saved successfully!");
            handleGetRoutesData();
            handleResetForm();
        } catch (error) {
            console.error("Error saving company:", error);
            showErrorToast("Error saving route!");
        }
    };

    const handleEdit = (routes) => {
        setEditFormData({
         ...routes,
        });
     };

    const handleEditSubmit = async (e) => {
        e.preventDefault();
        const requestBody = {
            ...editFormData,
        };
        try {
            // Create a new company
            await axios.put(`${API_URL}/routes/update/${editFormData.id}`, requestBody, {
                headers: {
                    "Content-Type": "application/json",
                },
            });
            showSuccessToast("Route updated successfully!");
            handleGetRoutesData();
        } catch (error) {
            console.error("Error saving company:", error);
            showErrorToast("Error updating route!");
        }
    };

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

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



    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 Routes
                        </h2>
                    </div>
                    <div className="mb-4">
                        <div className="flex justify-between">
                            <div>
                                <h3 className="text-base font-semibold mb-2">
                                    Add New Routes
                                </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 className="mb-4">
                            <form onSubmit={handleSubmit}>
                                <div className="flex flex-col space-y-2">
                                    <label htmlFor="name">Select Section</label>
                                    <select
                                        id="section_id"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        value={formData.section_id || ""}
                                        onChange={handleChanges}
                                        required
                                    >
                                        <option>Select Section</option>
                                        {branches.map((branch) => (
                                            <option
                                                key={branch.id}
                                                value={branch.id}
                                            >
                                                {`${branch.branchName} - ${branch.company_name}`}
                                            </option>
                                        ))}
                                    </select>
                                    <label htmlFor="name">Route Number</label>
                                    <input
                                        type="text"
                                        id="routeID"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                                        disabled
                                        value={currentRouteID || "1"}
                                    />
                                    <label htmlFor="name">Route Name</label>
                                    <input
                                        type="text"
                                        id="routeName"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        placeholder="Enter Route Name"
                                        value={formData.routeName || ""}
                                        onChange={handleChanges}
                                        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">
                            Modify Routes
                        </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"
                                                >
                                                    Route ID
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    Route 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 ? <AddItemsTableSkeleton rows={5} /> : (
                                        <tbody className="divide-y divide-gray-200">
                                            {RoutesData.map((routes) => (
                                            <tr key={routes.id}>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                   {routes.id}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                   {routes.routeName}
                                                </td>
                                                
                                                <td className="px-6 py-4 whitespace-nowrap text-end text-sm font-medium">
                                                    <button
                                                        type="button"
                                                        onClick={() => handleOpenModal(routes)}
                                                        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>
                    <>
                        {/* 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 Routes
                                        </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">Select Section</label>
                                        <select
                                            id="section_idEdit"
                                            className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                            value={editFormData.section_id}
                                            onChange={handleEditChanges}
                                        >
                                            {branches.map((branch) => (
                                            <option
                                                key={branch.id}
                                                value={branch.id}
                                            >
                                                {`${branch.branchName} - ${branch.company_name}`}
                                            </option>
                                        ))}
                                        </select>
                                        <label htmlFor="name">Route Number</label>
                                        <input
                                            type="text"
                                            id="routeID"
                                            className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                                            disabled
                                            value={editFormData.id}
                                        />
                                        <label htmlFor="name">Route Name</label>
                                        <input
                                            type="text"
                                            id="routeName"
                                            className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                            placeholder="Enter Item Name"
                                            value={editFormData.routeName}
                                            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>
                        )}
                    </>
                </div>
            </div>
        </>
    );
}

export default AddRoutes;
