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

const API_URL = import.meta.env.VITE_API_URL;

function CompanyAddEdit() {
    const [companies, setCompanies] = useState([]);
    const [formData, setFormData] = useState({
        id: "",
        name: "",
        shortCode: "",
        wearHouse: false, // Default to false
    });
    const [editFormData, setEditFormData] = useState({
        id: "",
        name: "",
        shortCode: "",
        wearHouse: false, // Default to false
    });
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [loading, setLoading] = 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 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}/company/store`, requestBody, {
                headers: {
                    "Content-Type": "application/json",
                },
            });
            showSuccessToast("Company saved successfully!");
            handleGetData();
           
        } catch (error) {
            console.error("Error saving company:", error);
            showErrorToast("Error saving company!");
        }
    };

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

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

    const handleEdit = (company) => {
        // Set the company data to the state for editing
        setEditFormData({
            id: company.id,
            name: company.name,
            shortCode: company.shortCode,
            wearHouse: company.wearHouse === 1, // Assuming 1 is true for wearHouse
        });
    };

    const resetForm = () => {
        setFormData({
            id: "",
            name: "",
            shortCode: "",
            wearHouse: false,
        });
    };

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

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

    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">
                            <div>
                                <h2 className="text-lg font-bold mb-4">
                                    Add new Bussiness / Company
                                </h2>
                            </div>
                        <div className="mb-4">
                            <h3 className="text-base font-semibold mb-2">
                                Company details
                            </h3>
                            <form onSubmit={handleSubmit}>
                                <div className="flex flex-col space-y-2">
                                    <label htmlFor="name">Company 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={formData.name}
                                        onChange={handleChange}
                                        required
                                    />
                                    <label htmlFor="shortCode">
                                        Short code
                                    </label>
                                    <input
                                        type="text"
                                        id="shortCode"
                                        className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                        placeholder="Enter short code"
                                        value={formData.shortCode}
                                        onChange={handleChange}
                                        required
                                    />
                                    <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={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>
                            </form>
                        </div>
                    </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]">
                                        <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"
                                                    >
                                                        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">
                                                {companies.map((company) => (
                                                    <tr key={company.id}>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
                                                            {company.id}
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                            {company.name}
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800">
                                                            {company.shortCode}
                                                        </td>
                                                        <td className="px-6 py-4 whitespace-nowrap text-end text-sm font-medium">
                                                            <button
                                                                type="button"
                                                                onClick={() =>
                                                                    handleOpenModal(
                                                                        company
                                                                    )
                                                                }
                                                                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">
                                                Company 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={editFormData.name}
                                                onChange={handleEditChange}
                                            />
                                            <label htmlFor="shortCode">
                                                Short code
                                            </label>
                                            <input
                                                type="text"
                                                id="shortCode"
                                                className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                                placeholder="Enter short code"
                                                value={editFormData.shortCode}
                                                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 CompanyAddEdit;
