import LtrTextField from "@/core/components/LtrTextField";
import StyledForm from "@/core/components/StyledForm";
import { yupResolver } from "@hookform/resolvers/yup";
import {
    Box,
    Button,
    Checkbox,
    Chip,
    DialogActions,
    DialogContent,
    Divider,
    FormControlLabel,
    FormHelperText,
    Grid,
    Skeleton,
    Stack,
} from "@mui/material";
import { Controller, useForm } from "react-hook-form";
import { array, object, string } from "yup";
import useRequest from "@/lib/hooks/useRequest";
import { ROLE_SERVICE } from "@/core/utils/routes";
import usePermissionsList from "@/lib/hooks/usePermissionsList";

const defaultValues = {
    name: "",
    name_fa: "",
    permissions: [],
};

const validationSchema = object().shape({
    name: string().required("نام فارسی نقش را وارد کنید"),
    name_fa: string().required("نام انگلیسی نقش را وارد کنید"),
    permissions: array().min(1, "حداقل یک دسترسی را انتخاب نمایید"),
});

const CreateRoleForm = ({ setOpen, mutate }) => {
    const requestServer = useRequest({ notificationSuccess: true });
    const { permissions, loadingPermissions } = usePermissionsList();

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

    const onSubmit = async (data) => {
        try {
            await requestServer(ROLE_SERVICE, "post", {
                data: {
                    permissions: data.permissions,
                    name: data.name,
                    name_fa: data.name_fa,
                },
            });
            setOpen(false);
            mutate();
        } catch (error) {}
    };

    return (
        <>
            <DialogContent dividers>
                <Divider sx={{ mb: 3 }}>
                    <Chip color="primary" variant="outlined" label="نقش جدید" />
                </Divider>
                <StyledForm
                    id="createRoleForm"
                    onSubmit={handleSubmit(onSubmit)}
                    style={{ width: "100%", height: "100%" }}
                >
                    <Stack spacing={2}>
                        <Grid container spacing={2}>
                            <Grid size={{ xs: 12, md: 6 }}>
                                <Controller
                                    control={control}
                                    render={({ field, fieldState: { error } }) => {
                                        return (
                                            <LtrTextField
                                                {...field}
                                                label="نام انگلیسی نقش"
                                                variant="outlined"
                                                fullWidth
                                                error={!!error}
                                                helperText={!!error && error.message}
                                            />
                                        );
                                    }}
                                    name={"name"}
                                />
                            </Grid>
                            <Grid size={{ xs: 12, md: 6 }}>
                                <Controller
                                    control={control}
                                    render={({ field, fieldState: { error } }) => {
                                        return (
                                            <LtrTextField
                                                {...field}
                                                label="نام فارسی نقش"
                                                variant="outlined"
                                                fullWidth
                                                error={!!error}
                                                helperText={!!error && error.message}
                                            />
                                        );
                                    }}
                                    name={"name_fa"}
                                />
                            </Grid>
                            <Box sx={{ width: "100%" }}>
                                <Divider>
                                    <Chip label="سطوح دسترسی" size="medium" />
                                </Divider>
                            </Box>
                            <Grid container spacing={1} sx={{ width: "100%" }}>
                                {!loadingPermissions ? (
                                    <Controller
                                        control={control}
                                        name="permissions"
                                        render={({ field, fieldState: { error } }) => (
                                            <>
                                                {permissions.map((permission) => (
                                                    <Grid key={permission.id} size={{ xs: 12, md: 4 }}>
                                                        <FormControlLabel
                                                            control={
                                                                <Checkbox
                                                                    value={permission.id}
                                                                    checked={field.value.includes(permission.id)}
                                                                    onChange={(e) => {
                                                                        const value = parseInt(e.target.value, 10);
                                                                        if (e.target.checked) {
                                                                            field.onChange([...field.value, value]);
                                                                        } else {
                                                                            field.onChange(
                                                                                field.value.filter((id) => id !== value)
                                                                            );
                                                                        }
                                                                    }}
                                                                />
                                                            }
                                                            label={permission.name_fa}
                                                        />
                                                    </Grid>
                                                ))}
                                                <FormHelperText sx={{ color: "error.main" }}>
                                                    {!!error && error.message}
                                                </FormHelperText>
                                            </>
                                        )}
                                    />
                                ) : (
                                    <Grid container spacing={2} width="100%">
                                        <Grid size={{ xs: 12, md: 4 }}>
                                            <Skeleton animation="wave" />
                                        </Grid>
                                        <Grid size={{ xs: 12, md: 4 }}>
                                            <Skeleton animation="wave" />
                                        </Grid>
                                        <Grid size={{ xs: 12, md: 4 }}>
                                            <Skeleton animation="wave" />
                                        </Grid>
                                        <Grid size={{ xs: 12, md: 4 }}>
                                            <Skeleton animation="wave" />
                                        </Grid>
                                        <Grid size={{ xs: 12, md: 4 }}>
                                            <Skeleton animation="wave" />
                                        </Grid>
                                        <Grid size={{ xs: 12, md: 4 }}>
                                            <Skeleton animation="wave" />
                                        </Grid>
                                    </Grid>
                                )}
                            </Grid>
                        </Grid>
                    </Stack>
                </StyledForm>
            </DialogContent>
            <DialogActions>
                <Button
                    disabled={isSubmitting}
                    variant="outlined"
                    color="secondary"
                    size="large"
                    onClick={() => setOpen(false)}
                >
                    بستن
                </Button>
                <Button
                    type="submit"
                    disabled={isSubmitting}
                    form="createRoleForm"
                    size="large"
                    autoFocus
                    variant="contained"
                >
                    {isSubmitting ? "در حال ثبت نقش جدید..." : "ثبت نقش جدید"}
                </Button>
            </DialogActions>
        </>
    );
};

export default CreateRoleForm;
