"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 = {
        savaneh_id: initialValues?.savaneh_id ?? "",
        action_id: initialValues?.action_id ?? "",
        description: initialValues?.description ?? "",
    };

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

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

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

    useEffect(() => {
        reset({
            savaneh_id: initialValues?.savaneh_id ?? "",
            action_id: initialValues?.action_id ?? "",
            description: initialValues?.description ?? "",
        });
    }, [initialValues.savaneh_id, initialValues.action_id, 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="savaneh_id"
                                        name="savaneh_id"
                                        size="small"
                                        sx={{ width: "100px", fontSize: "12px" }}
                                        value={field.value}
                                        label="پیگیری"
                                        onChange={(e) => field.onChange(e.target.value)}
                                    >
                                        <MenuItem value={1}>عدم نیاز به ثبت (مشکل راه)</MenuItem>
                                        <MenuItem value={2}>عدم نیاز به ثبت (مشکل حمل و نقلی)</MenuItem>
                                        <MenuItem value={3}>عدم نیاز به ثبت (مشکل عوارضی)</MenuItem>
                                        <MenuItem value={4}>ثبت سوانح (مشکل راه)</MenuItem>
                                        <MenuItem value={5}>ثبت سوانح (مشکل حمل و نقلی)</MenuItem>
                                    </Select>
                                </FormControl>
                            );
                        }}
                        name="savaneh_id"
                    />
                </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="action_id"
                    />
                </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;
