"use client"
import React, { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { useMounted } from '@/hooks/useMounted';
import { useTranslations } from 'next-intl';
import { makeStyles } from 'tss-react/mui';
import { getAccountType, getCompanyDomain, getServicePath, getTitleOfEmailField, getTitleOfPasswordField, getViewSettings } from '@/lib/redux/features/serviceAdmin';
import { z } from 'zod';
import { APP_URL, IMAGE_PATH, OPTION_LOGIN, PATTERNS, USER_CONFIG } from '@/lib/appConstant';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { FormItem, FormWrapper } from '../../ui/form';
import { Col, Row } from 'antd';
import CircularProgress from '@mui/material/CircularProgress';
import InputField from '../../ui/input/input-field';
// import AppButton from '../ui/button/button';
import Link from 'next/link';
import { getAuthIsLoading, getIsRegistered, getIsRegistering, registerAccountUser, resetRegister } from '@/lib/redux/features/auth';
import { useRouter } from 'next/navigation';
import { hashMD5 } from '@/lib/utils';
import AppButton from '../../ui/button/app-button';

const useStyles = makeStyles()(theme => ({
    cardBody: {

    },
    formControlContainer: {
        // marginTop: theme.spacing(2),
        // marginBottom: theme.spacing(2)
    },
    buttonContainer: {
        justifyContent: 'center',
        marginTop: theme.spacing(2)
    },
    form: {
        width: '100vw',
        maxWidth: '400px',
        padding: '15px',
        '& input': {
            minHeight: 'unset!important',
            fontSize: '1rem',
            borderColor: '#ced4da',
            flex: 'none'
        },
        '& input:focus': {
            borderColor: '#80bdff',
            outline: 0,
            boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)!important'
        },
        '& input:hover': {
            borderColor: '#ced4da'
        }
    }
}));

type PropsType = {
    location: any;
    loginRole: any;
}

