"use client";

import {
    Autocomplete,
    Avatar,
    Backdrop,
    Box,
    Button,
    Chip,
    Divider,
    FormControl,
    FormHelperText,
    Grid,
    InputLabel,
    OutlinedInput,
    TextField,
} from "@mui/material";
import StyledForm from "@/core/components/StyledForm";
import useRequest from "@/lib/hooks/useRequest";
import { Controller, useForm } from "react-hook-form";
import { useAuth } from "@/lib/contexts/auth";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { styled } from "@mui/material/styles";
import { useEffect, useState } from "react";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string } from "yup";
import { UPDATE_USER_ROUTE } from "@/core/utils/routes";

const degreeItems = ["دیپلم", "کارشناسی", "کارشناسی ارشد", "دکترا"];

const VisuallyHiddenInput = styled("input")({
    clip: "rect(0 0 0 0)",
    clipPath: "inset(50%)",
    height: 1,
    overflow: "hidden",
    position: "absolute",
    bottom: 0,
    left: 0,
    whiteSpace: "nowrap",
    width: 1,
});

const validationSchema = object({
    first_name: string().required("اجباری"),
    last_name: string().required("اجباری"),
    degree: string().required("اجباری"),
    major: string().required("اجباری"),
    mobile: string().required("اجباری"),
});

const Form = ({ handleCloseForm, setLoading }) => {
    const request = useRequest();
    const { user, getUser } = useAuth();
    const [uploadBackDrop, setUploadBackDrop] = useState(false);
    const defaultValues = {
        first_name: user.first_name,
        last_name: user.last_name,
        major: user.major,
        degree: user.degree,
        mobile: user.mobile,
        avatar: null,
    };

    const {
        control,
        watch,
        register,
        setValue,
        handleSubmit,
        formState: { isSubmitting, errors },
    } = useForm({ defaultValues, resolver: yupResolver(validationSchema) });

    useEffect(() => {
        setLoading(isSubmitting);
    }, [isSubmitting]);

    const onSubmit = async (data) => {
        const formData = new FormData();
        formData.append("first_name", data.first_name);
        formData.append("last_name", data.last_name);
        formData.append("major", data.major);
        formData.append("degree", data.degree);
        formData.append("mobile", data.mobile);
        if (data.avatar) {
            formData.append("avatar", data.avatar);
        }

        try {
            await request(UPDATE_USER_ROUTE, "post", { data: formData });
            getUser();
            handleCloseForm();
        } catch (error) {}
    };

    return (
        <>
            <Divider sx={{ mb: 3 }}>
                <Chip color="success" variant="outlined" label="ویرایش پروفایل" />
            </Divider>
            <StyledForm onSubmit={handleSubmit(onSubmit)} id={"UpdateProfile"}>
                <Box
                    sx={{
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                        justifyContent: "center",
                        mb: 4,
                        position: "relative",
                        borderRadius: "50%",
                    }}
                >
                    <Button
                        component="label"
                        sx={{
                            borderRadius: "50%",
                            padding: "unset",
                            "&:hover": {
                                backgroundColor: "unset",
                            },
                        }}
                    >
                        <Box
                            sx={{ borderRadius: "50%" }}
                            onMouseEnter={() => setUploadBackDrop(true)}
                            onMouseLeave={() => setUploadBackDrop(false)}
                        >
                            <Avatar src={user?.avatar} sx={{ width: 120, height: 120, border: "1px solid #e1e1e1" }} />
                            <Backdrop
                                sx={{
                                    color: "#fff",
                                    zIndex: (theme) => theme.zIndex.drawer + 1,
                                    position: "absolute",
                                    width: 120,
                                    height: 120,
                                    marginLeft: "auto",
                                    marginRight: "auto",
                                    borderRadius: "50%",
                                }}
                                open={uploadBackDrop}
                            >
                                <CloudUploadIcon sx={{ fontSize: "2rem" }} color="inherit" />
                            </Backdrop>
                        </Box>
                        <VisuallyHiddenInput
                            type="file"
                            accept="image/*"
                            onChange={(event) => setValue("avatar", event.target.files[0])}
                        />
                    </Button>
                </Box>
                <Grid container columns={{ xs: 1, sm: 2 }} spacing={2}>
                    <Grid item xs={1}>
                        <FormControl error={!!errors.first_name} size="small" fullWidth variant="outlined">
                            <InputLabel htmlFor="first_name">نام</InputLabel>
                            <OutlinedInput
                                id="first_name"
                                label="نام"
                                autoComplete="off"
                                {...register("first_name")}
                                size="small"
                                fullWidth
                                type="text"
                            />
                            <FormHelperText id="first_name">
                                {errors.first_name ? errors.first_name.message : null}
                            </FormHelperText>
                        </FormControl>
                    </Grid>
                    <Grid item xs={1}>
                        <FormControl error={!!errors.last_name} size="small" fullWidth variant="outlined">
                            <InputLabel htmlFor="last_name">نام خانوادگی</InputLabel>
                            <OutlinedInput
                                id="last_name"
                                label="نام خانوادگی"
                                autoComplete="off"
                                {...register("last_name")}
                                size="small"
                                fullWidth
                                type="text"
                            />
                            <FormHelperText id="last_name">
                                {errors.last_name ? errors.last_name.message : null}
                            </FormHelperText>
                        </FormControl>
                    </Grid>
                    <Grid item xs={1}>
                        <FormControl error={!!errors.major} size="small" fullWidth variant="outlined">
                            <InputLabel htmlFor="major">رشته تحصیلی</InputLabel>
                            <OutlinedInput
                                id="major"
                                label="رشته تحصیلی"
                                autoComplete="off"
                                {...register("major")}
                                size="small"
                                fullWidth
                                type="text"
                            />
                            <FormHelperText id="major">{errors.major ? errors.major.message : null}</FormHelperText>
                        </FormControl>
                    </Grid>
                    <Grid item xs={1}>
                        <Controller
                            name="degree"
                            control={control}
                            render={({ field: { onChange, value }, fieldState: { error } }) => (
                                <FormControl error={!!error} size="small" fullWidth variant="outlined">
                                    <Autocomplete
                                        size="small"
                                        disablePortal
                                        value={value || null}
                                        onChange={(event, newValue) => {
                                            onChange(newValue);
                                        }}
                                        options={degreeItems}
                                        renderInput={(params) => (
                                            <TextField
                                                {...params}
                                                label="مدرک تحصیلی"
                                                placeholder="مدرک تحصیلی را انتخاب کنید"
                                                autoComplete="off"
                                                error={!!error}
                                                InputLabelProps={{ shrink: true }}
                                            />
                                        )}
                                    />
                                    <FormHelperText>{error ? error.message : null}</FormHelperText>
                                </FormControl>
                            )}
                        />
                    </Grid>
                    <Grid item xs={2}>
                        <FormControl error={!!errors.mobile} size="small" fullWidth variant="outlined">
                            <InputLabel htmlFor="mobile">موبایل</InputLabel>
                            <OutlinedInput
                                id="mobile"
                                label="موبایل"
                                autoComplete="off"
                                {...register("mobile")}
                                size="small"
                                fullWidth
                                type="text"
                            />
                            <FormHelperText id="mobile">{errors.mobile ? errors.mobile.message : null}</FormHelperText>
                        </FormControl>
                    </Grid>
                </Grid>
            </StyledForm>
        </>
    );
};
export default Form;
