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

const API_URL = import.meta.env.VITE_API_URL;

function BranchAddEdit() {
    const [companies, setCompanies] = useState([]);
    const [branches, setBranches] = useState([]);
    const [formData, setFormData] = useState({
        company_id: "",
        branchName: "",
        branchShortCode: "",
        wearHouse: false,
    });
    const [editFormData, setEditFormData] = useState({
        id: "",
        company_id: "",
        branchName: "",
        branchShortCode: "",
        wearHouse: false,
    });
    const [loading, setLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleChange = (e) => {
        const { id, value, type, checked } = e.target;
        setFormData({
            ...formData,
            [id]: type === "checkbox" ? checked : value,
        });
    };

    const handleEditChange = (e) => {
        const { id, value, type, checked } = e.target;
        setEditFormData({
            ...editFormData,
            [id]: type === "checkbox" ? checked : value,
        });
    };

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

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

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



    const handleSubmit = async (e) => {
        e.preventDefault();
        const requestBody = {
            ...formData,
            wearHouse: formData.wearHouse ? 1 : 0, // Convert boolean to 1/0 for Laravel
        };
        try {
            // Create a new company
            await axios.post(`${API_URL}/companyBranch/store`, requestBody, {
                headers: {
                    "Content-Type": "application/json",
                },
            });
            showSuccessToast("Branch saved successfully!");
            handleGetBranchData();
        } catch (error) {
            console.error("Error saving company:", error);
            showErrorToast(
                error.response?.data?.message || "Error saving branch!"
            );
        }
    };

    const handleUpdate = async (e) => {
        e.preventDefault();
        const requestBody = {
            ...editFormData,
            wearHouse: editFormData.wearHouse ? 1 : 0, // Convert boolean to 1/0 for Laravel
        };
        try {
            // Update the company
            await axios.put(
                `${API_URL}/companyBranch/update/${editFormData.id}`, requestBody, {
                    headers: {
                        "Content-Type": "application/json",
                    },
                }
            );
            showSuccessToast("Branch updated successfully!");
            handleGetBranchData();
            handleCloseModal();
        } catch (error) {
            console.error("Error updating company:", error);
            showErrorToast(
                error.response?.data?.message || "Error updating branch!"
            );
        }
    };

    const handleEdit = (branch) => {
        setEditFormData({
            id: branch.id,
            company_id: branch.company_id,
            branchName: branch.branchName,
            branchShortCode: branch.branchShortCode,
            wearHouse: branch.wearHouse === 1 ? true : false,
        });
    };

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

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

    return (
        <>
            <ToastNotification />
            <div id="section-tab" role="tabpanel">
                <div className="flex lg:flex-row md:flex-row mobile:flex-col">
                    <div className="lg:w-1/2 md:w-1/2 mobile:w-full pr-4 bg-slate-100 rounded-lg p-4 shadow-lg">
                        <h2 className="text-lg font-bold mb-4">
                            Add new Branches / Section
                        </h2>
                        <form onSubmit={handleSubmit}>
                            <div className="mb-4">
                                <h3 className="text-base font-semibold mb-2">
                                    Section details
                                </h3>
                                <div className="flex flex-col space-y-2">
                                    <label htmlFor="sectionName">
                                        Select Company
                                    </label>
                                    <select
                                        value={formData.company_id}
                                        onChange={handleChange}
                                        required
                                        id="company_id"
                                        className="py-3 px-4 pe-9 block w-full border-gray-200 rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none"
                                    >
                                        <option value="">Select Company</option>
                                        {companies.map((company) => (
                                            <option
                                                key={company.id}
                                                value={company.id}
                                            >
                                                {company.name} -{" "}
                                                {company.shortCode}
                                            </option>
                                        ))}
                                    </select>
                                    <label htmlFor="shortCode">
                                        Section Name
                                    </label>
                                    <input
                                        type="text"
                                        id="branchName"
                                        className="py-2.5 sm:py-3 px-4 block w-full border-gray-200 rounded-lg sm:text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none"
                                        placeholder="Enter section name"
                                        value={formData.branchName}
                                        onChange={handleChange}
                                        required
                                    />
                                    <label htmlFor="branchShortCode">
                                        Short Code
                                    </label>
                                    <input
                                        type="text"
                                        id="branchShortCode"
                                        className="py-2.5 sm:py-3 px-4 block w-full border-gray-200 rounded-lg sm:text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none"
                                        placeholder="Enter short code"
                                        value={formData.branchShortCode}
                                        onChange={handleChange}
                                        required
                                    />
                                    <span>Example : HO - Head Office </span>
                                    <div className="flex items-center space-x-2">
                                        <input
                                            type="checkbox"
                                            id="wearHouse"
                                            className="rounded-md border-gray-300 p-2"
                                            value={formData.wearHouse}
                                            onChange={handleChange}
                                        />
                                        <label htmlFor="wearHouse">
                                            Is Wear House
                                        </label>
                                    </div>
                                    <div className="flex justify-center">
                                        <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>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div className="lg:w-1/2 md:w-1/2 mobile:w-full pr-4 bg-slate-100 rounded-lg p-4 ml-4 shadow-lg">
                        <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-[390px]">
                                        {" "}
                                        {/* Add overflow-x-auto */}
                                        <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"
                                                    >
                                                        Branch Code
                                                    </th>
                                                    <th
                                                        scope="col"
                                                        className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                    >
                                                        Company Name
                                                    </th>
                                                    <th
                                                        scope="col"
                                                        className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                    >
                                                        Branch Name
                                                    </th>
                                                    <th
                                                        scope="col"
                                                        className="px-6 py-3 text-start text-xs font-medium text-gray-500 uppercase"
                                                    >
                                                        Short Code
                                                    </th>
                                                    <th
                                                        scope="col"
                                                        className="px-6 py-3 text-end text-xs font-medium text-gray-500 uppercase"
                                                    >
                                                        Action
                                                    </th>
                                                </tr>
                                            </thead>
                                            {loading ? <CompanyTableSkeleton rows={5} /> : (
                                            <tbody className="divide-y divide-gray-200">
                                                {branches.map((branch) => (
                                                <tr key={branch.id}>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                       {branch.id}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                        {branch.company_name}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                        {branch.branchName}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                        {branch.branchShortCode}
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-end text-sm font-medium">
                                                        <button
                                                            type="button"
                                                            onClick={() =>
                                                                handleOpenModal(
                                                                    branch
                                                                )
                                                            }
                                                            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 className="mt-4">
                            <ul>
                                <li>
                                    * Short Code is compulsory to create a new
                                    account in general ledger.
                                </li>
                                <li>
                                    * Maximum 2 characters can use for Short
                                    Code.
                                </li>
                                <li>
                                    * The short code "HO" is reserved for Head
                                    Office.
                                </li>
                            </ul>
                        </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">
                                                Select Company
                                            </label>
                                            <select
                                                value={editFormData.company_id}
                                                onChange={handleEditChange}
                                                id="company_id"
                                                className="py-3 px-4 pe-9 block w-full border-gray-200 rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none"
                                            >
                                                <option value="">Select Company</option>
                                                {companies.map((company) => (
                                                    <option
                                                        key={company.id}
                                                        value={company.id}
                                                    >
                                                        {company.name} -{" "}
                                                        {company.shortCode}
                                                    </option>
                                                ))}
                                            </select>
                                            <label htmlFor="name">
                                                Section Name
                                            </label>
                                            <input
                                                type="text"
                                                id="branchName"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter company name"
                                                value={editFormData.branchName}
                                                onChange={handleEditChange}
                                            />
                                            <label htmlFor="shortCode">
                                                Short code
                                            </label>
                                            <input
                                                type="text"
                                                id="branchShortCode"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter short code"
                                                value={editFormData.branchShortCode}
                                                onChange={handleEditChange}
                                            />
                                            <span>
                                                Example: NL - New Line PVT LTD
                                            </span>
                                            <div className="flex items-center space-x-2">
                                                <input
                                                    type="checkbox"
                                                    id="wearHouse"
                                                    className="rounded-md border-gray-300 p-2"
                                                    checked={editFormData.wearHouse}
                                                    onChange={handleEditChange}
                                                />
                                                <label htmlFor="wearHouse">
                                                    Is Wear House
                                                </label>
                                            </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={handleUpdate}
                                            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 BranchAddEdit;
