"use client";

import { Button, FormControl, FormHelperText, Grid, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material";
import LtrTextField from "@/core/components/LtrTextField";
import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string, number } from "yup";
import { GET_SYSTEM_MESSAGES_SUPERVISOR } from "@/core/utils/routes";
import StyledForm from "@/core/components/StyledForm";
import useRequest from "@/lib/hooks/useRequest";
import usePermissionsList from "@/lib/hooks/usePermissionsList";
import { useEffect } from "react";

const RateMessage = ({ messageId, initialValues, mutate }) => {
    const requestServer = useRequest({ notificationSuccess: true });

    const defaultValues = {
        message_quality: initialValues?.message_quality ?? "",
        format_quality: initialValues?.format_quality ?? "",
        description: initialValues?.description ?? "",
    };

    const validationSchema = object().shape({
        message_quality: string().required("وضعیت کیفیت پیام را مشخص کنید"),
        format_quality: string().required("وضعیت فرمت پیام را مشخص کنید"),
        description: string().optional(),
    });

    const {
        control,
        handleSubmit,
        reset,
        formState: { isSubmitting, errors, isDirty, isValid },
    } = useForm({ defaultValues, resolver: yupResolver(validationSchema) });

    const onSubmit = async (data) => {
        const fixData = {
            message_quality: parseInt(data.message_quality),
            format_quality: parseInt(data.format_quality),
            ...(data.description !== "" && { description: data.description }),
        };
        try {
            await requestServer(`${GET_SYSTEM_MESSAGES_SUPERVISOR}/${messageId}`, "post", {
                data: fixData,
            });
            mutate();
            reset({
                message_quality: initialValues?.message_quality ?? "",
                format_quality: initialValues?.format_quality ?? "",
                description: initialValues?.description ?? "",
            });
        } catch (error) {}
    };

    useEffect(() => {
        reset({
            message_quality: initialValues?.message_quality ?? "",
            format_quality: initialValues?.format_quality ?? "",
            description: initialValues?.description ?? "",
        });
    }, [initialValues.message_quality, initialValues.format_quality, initialValues.description]);

    return (
        <StyledForm id="monitoringForm" onSubmit={handleSubmit(onSubmit)} style={{ width: "100%", height: "100%" }}>
            <Grid container spacing={2} sx={{ flexWrap: "nowrap", alignItems: "start" }}>
                <Grid item sx={{ xs: 3, sm: 3 }}>
                    <Controller
                        control={control}
                        render={({ field, fieldState: { error } }) => {
                            return (
                                <FormControl fullWidth error={!!error} variant="outlined">
                                    <InputLabel id="label-message-quality" size="small" sx={{ fontSize: "12px" }}>
                                        کیفیت پیام
                                    </InputLabel>
                                    <Select
                                        variant="outlined"
                                        labelId="label-message-quality"
                                        id="message_quality"
                                        name="message_quality"
                                        size="small"
                                        sx={{ width: "100px", fontSize: "12px" }}
                                        value={field.value}
                                        label="کیفیت پیام"
                                        onChange={(e) => field.onChange(e.target.value)}
                                    >
                                        <MenuItem value={0}>نامناسب</MenuItem>
                                        <MenuItem value={1}>مناسب</MenuItem>
                                    </Select>
                                </FormControl>
                            );
                        }}
                        name="message_quality"
                    />
                </Grid>
                <Grid item sx={{ xs: 3, sm: 3 }}>
                    <Controller
                        control={control}
                        render={({ field, fieldState: { error } }) => {
                            return (
                                <FormControl fullWidth error={!!error} variant="outlined">
                                    <InputLabel id="label-format-quality" size="small" sx={{ fontSize: "12px" }}>
                                        فرمت پیام
                                    </InputLabel>
                                    <Select
                                        variant="outlined"
                                        labelId="label-format-quality"
                                        id="format_quality"
                                        name="format_quality"
                                        size="small"
                                        sx={{ width: "100px", fontSize: "12px" }}
                                        value={field.value}
                                        label="فرمت پیام"
                                        onChange={(e) => field.onChange(e.target.value)}
                                    >
                                        <MenuItem value={0}>نامناسب</MenuItem>
                                        <MenuItem value={1}>مناسب</MenuItem>
                                    </Select>
                                </FormControl>
                            );
                        }}
                        name="format_quality"
                    />
                </Grid>
                <Grid item sx={{ xs: 3, sm: 3 }}>
                    <Controller
                        control={control}
                        render={({ field, fieldState: { error } }) => {
                            return (
                                <LtrTextField
                                    {...field}
                                    variant="outlined"
                                    label="توضیحات"
                                    size="small"
                                    sx={{
                                        width: "180px",
                                    }}
                                    InputProps={{ sx: { fontSize: "12px" } }}
                                    InputLabelProps={{ sx: { fontSize: "12px" } }}
                                    error={!!error}
                                    helperText={!!error && error.message}
                                />
                            );
                        }}
                        name="description"
                    />
                </Grid>
                <Grid item sx={{ xs: 3, sm: 3 }}>
                    <Button
                        type="submit"
                        disabled={isSubmitting || !isDirty || !isValid}
                        size="medium"
                        autoFocus
                        variant="contained"
                    >
                        {isSubmitting ? "درحال ثبت..." : "ثبت"}
                    </Button>
                </Grid>
            </Grid>
        </StyledForm>
    );
};

export default RateMessage;
