'use client';
// ChangePasswordModal.tsx
import React, { useState } from 'react';
import { Button, Form, Input, notification } from 'antd';
import { EyeOutlined, LockOutlined, EyeInvisibleOutlined } from '@ant-design/icons';

import { changeNewPasswordValidator } from '@/utills/validator';
import { changePasswordByUser } from '@/app/auth/service';
interface FirstChangePasswordProps {
    user: { id: number; token: string }
    callAfterSuccess: Function
}

const FirstChangePassword: React.FC<FirstChangePasswordProps> = ({ user, callAfterSuccess }) => {
  const [form] = Form.useForm();
  const [passwordVisible, setPasswordVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState<boolean>(false);
  const userId = user.id;
  const token = user.token;

  const onFinish = (): void => {
    form.validateFields()
      .then(() => {
        const newPassword = form.getFieldValue('newPassword');
        const confirmPassword = form.getFieldValue('confirmPassword');

        if (newPassword && confirmPassword && newPassword === confirmPassword) {
          handleOk();
        } else {
          console.log('Passwords do not match or are empty');
        }
      })
      .catch((errorInfo) => {
        console.error('Failed:', errorInfo);
      });
  };

  // Function to handle password change
  const handleOk = (): void => {
    const newPassword = form.getFieldValue('newPassword');
    setLoading(true);
    if (userId !== undefined && userId !== null) {
      changePasswordByUser(userId, { password: newPassword }, token)
        .then(() => {
          notification.success({
            message: 'Success',
            description:
                            'Your new password has been set successfully. Please log in using your new password.',
          });
          setLoading(false);
          callAfterSuccess(null);
        })
        .catch((error) => {
          notification.error({
            message: 'Error',
            description: error?.response?.data.message,
          });
          setLoading(false);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  };

  return (
    <Form form={form} onFinish={onFinish} layout="vertical">
      <Form.Item name="newPassword" rules={[{ validator: changeNewPasswordValidator }]}>
        <Input.Password
          placeholder="New Password"
          type={passwordVisible ? 'text' : 'password'}
          size="large"
          prefix={<LockOutlined className="site-form-item-icon" />}
          suffix={
            <span
              style={{ cursor: 'pointer' }}
              onClick={() => {
                setPasswordVisible(!passwordVisible);
              }}>
              {passwordVisible ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            </span>
          }
        />
      </Form.Item>

      <Form.Item
        name="confirmPassword"
        dependencies={['newPassword']}
        rules={[
          { required: true, message: 'Please Enter Confirm Password' },
          ({ getFieldValue }) => ({
            async validator(_, value) {
              if (value === undefined || getFieldValue('newPassword') === value) {
                await Promise.resolve();
                return;
              }
              return await Promise.reject(
                new Error('New And Confirm Password Are Not Match')
              );
            },
          }),
        ]}>
        <Input.Password
          placeholder="Confirm Password"
          size="large"
          prefix={<LockOutlined className="site-form-item-icon" />}
          type={confirmPasswordVisible ? 'text' : 'password'}
          suffix={
            <span
              style={{ cursor: 'pointer' }}
              onClick={() => {
                setConfirmPasswordVisible(!confirmPasswordVisible);
              }}>
              {confirmPasswordVisible ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            </span>
          }
        />
      </Form.Item>
      <div className="d-flex justify-content-end">
        <Button
          type="primary"
          htmlType="submit"
          className="btn btn-primary login-form-button"
          size="large"
          loading={loading}>
                    Update Password
        </Button>
      </div>
    </Form>
  );
};

export default FirstChangePassword;
