import useRequest from "@/lib/hooks/useRequest";
import { useEffect, useState } from "react";
import { GET_TOLL_HOUSE_DETAILS, UPDATE_TOLL_HOUSE_ITEM } from "@/core/utils/routes";
import DialogLoading from "@/core/components/DialogLoading";
import CreateTollHouseContent from "../CreateTollHouse/CreateTollHouseContent";
import { usePermissions } from "@/lib/hooks/usePermissions";

const EditController = ({ rowId, mutate, setOpenEditDialog }) => {
    const { data: userPermissions } = usePermissions();
    const hasCreateProvincePermission = userPermissions.some((item) => ["add-receipt"].includes(item));
    const requestServer = useRequest();
    const [tollHouseItemDetails, setTollHouseItemDetails] = useState(null);
    const [tollHouseItemDetailsLoading, setTollHouseItemDetailsLoading] = useState(false);

    useEffect(() => {
        setTollHouseItemDetailsLoading(true);
        requestServer(`${GET_TOLL_HOUSE_DETAILS}/${rowId}`, "get")
            .then((response) => {
                setTollHouseItemDetails(response.data.data);
                setTollHouseItemDetailsLoading(false);
            })
            .catch((e) => {
                setTollHouseItemDetailsLoading(false);
            });
    }, [rowId]);

    const defaultData = {
        phone: tollHouseItemDetails?.phone || "",
        is_province: !hasCreateProvincePermission,
        province_id: tollHouseItemDetails?.province_id || null,
        city_id: tollHouseItemDetails?.city_id || null,
        start_point: { lat: tollHouseItemDetails?.lat || "", lng: tollHouseItemDetails?.lng || "" },
        name: tollHouseItemDetails?.name || "",
        status: tollHouseItemDetails?.status || "",
        type: tollHouseItemDetails?.type || "",
        team_num: tollHouseItemDetails?.team_num || "",
        staff_num: tollHouseItemDetails?.staff_num || "",
        responsible_name: tollHouseItemDetails?.responsible_name || "",
        responsible_mobile: tollHouseItemDetails?.responsible_mobile || "",
        successor_name: tollHouseItemDetails?.successor_name || "",
        successor_mobile: tollHouseItemDetails?.successor_mobile || "",
        machines_light: tollHouseItemDetails?.machines_light || "",
        machines_sheavy: tollHouseItemDetails?.machines_sheavy || "",
        machines_heavy: tollHouseItemDetails?.machines_heavy || "",
        overview_files_1: tollHouseItemDetails?.files[0]?.path || null,
        overview_files_2: tollHouseItemDetails?.files[1]?.path || null,
        overview_files_3: tollHouseItemDetails?.files[2]?.path || null,
        overview_files_4: tollHouseItemDetails?.files[3]?.path || null,
        overview_files_5: tollHouseItemDetails?.files[4]?.path || null,
        area: tollHouseItemDetails?.area?.coordinates.map(([lat, lon]) => ({ lat, lon })) || [
            { lat: "", lon: "" },
            { lat: "", lon: "" },
            { lat: "", lon: "" },
            { lat: "", lon: "" },
        ],
    };
    const HandleSubmit = async (result) => {
        const fields = [
            "province_id",
            "city_id",
            "name",
            "status",
            "type",
            "team_num",
            "staff_num",
            "phone",
            "responsible_name",
            "responsible_mobile",
            "successor_name",
            "successor_mobile",
            "machines_light",
            "machines_sheavy",
            "machines_heavy",
        ];
        const formData = new FormData();
        fields.forEach((field) => {
            if (result[field] !== undefined && result[field] !== null) {
                formData.append(field, result[field]);
            }
        });
        for (let i = 1; i <= 5; i++) {
            if (result[`overview_files_${i}`] !== defaultData[`overview_files_${i}`]) {
                formData.append(`overview_files_${i}`, result[`overview_files_${i}`]);
            }
        }
        formData.append("lat", result.start_point.lat);
        formData.append("lng", result.start_point.lng);
        formData.append("area[type]", "polygon");
        result.area.map((point, pointIndex) => {
            formData.append(`area[coordinates][${pointIndex}][0]`, point.lat);
            formData.append(`area[coordinates][${pointIndex}][1]`, point.lon);
        });

        await requestServer(`${UPDATE_TOLL_HOUSE_ITEM}/${rowId}`, "post", {
            data: formData,
            notificationSuccess: true,
        })
            .then(() => {
                mutate();
                setOpenEditDialog(false);
            })
            .catch(() => {});
    };
    return (
        <>
            {tollHouseItemDetailsLoading ? (
                <DialogLoading />
            ) : (
                <CreateTollHouseContent
                    setOpen={setOpenEditDialog}
                    SubmitCreateTollHouse={HandleSubmit}
                    defaultValues={defaultData}
                />
            )}
        </>
    );
};
export default EditController;
