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

const Create = ({ 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);

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

    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 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: [],
                            requested_machines: [],
                            area: null,
                            locations: [],
                            type: "",
                            start_date: "",
                            start_time: null,
                            end_date: "",
                            end_time: null,
                            end_point: "",
                            region: "",
                        }}
                        submitForm={submitForm}
                        submitting={submitting}
                        open={open}
                        setOpen={setOpen}
                        mutate={mutate}
                    />
                )}
            </Dialog>
        </>
    );
};
export default Create;
