import { useEffect } from 'react';

import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';

import { resetPassword } from '@/redux/auth/actions';
import { selectAuth } from '@/redux/auth/selectors';

import { Alert, Form, Button, Space, Typography } from 'antd';

import ResetPasswordForm from '@/forms/ResetPasswordForm';

import useLanguage from '@/locale/useLanguage';

import Loading from '@/components/Loading';
import AuthModule from '@/modules/AuthModule';

const ResetPassword = () => {
  const translate = useLanguage();
  const { isLoading, isSuccess } = useSelector(selectAuth);
  const navigate = useNavigate();
  const { userId, resetToken } = useParams();

  const dispatch = useDispatch();
  const onFinish = (values) => {
    dispatch(
      resetPassword({
        resetPasswordData: {
          password: values.password,
          userId,
          resetToken,
        },
      })
    );
  };

  useEffect(() => {
    if (isSuccess) navigate('/');
  }, [isSuccess]);

  const FormContainer = () => {
    return (
      <Loading isLoading={isLoading}>
        <Space direction="vertical" size={16} style={{ width: '100%' }}>
          <Alert
            type="info"
            showIcon
            message="Set your password to activate this workspace session"
            description="Use this page for first-time account setup or after an administrator refreshes your access."
          />
          <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
            Once your password is saved, you will be signed in immediately and taken into the application.
          </Typography.Paragraph>
          <Form
            name="signup"
            className="login-form"
            initialValues={{
              remember: true,
            }}
            onFinish={onFinish}
          >
            <ResetPasswordForm />
            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button" size="large">
                {translate('update password')}
              </Button>
              {translate('Or')} <a href="/login"> {translate('already have account Login')} </a>
            </Form.Item>
          </Form>
        </Space>
      </Loading>
    );
  };
  return <AuthModule authContent={<FormContainer />} AUTH_TITLE="Reset Password" />;
};

export default ResetPassword;
