import { HTTPSTATUS } from '@/constants';
import { apiChangePassword } from '@/services/master/AuthController';
import {
  ProForm,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import { useRef } from 'react';

type ChangePasswordForm = {
  old_password: string;
  new_password: string;
  confirm_password: string;
};
const ChangePassword = () => {
  const formRef = useRef<ProFormInstance<ChangePasswordForm>>();
  const intl = useIntl();
  const [messageApi, contextHolder] = message.useMessage();
  return (
    <>
      {contextHolder}
      <ProForm<ChangePasswordForm>
        formRef={formRef}
        title={intl.formatMessage({
          id: 'master.profile.change-password',
        })}
        autoFocusFirstInput
        onFinish={async (values) => {
          if (values.new_password !== values.confirm_password) {
            messageApi.error(
              intl.formatMessage({
                id: 'master.profile.change-password.password_not_match',
              }),
            );
            return false;
          } else {
            console.log('Values: ', values);
            const changePasswordBody: MasterModel.ChangePasswordRequestBody = {
              old_password: values.old_password,
              password: values.new_password,
            };
            try {
              const resp = await apiChangePassword(changePasswordBody);
              if (resp.status === HTTPSTATUS.HTTP_CREATED) {
                messageApi.success(
                  intl.formatMessage({
                    id: 'master.profile.change-password.success',
                  }),
                );
                formRef.current?.resetFields();
              } else {
                throw new Error('Change password failed');
              }
            } catch (error) {
              messageApi.error(
                intl.formatMessage({
                  id: 'master.profile.change-password.fail',
                }),
              );
            }
          }
        }}
        submitter={{
          resetButtonProps: false,
          render: () => {
            return [
              <Button
                key="submit"
                type="primary"
                onClick={() => {
                  formRef.current?.submit();
                }}
              >
                <FormattedMessage
                  id="common.confirm"
                  defaultMessage="Cập nhật"
                />
              </Button>,
            ];
          },
        }}
      >
        <ProFormText.Password
          name="old_password"
          label={intl.formatMessage({
            id: 'master.profile.change-password.old_password',
          })}
          fieldProps={{ autoComplete: 'current-password' }}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'common.required_field' }),
            },
          ]}
        />
        <ProFormText.Password
          name="new_password"
          label={intl.formatMessage({
            id: 'master.profile.change-password.new_password',
          })}
          fieldProps={{ autoComplete: 'new-password' }}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'common.required_field' }),
            },
            {
              pattern:
                /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*.]{6,16}$/g,
              message: intl.formatMessage({
                id: 'master.profile.change-password.password.strong',
                defaultMessage:
                  'A password contains at least 8 characters, including at least one number and includes both lower and uppercase letters and special characters, for example #, ?, !',
              }),
            },
            ({ getFieldValue }) => ({
              validator(rule, value) {
                const old_password = getFieldValue('old_password');
                if (old_password === value) {
                  return Promise.reject(
                    intl.formatMessage({
                      id: 'account.message.newpass.conflict',
                      defaultMessage: 'New password cannot be the same as old',
                    }),
                  );
                }
                return Promise.resolve();
              },
            }),
          ]}
        />
        <ProFormText.Password
          name="confirm_password"
          label={intl.formatMessage({
            id: 'master.profile.change-password.confirm_password',
          })}
          fieldProps={{ autoComplete: 'new-password-confirm' }}
          rules={[
            ({ getFieldValue }) => ({
              validator(rule, value) {
                const new_password = getFieldValue('new_password');
                if (new_password === value) {
                  return Promise.resolve();
                }
                return Promise.reject(
                  intl.formatMessage({
                    id: 'master.profile.change-password.password_not_match',
                    defaultMessage: 'Confirmation password does not match',
                  }),
                );
              },
            }),
          ]}
        />
      </ProForm>
    </>
  );
};

export default ChangePassword;
