import {
    Autocomplete,
    Button,
    CircularProgress,
    DialogActions,
    DialogContent,
    FormControl,
    FormHelperText,
    InputLabel,
    OutlinedInput,
    Stack,
    TextField,
    Typography,
} from "@mui/material";
import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string } from "yup";
import StyledForm from "@/core/components/StyledForm";
import useProvinces from "@/lib/hooks/useProvince";
import useRequest from "@/lib/hooks/useRequest";
import { REFER_ADMIN_PROVINCE } from "@/core/utils/routes";

const validationSchema = object({
    description: string().required("وارد کردن توضیحات الزامیست!"),
    province: string().required("وارد کردن استان الزامیست!"),
});

const ReferFormContext = ({ setOpenReferDialog, rowId, mutate }) => {
    const defaultValues = {
        description: "",
        province: "",
    };
    const { provinces, loadingProvinces, errorProvinces } = useProvinces();
    const requestServer = useRequest({ auth: true });
    const {
        control,
        register,
        handleSubmit,
        formState: { isSubmitting, errors, touchedFields },
    } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "onBlur" });

    const onSubmit = async (data) => {
        const formData = new FormData();
        formData.append("description", data.description);
        formData.append("provinceId", data.province);

        requestServer(`${REFER_ADMIN_PROVINCE}/${rowId}`, "post", {
            data: formData,
        })
            .then(() => {
                setOpenReferDialog(false);
                mutate();
            })
            .catch(() => {});
    };
    return (
        <StyledForm onSubmit={handleSubmit(onSubmit)}>
            <DialogContent>
                <Stack spacing={2}>
                    <Stack>
                        <FormControl error={!!errors.description} size="small" fullWidth variant="outlined">
                            <InputLabel sx={{ pt: 1 }} htmlFor="description">
                                توضیحات
                            </InputLabel>
                            <OutlinedInput
                                id="description"
                                label={"توضیحات"}
                                multiline
                                rows={8}
                                autoComplete="off"
                                {...register("description")}
                                size="small"
                                fullWidth
                                sx={{ mt: 1 }}
                                type="text"
                            />
                            <FormHelperText id="description">
                                {errors.description ? errors.description.message : null}
                            </FormHelperText>
                        </FormControl>
                    </Stack>
                    <Stack>
                        <Controller
                            name="province"
                            control={control}
                            render={({ field: { onChange, value }, fieldState: { error } }) => (
                                <FormControl error={!!error} size="small" fullWidth variant="outlined">
                                    <InputLabel htmlFor="province" />
                                    {errorProvinces ? (
                                        <Typography color={"red"}>خطایی در دریافت استان ها رخ داده است!</Typography>
                                    ) : loadingProvinces ? (
                                        <Typography sx={{ display: "flex", alignItems: "center", gap: 2 }}>
                                            <CircularProgress size={20} />
                                            درحال دریافت لیست استان ها
                                        </Typography>
                                    ) : (
                                        <Autocomplete
                                            id="province"
                                            size="small"
                                            value={provinces.find((province) => province.id === value) || null}
                                            disablePortal
                                            options={provinces}
                                            getOptionLabel={(province) => province.name}
                                            isOptionEqualToValue={(option, value) => option.id === value.id}
                                            onChange={(event, newValue) => {
                                                onChange(newValue ? newValue.id : "");
                                            }}
                                            renderInput={(params) => (
                                                <TextField
                                                    {...params}
                                                    autoComplete="off"
                                                    error={!!errors.province}
                                                    fullWidth
                                                    label="استان"
                                                />
                                            )}
                                        />
                                    )}
                                    <FormHelperText id="province">
                                        {errors.province ? errors.province.message : null}
                                    </FormHelperText>
                                </FormControl>
                            )}
                        />
                    </Stack>
                </Stack>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => setOpenReferDialog(false)} variant="outlined" color="secondary" autoFocus>
                    {"انصراف"}
                </Button>
                <Button variant="contained" color="primary" type={"submit"} disabled={isSubmitting}>
                    {isSubmitting ? "در حال اسال" : "ارجاع"}
                </Button>
            </DialogActions>
        </StyledForm>
    );
};
export default ReferFormContext;
