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 useCities from "@/lib/hooks/useCities";
import useRequest from "@/lib/hooks/useRequest";
import { REFER_ADMIN_CITY } from "@/core/utils/routes";

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

const ReferFormContext = ({ setOpenReferDialog, rowId, mutate }) => {
    const defaultValues = {
        description: "",
        city: "",
    };
    const { cities, loadingCities, errorCities } = useCities();
    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("cityId", data.city);
        requestServer(`${REFER_ADMIN_CITY}/${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="city"
                            control={control}
                            render={({ field: { onChange, value }, fieldState: { error } }) => (
                                <FormControl error={!!error} size="small" fullWidth variant="outlined">
                                    <InputLabel htmlFor="city" />
                                    {errorCities ? (
                                        <Typography color={"red"}>خطایی در دریافت شهرستان ها رخ داده است!</Typography>
                                    ) : loadingCities ? (
                                        <Typography sx={{ display: "flex", alignItems: "center", gap: 2 }}>
                                            <CircularProgress size={20} />
                                            درحال دریافت لیست شهرستان ها
                                        </Typography>
                                    ) : (
                                        <Autocomplete
                                            id="city"
                                            size="small"
                                            value={cities.find((city) => city.id === value) || null}
                                            disablePortal
                                            options={cities}
                                            getOptionLabel={(city) => city.name}
                                            isOptionEqualToValue={(option, value) => option.id === value.id}
                                            onChange={(event, newValue) => {
                                                onChange(newValue ? newValue.id : "");
                                            }}
                                            renderInput={(params) => (
                                                <TextField
                                                    {...params}
                                                    autoComplete="off"
                                                    error={!!errors.city}
                                                    fullWidth
                                                    label="شهرستان"
                                                />
                                            )}
                                        />
                                    )}
                                    <FormHelperText id="city">
                                        {errors.city ? errors.city.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;
