import { REQUEST_MISSION_WITHOUT_PROCESS } from "@/core/utils/routes";
import useRequest from "@/lib/hooks/useRequest";
import { AddCircle, AddCircleOutline, Close } from "@mui/icons-material";
import { Button, Dialog, IconButton, useMediaQuery, useTheme } from "@mui/material";
import moment from "jalali-moment";
import { useState } from "react";
import CreateForm from "./Form";

const CreateWithoutProcess = ({ mutate }) => {
    const [submitting, setSubmitting] = useState(false);
    const requestServer = useRequest({ notificationSuccess: true });
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
    const [open, setOpen] = useState(false);

    const handleOpen = () => {
        setOpen(true);
    };

    const submitForm = async (result) => {
        setSubmitting(true);
        const bound = result.bound.getLatLngs();
        let area =
            result.bound_type === "polygon"
                ? bound.map((ring) => ring.map((latlng) => [latlng.lng, latlng.lat]))[0]
                : bound.map((latlng) => [latlng.lng, latlng.lat]);

        // بستن polygon
        if (result.bound_type === "polygon" && area.length > 0) {
            const firstPoint = area[0];
            area.push({ ...firstPoint });
        }

        await requestServer(REQUEST_MISSION_WITHOUT_PROCESS, "post", {
            data: {
                explanation: result.explanation,
                category_id: result.category_id,
                ...(result.category_id == 3
                    ? {
                          road_observed_id: result.road_observed_id,
                      }
                    : {}),
                area: {
                    type: result.bound_type,
                    coordinates: area,
                },
                ...(result.rahdaran.length != 0 ? { rahdaran: result.rahdaran.map((r) => r.id) } : {}),
                zone: result.region,
                end_point: result.end_point,
                start_date: `${result.start_date} ${moment(result.start_time).format("HH:mm")}`,
                end_date: `${result.end_date} ${moment(result.end_time).format("HH:mm")}`,
                machines: [result.machine.id],
                driver: result.driver.id,
            },
            hasSidebarUpdate: true,
        })
            .then((response) => {
                mutate();
                setOpen(false);
            })
            .catch((error) => {})
            .finally(() => {
                setSubmitting(false);
            });
    };

    return (
        <>
            {isMobile ? (
                <IconButton aria-label="ثبت ماموریت بدون فرایند" color="primary" onClick={handleOpen}>
                    <AddCircleOutline sx={{ fontSize: "25px" }} />
                </IconButton>
            ) : (
                <Button
                    size={"small"}
                    variant="contained"
                    color="primary"
                    startIcon={<AddCircle />}
                    onClick={handleOpen}
                >
                    ثبت ماموریت بدون فرایند
                </Button>
            )}
            <Dialog open={open} fullWidth maxWidth="sm">
                <IconButton
                    aria-label="close"
                    onClick={() => setOpen(false)}
                    sx={(theme) => ({
                        position: "absolute",
                        right: 8,
                        top: 8,
                        zIndex: 50,
                        color: theme.palette.grey[500],
                    })}
                >
                    <Close />
                </IconButton>
                {open && (
                    <CreateForm
                        defaultValues={{
                            explanation: "",
                            category_id: "",
                            road_observed_id: "",
                            rahdaran: [],
                            bound: null,
                            bound_type: "polyline",
                            start_date: "",
                            start_time: null,
                            end_date: "",
                            end_time: null,
                            end_point: "",
                            region: "",
                            machine: null,
                            driver: null,
                        }}
                        submitForm={submitForm}
                        submitting={submitting}
                        open={open}
                        setOpen={setOpen}
                        mutate={mutate}
                    />
                )}
            </Dialog>
        </>
    );
};
export default CreateWithoutProcess;
