import LoadingHardPage from "@/core/components/LoadingHardPage";
import { CALL_ACTION } from "@/core/utils/routes";
import { useCall } from "@/lib/contexts/call";
import useRequest from "@/lib/hooks/useRequest";
import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Stack } from "@mui/material";
import { useForm } from "react-hook-form";
import { object, string } from "yup";
import ActionHeader from "./ActionHeader";
import CallActionDescription from "./CallActionDescription";
import CallActionsCategories from "./CallActionsCategories";
import CallActionsSubcategories from "./CallActionsSubcategories";

const defaultValues = {
    description: "",
    category_id: "",
    subcategory_id: "",
};

const validationSchema = object({
    category_id: string().required("لطفا نام کاربری را وارد کنید!"),
    subcategory_id: string().required("لطفا رمز عبور را وارد کنید!"),
});

function CallActions({ tab }) {
    const requestServer = useRequest();
    const { closeCall } = useCall();

    const {
        control,
        handleSubmit,
        formState: { isSubmitting },
    } = useForm({
        defaultValues,
        resolver: yupResolver(validationSchema),
        mode: "all",
    });

    const onSubmit = handleSubmit(async (data) => {
        try {
            const formData = new FormData();
            data.description != "" && formData.append("description", data.description);
            formData.append("category_id", data.category_id);
            formData.append("subcategory_id", data.subcategory_id);
            await requestServer(`${CALL_ACTION}/${tab.id}`, "post", {
                data: formData,
            });
            closeCall(tab.id);
        } catch (error) {}
    });

    return (
        <Stack
            sx={{
                height: "100%",
            }}
        >
            <ActionHeader tab={tab} />
            <Stack sx={{ height: "100%", overflowY: "auto", position: "relative" }}>
                <CallActionDescription control={control} />
                <CallActionsCategories control={control} />
                <CallActionsSubcategories control={control} onSubmit={onSubmit} />
                {isSubmitting && (
                    <Box
                        sx={{
                            position: "absolute",
                            width: "100%",
                            height: "100%",
                            opacity: 0.9,
                            zIndex: 9999,
                        }}
                    >
                        <LoadingHardPage width={80} height={80} loading={true} sx={{ position: "absolute" }} />
                    </Box>
                )}
            </Stack>
        </Stack>
    );
}

export default CallActions;
