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

const API_URL = import.meta.env.VITE_API_URL;

function EmployeeAddEdit() {
    const [formData, setFormData] = useState({
        employeePosition: "",
        employeeName: "",
        employeeNIC: "",
        employeeAddress: "",
        employeeTelephone: "",
        employeeMobile: "",
    });
    const [editFormData, setEditFormData] = useState({
        employeePosition: "",
        employeeName: "",
        employeeNIC: "",
        employeeAddress: "",
        employeeTelephone: "",
        employeeMobile: "",
    });
    const [positions, setPositions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [employees, setEmployees] = useState([]);
    const [currentEmployeeId, setCurrentEmployeeId] = useState("");
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleChanges = (e) => {
        setFormData({
            ...formData,
            [e.target.id]: e.target.value,
        });
    };

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

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

    const handleGetData = async () => {
        setLoading(true);
        try {
            const response = await axios.get(`${API_URL}/employee/index`);
            setEmployees(response.data);
            const maxID = response.data.reduce(
                (max, item) => (item.id > max ? item.id : max),
                response.data[0].id
            );
            setCurrentEmployeeId(maxID);
        } catch (error) {
            console.error("Error getting company data:", error);
        }
        setLoading(false);
    };

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

    useEffect(() => {
        handleGetPositionData();
        handleGetData();
    }, []);

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

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

    const handleResetForm = () => {
        setFormData({
            employeePosition: "",
            employeeName: "",
            employeeNIC: "",
            employeeAddress: "",
            employeeTelephone: "",
            employeeMobile: "",
        });
    };

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

    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 Employees
                        </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">Employee ID</label>
                                    <input
                                        type="text"
                                        id="employeeId"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                                        disabled
                                        value={currentEmployeeId || "1"}
                                    />
                                    <label htmlFor="name">
                                        Select Position
                                    </label>
                                    <select
                                        id="employeePosition"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        value={formData.employeePosition || ""}
                                        onChange={handleChanges}
                                        required
                                    >
                                        <option>Select Position</option>
                                        {positions.map((position) => (
                                            <option
                                                key={position.id}
                                                value={position.id}
                                            >
                                                {" "}
                                                {position.positionName}{" "}
                                            </option>
                                        ))}
                                    </select>

                                    <label htmlFor="name">Name</label>
                                    <input
                                        type="text"
                                        id="employeeName"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        placeholder="Enter Employee Name"
                                        value={formData.employeeName || ""}
                                        onChange={handleChanges}
                                        required
                                    />
                                    <label htmlFor="name">NIC Number</label>
                                    <input
                                        type="text"
                                        id="employeeNIC"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        placeholder="Enter Employee NIC Number"
                                        value={formData.employeeNIC || ""}
                                        onChange={handleChanges}
                                        required
                                    />
                                    <label htmlFor="name">Address</label>
                                    <input
                                        type="text"
                                        id="employeeAddress"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        placeholder="Enter Employee Address"
                                        value={formData.employeeAddress}
                                        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="employeeTelephone"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter Employee Telephone"
                                                value={
                                                    formData.employeeTelephone
                                                }
                                                onChange={handleChanges}
                                                required
                                            />
                                        </div>
                                        <div>
                                            <label htmlFor="name">Mobile</label>
                                            <input
                                                type="text"
                                                id="employeeMobile"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter Employee Mobile"
                                                value={formData.employeeMobile}
                                                onChange={handleChanges}
                                                required
                                            />
                                        </div>
                                    </div>
                                </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 Employees
                        </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"
                                                >
                                                    Name
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    NIC Number
                                                </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"
                                                >
                                                    Position
                                                </th>
                                                <th
                                                    scope="col"
                                                    className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                >
                                                    Action
                                                </th>
                                            </tr>
                                        </thead>
                                        {loading ? (
                                            <AddEmployeeTableSkeleton rows={ currentEmployeeId? 1 : 5} />
                                        ) : (
                                        <tbody className="divide-y divide-gray-200">
                                            {employees.map((employee) => (
                                                <tr key={employee.id}>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                        {employee.id}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                        {employee.employeeName}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                        {employee.employeeNIC}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                        {employee.employeeMobile}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                        {
                                                            employee
                                                                .employee_position
                                                                ?.positionName
                                                        }
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-end text-sm font-medium">
                                                        <button
                                                            type="button"
                                                            onClick={() =>
                                                                handleOpenModal(
                                                                    employee
                                                                )
                                                            }
                                                            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 Employee
                                        </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">
                                                Employee ID
                                            </label>
                                            <input
                                                type="text"
                                                id="employeeId"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm bg-slate-100"
                                                disabled
                                                value={editFormData.id || "1"}
                                            />
                                            <label htmlFor="name">
                                                Select Position
                                            </label>
                                            <select
                                                id="employeePosition"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                value={
                                                    editFormData.employeePosition ||
                                                    ""
                                                }
                                                onChange={handleEditChanges}
                                                required
                                            >
                                                <option>Select Position</option>
                                                {positions.map((position) => (
                                                    <option
                                                        key={position.id}
                                                        value={position.id}
                                                    >
                                                        {" "}
                                                        {
                                                            position.positionName
                                                        }{" "}
                                                    </option>
                                                ))}
                                            </select>

                                            <label htmlFor="name">Name</label>
                                            <input
                                                type="text"
                                                id="employeeName"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter Employee Name"
                                                value={
                                                    editFormData.employeeName || ""
                                                }
                                                onChange={handleEditChanges}
                                                required
                                            />
                                            <label htmlFor="name">
                                                NIC Number
                                            </label>
                                            <input
                                                type="text"
                                                id="employeeNIC"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter Employee NIC Number"
                                                value={
                                                    editFormData.employeeNIC || ""
                                                }
                                                onChange={handleEditChanges}
                                                required
                                            />
                                            <label htmlFor="name">
                                                Address
                                            </label>
                                            <input
                                                type="text"
                                                id="employeeAddress"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter Employee Address"
                                                value={editFormData.employeeAddress}
                                                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="employeeTelephone"
                                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                        placeholder="Enter Employee Telephone"
                                                        value={
                                                            editFormData.employeeTelephone
                                                        }
                                                        onChange={handleEditChanges}
                                                        required
                                                    />
                                                </div>
                                                <div>
                                                    <label htmlFor="name">
                                                        Mobile
                                                    </label>
                                                    <input
                                                        type="text"
                                                        id="employeeMobile"
                                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                        placeholder="Enter Employee Mobile"
                                                        value={
                                                            editFormData.employeeMobile
                                                        }
                                                        onChange={handleEditChanges}
                                                        required
                                                    />
                                                </div>
                                            </div>
                                        </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 EmployeeAddEdit;
