'use client';

// pages/reset-password.tsx
import Image from 'next/image';
import React, { useState } from 'react';
import { Form, Input, Button, Typography, notification, Spin } from 'antd';
import { LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { useParams, useRouter } from 'next/navigation';
import { resetPwPost } from '../service';

const { Title } = Typography;

const ResetPasswordPage: React.FC = () => {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState<boolean>(false);
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const searchParams = useParams();

  const onFinish = (values: { password: string; }): void => {
    setLoading(true);
    resetPwPost({
      password: values.password,
      token: searchParams.token[0],
    })
      .then((res) => {
        notification.success({
          message: 'Success',
          description: res?.data?.message,
        });
        router.push('/auth/login');
        setLoading(false);
      })
      .catch((err) => {
        const { message } = err?.response?.data || {};
        notification.error({
          message: 'Error',
          description: message,
        });
        setLoading(false);
        console.error('Error resetting password:', err);
      });
  };

  const togglePasswordVisibility = (): void => {
    setShowPassword(!showPassword);
  };

  return (
    <>
      {loading ? (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
          }}>
          <Spin size="large" />
        </div>
      ) : (
        <div className="auth-page">
          <div className="login-box">
            <div className="login-box-header">
              <div className="logo">
                <Image src="/images/logo.png" alt="logo" height={50} width={190} />
              </div>
            </div>
            <div className="login-box-content">
              <Title level={2} className="text-center">
                                Reset Password
              </Title>
              <Form name="resetPassword" onFinish={onFinish}>
                <Form.Item
                  name="password"
                  rules={[
                    () => ({
                      async validator(_, value) {
                        if (!value) {
                          return await Promise.reject(
                            new Error('Please Enter New Password')
                          );
                        }
                        if (value.length > 128) {
                          return await Promise.reject(
                            new Error(
                              'Password Must be at Most 128 Characters Long'
                            )
                          );
                        }
                        if (value.length < 8) {
                          return await Promise.reject(
                            new Error(
                              'Password Must be at Least 8 Characters Long'
                            )
                          );
                        }
                        if (
                          !/^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#*^()_+=])[A-Za-z\d@$!%*?&#*^()_+=]+$/.test(
                            value
                          )
                        ) {
                          return await Promise.reject(
                            new Error(
                              'Must Enter at Least 1 Uppercase Letter, 1 Number, and 1 Special Character'
                            )
                          );
                        }
                        await Promise.resolve();
                      },
                    }),
                  ]}>
                  <Input.Password
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    type={showPassword ? 'text' : 'password'}
                    placeholder="New Password"
                    size="large"
                    suffix={
                      <span
                        style={{ cursor: 'pointer' }}
                        onClick={togglePasswordVisibility}>
                        {showPassword ? (
                          <EyeTwoTone />
                        ) : (
                          <EyeInvisibleOutlined />
                        )}
                      </span>
                    }
                  />
                </Form.Item>
                <Form.Item
                  name="confirmPassword"
                  dependencies={['password']}
                  rules={[
                    {
                      required: true,
                      message: 'Please Enter Confirm Password',
                    },
                    ({ getFieldValue }) => ({
                      async validator(_, value) {
                        if (
                          value === undefined ||
                                                    getFieldValue('password') === value
                        ) {
                          await Promise.resolve();
                          return;
                        }
                        return await Promise.reject(
                          new Error(
                            'New And Confirm Password Are Not Match'
                          )
                        );
                      },
                    }),
                  ]}>
                  <Input.Password
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    type={confirmPasswordVisible ? 'text' : 'password'}
                    suffix={
                      <span
                        style={{ cursor: 'pointer' }}
                        onClick={() => {
                          setConfirmPasswordVisible(
                            !confirmPasswordVisible
                          );
                        }}>
                        {confirmPasswordVisible ? (
                          <EyeTwoTone />
                        ) : (
                          <EyeInvisibleOutlined />
                        )}
                      </span>
                    }
                    placeholder="Confirm Password"
                    size="large"
                  />
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    size="large"
                    className="login-form-button">
                                        Reset Password
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default ResetPasswordPage;
