import { Button, Dialog, IconButton, useMediaQuery } from "@mui/material";
import { useState } from "react";
import CreateTollHouseContent from "./CreateTollHouseContent";
import { AddCircle } from "@mui/icons-material";
import { useTheme } from "@emotion/react";
import { CREATE_TOLL_HOUSE } from "@/core/utils/routes";
import useRequest from "@/lib/hooks/useRequest";
import CloseIcon from "@mui/icons-material/Close";
import { useAuth } from "@/lib/contexts/auth";
import { usePermissions } from "@/lib/hooks/usePermissions";

const CreateTollHouse = ({ mutate }) => {
    const requestServer = useRequest({ notificationSuccess: true });
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
    const [open, setOpen] = useState(false);
    const { user } = useAuth();
    const { data: userPermissions } = usePermissions();
    const hasCreateProvincePermission = userPermissions.some((item) => ["add-tollhouse"].includes(item));
    const handleOpen = () => {
        setOpen(true);
    };
    const SubmitCreateTollHouse = 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",
            "overview_files_1",
            "overview_files_2",
            "overview_files_3",
            "overview_files_4",
            "overview_files_5",
        ];
        const formData = new FormData();
        fields.forEach((field) => {
            if (result[field] !== undefined && result[field] !== null) {
                formData.append(field, result[field]);
            }
        });
        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.lon);
            formData.append(`area[coordinates][${pointIndex}][1]`, point.lat);
        });
        const repeat_first = result.area.length;
        formData.append(`area[coordinates][${repeat_first}][0]`, result.area[0].lon);
        formData.append(`area[coordinates][${repeat_first}][1]`, result.area[0].lat);
        await requestServer(`${CREATE_TOLL_HOUSE}`, "post", {
            data: formData,
        })
            .then(() => {
                mutate();
                setOpen(false);
            })
            .catch(() => {});
    };
    const defaultValues = {
        name: "",
        is_province: !hasCreateProvincePermission,
        province_id: !hasCreateProvincePermission ? user.province_id : null,
        city_id: null,
        status: "",
        type: "",
        phone: "",
        team_num: "",
        staff_num: "",
        responsible_name: "",
        responsible_mobile: "",
        successor_name: "",
        successor_mobile: "",
        machines_light: "",
        machines_sheavy: "",
        machines_heavy: "",
        overview_files_1: null,
        overview_files_2: null,
        overview_files_3: null,
        overview_files_4: null,
        overview_files_5: null,
        start_point: "",
        area: [
            { lat: "", lon: "" },
            { lat: "", lon: "" },
            { lat: "", lon: "" },
            { lat: "", lon: "" },
        ],
    };
    return (
        <>
            {isMobile ? (
                <IconButton aria-label={"راهدارخانه جدید"} color="primary" onClick={handleOpen}>
                    <AddCircle sx={{ fontSize: "25px" }} />
                </IconButton>
            ) : (
                <Button
                    size={"small"}
                    variant="contained"
                    color="primary"
                    startIcon={<AddCircle />}
                    onClick={handleOpen}
                >
                    راهدارخانه جدید
                </Button>
            )}
            <Dialog
                fullWidth
                open={open}
                onClose={() => setOpen(false)}
                PaperProps={{
                    sx: {
                        boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px",
                    },
                }}
                maxWidth={"md"}
                scroll="paper"
            >
                <IconButton
                    aria-label="close"
                    onClick={() => setOpen(false)}
                    sx={(theme) => ({
                        position: "absolute",
                        right: 8,
                        top: 8,
                        zIndex: 50,
                        color: theme.palette.grey[500],
                    })}
                >
                    <CloseIcon />
                </IconButton>
                {open && (
                    <CreateTollHouseContent
                        setOpen={setOpen}
                        defaultValues={defaultValues}
                        SubmitCreateTollHouse={SubmitCreateTollHouse}
                    />
                )}
            </Dialog>
        </>
    );
};
export default CreateTollHouse;