export default function SignUpForm(props: PropsType) {
    const {
        loginRole,
    } = props;

    const t = useTranslations("");
    const mounted = useMounted();
    const dispatch = useAppDispatch();
    const router = useRouter();


    const viewSettings = useAppSelector(getViewSettings);
    const domain = useAppSelector(getCompanyDomain);
    const servicePath = useAppSelector(getServicePath);

    const titleOfEmailField = useAppSelector(getTitleOfEmailField);
    const titleOfPasswordField = useAppSelector(getTitleOfPasswordField);
    const isLoading = useAppSelector(getAuthIsLoading);
    const accountType = useAppSelector(getAccountType);
    const isRegistering = useAppSelector(getIsRegistering);
    const isRegistered = useAppSelector(getIsRegistered);



    const isStrictPassword = viewSettings.strictPassword;

    useEffect(() => {
        if (isRegistered) {
            router.push(`${servicePath ? '/'+servicePath : ''}/login`);
            dispatch(resetRegister());
        }
    }, [isRegistered]);

    
    const submit = data => {
        const request: any = {
            passwordHash: hashMD5(data.password),
            domain: domain,
            path: servicePath && servicePath !== '' ? servicePath : domain,
            fullName: data.name
        };
        request.email = data.email;
        dispatch(registerAccountUser(request));
    };

    const zodValidations = {
        email: z.string()
            .max(255, t('validate.max_length_255'))
            .min(1, t('validate.required'))
            .regex(PATTERNS.EMAIL_PATTERN, {
                message: t('validate.email.invalid')
            }),
        username: z.string()
            .min(6, t('validate.required'))
            .max(64, t('validate.max_length_32'))
            .regex(PATTERNS.USERNAME_PATTERN, {
                message: t('validate.username.invalid')
            })
            .refine(value => !value.includes(' '), t('validate.username.required')),
        emailOrUsername: z.string()
            .max(255, t('validate.max_length_255'))
            .min(6, t('validate.required')),
        password: z.string()
            .min(1, t('validate.required'))
            .regex(PATTERNS.PASSWORD_PATTERN, {
                message: t('validate.password.minLength')
            })
            .max(32, t('validate.max_length_32'))
            .regex(PATTERNS.PASSWORD_UPPER, {
                message: t('validate.password.uppercase')
            })
            .regex(PATTERNS.PASSWORD_LOWER, {
                message: t('validate.password.lowercase')
            })
            .regex(PATTERNS.PASSWORD_NUMBER, {
                message: t('validate.password.number')
            })
            .refine(value => !value.includes(' '), t('validate.password.spaces')),
        
        weakPassword: z.string()
            .min(4, t('validate.min_length_4'))
            .max(16, t('validate.max_length_16'))
            .refine(value => !value.includes(' '), t('validate.password.spaces')),
    }
    const formSchema = z
        .object({
            name: z.string().trim()
                .max(64, t('validate.max_length_64'))
                .min(2, t('validate.min_length_2')),
            email: accountType === OPTION_LOGIN.ALL
            ? zodValidations.emailOrUsername
            : accountType === OPTION_LOGIN.EMAIL
                ? zodValidations.email
                : zodValidations.username,
            password: isStrictPassword ? zodValidations.password : zodValidations.weakPassword,
            confirmPassword: isStrictPassword ? zodValidations.password : zodValidations.weakPassword,
        })
        .refine((data) => data.password === data.confirmPassword, {
            message: t("validate.confirmPassword.mismatch"),
            path: ["confirmPassword"],
        });
    
    type SignUpFormSchema = z.infer<typeof formSchema>;
    

    const signUpForm = useForm<SignUpFormSchema>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            name: '',
            email: '',
            password: '',
            confirmPassword: ''
        }
    });

    const values = signUpForm.getValues();
    const { classes } = useStyles();

    if (isLoading) {
        return (
            <Row
                align="middle"
                justify="center"
            >
                <Col span={24}>
                    <CircularProgress color='primary' style={{ marginRight: 20 }} />
                    {t('progress.loading')}
                </Col>
            </Row>
        );
    }
  return (
    <FormWrapper<SignUpFormSchema>
        form={signUpForm}
        onSubmit={submit}
        layout="vertical"
        // className="space-y-4"
    >
        <div className={classes.cardBody}>
            <FormItem name="name" label={t('label.name')}>
                {({ value, ref, ...field }) => (
                    <InputField
                        name="name"
                        placeholder={t('label.name')}
                        {...field}
                    />
                )}
            </FormItem>
            <FormItem
                name="email"
                label={
                    titleOfEmailField && titleOfEmailField !== '' && loginRole === USER_CONFIG.USER.roleLevel
                    ? titleOfEmailField
                    : t(loginRole !== USER_CONFIG.USER.roleLevel ? 'label.email' : accountType === OPTION_LOGIN.ALL ? 'label.emailOrUser' : accountType === OPTION_LOGIN.EMAIL ? 'label.email' : 'label.username')
                }
            >
                {({ value, ref, ...field }) => (
                    <InputField
                        name="email"
                        placeholder={titleOfEmailField && titleOfEmailField !== '' && loginRole === USER_CONFIG.USER.roleLevel
                            ? titleOfEmailField
                            : t(loginRole !== USER_CONFIG.USER.roleLevel ? 'label.email' : accountType === OPTION_LOGIN.ALL ? 'label.emailOrUser' : accountType === OPTION_LOGIN.EMAIL ? 'label.email' : 'label.username')
                        }
                        {...field}
                    />
                )}
            </FormItem>
            <FormItem
                name="password"
                label={titleOfPasswordField && titleOfPasswordField !== '' && loginRole === USER_CONFIG.USER.roleLevel
                    ? titleOfPasswordField
                    : t('label.password')
                }>
                {({ value, ref, ...field }) => (
                    <InputField
                        name="password"
                        type='password'
                        placeholder={titleOfPasswordField && titleOfPasswordField !== '' && loginRole === USER_CONFIG.USER.roleLevel
                            ? titleOfPasswordField
                            : t('label.password')
                            }
                        {...field}
                    />
                )}
            </FormItem>
            
            <FormItem
                name="confirmPassword"
                label={t('label.confirmPassword')}>
                {({ value, ref, ...field }) => (
                    <InputField
                        name="password"
                        type='password'
                        placeholder={t('label.confirmPassword')}
                        {...field}
                    />
                )}
            </FormItem>
            <div className="mb-[1rem]">
                <AppButton
                    type="submit"
                    className='w-full'
                    disabled={!!isRegistering}
                >
                    {t('menu.register')}
                </AppButton>
            </div>
            {
                <div className="text-center mb-[1rem]">
                    {t('text.haveAnAccount')} <Link href={`${servicePath ? '/'+servicePath : ''}/login`}>{t('menu.login')}</Link>
                </div>
            }
        </div>
    </FormWrapper>
  );
};
