import React, { FC, useState } from 'react';
import { Form, FormInstance, notification } from 'antd';
import { AUTH_USER } from '../../../constants/common';
import { getRegister } from '../../../actions/auth';
import { setPersonData } from '../../../actions/profile';
import { CustomInput } from '../../view/CustomInput';
import { CustomInputPassword } from '../../view/CustomInputPassword';
import { FilledButton } from '../../view/FilledButton';
import { OutlinedButton } from '../../view/OutlinedButton';

type RegisterProps = {
    form: FormInstance;
    locale: string;
    updateMode: (mode: 'enter' | 'register' | 'reset' | 'finish') => void;
    updateToken: (token: string) => void;
    handleCancel: () => void;
};

export const RegisterContent: FC<RegisterProps> = ({
    form,
    updateMode,
    locale,
    updateToken,
    handleCancel
}) => {
    const [isLoading, setIsLoading] = useState<boolean>(false);

    const onRegister = () => {
        form.validateFields().then(() => {
            const { login, password } = form.getFieldsValue();
            setIsLoading(true);
            getRegister(locale)
                .then(({ data }) => {
                    if (data.jwtToken) {
                        setPersonData( { login, password, role: 'client', languagesLinks: [] }, locale, data.jwtToken)
                            .then(({ data: profile }) => {
                                updateToken(data.jwtToken);
                                localStorage.setItem(AUTH_USER, profile.userData.id.toString());
                                handleCancel();
                            })
                            .catch((error) => {
                                notification.error({
                                    message: 'Error',
                                    description: error?.response?.data?.errors?.toString()
                                });
                            });
                    }
                })
                .catch((error) => {
                    notification.error({
                        message: 'Error',
                        description: error?.response?.data?.errMessage
                    });
                })
                .finally(() => {
                    setIsLoading(false);
                })
        });
    };

    return (
        <>
            <Form form={form} autoComplete="off" style={{ display: 'flex', gap: 16, flexDirection: 'column' }}>
                <Form.Item
                    name="login"
                    noStyle
                    rules={[
                        {
                            type: 'email',
                            message: 'The input is not valid E-mail'
                        },
                        {
                            required: true,
                            message: 'Please input your E-mail'
                        }
                    ]}
                >
                    <CustomInput
                        size="small"
                        placeholder="E-mail"
                        type="email"
                    />
                </Form.Item>
                <Form.Item
                    name="password"
                    noStyle
                    rules={[{
                        required: true,
                        message: 'Please input your password'
                    }]}
                >
                    <CustomInputPassword
                        size="small"
                        placeholder="Password"
                    />
                </Form.Item>
                <Form.Item
                    name="confirmPassword"
                    noStyle
                    dependencies={['password']}
                    hasFeedback
                    rules={[
                        {
                            required: true,
                            message: 'Please confirm your password',
                        },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                                if (!value || getFieldValue('password') === value) {
                                    return Promise.resolve();
                                }
                                return Promise.reject(new Error('The new password that you entered do not match'));
                            },
                        }),
                    ]}
                >
                    <CustomInputPassword
                        size="small"
                        placeholder="Confirm password"
                    />
                </Form.Item>
            </Form>
            <FilledButton
                type="primary"
                onClick={onRegister}
                loading={isLoading}
            >
                Register
            </FilledButton>
            <OutlinedButton onClick={() => updateMode('enter')}>Enter</OutlinedButton>
        </>
    );
};
