import Footer from '@/components/Footer';
import LangSwitches from '@/components/Lang/LanguageSwitcherAuth';
import ThemeSwitcherAuth from '@/components/Theme/ThemeSwitcherAuth';
import { THEME_KEY } from '@/constants';
import { ROUTE_LOGIN } from '@/constants/routes';
import { apiUserResetPassword } from '@/services/master/UserController';
import { parseAccessToken } from '@/utils/jwt';
import { getDomainTitle, getLogoImage } from '@/utils/logo';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import {
  FormattedMessage,
  history,
  useIntl,
  useSearchParams,
} from '@umijs/max';
import { Button, ConfigProvider, Image, message, Result, theme } from 'antd';
import { useEffect, useState } from 'react';
import backgroundImg from '../../../../public/background.png';
import mobifontLogo from '../../../../public/mobifont-logo.png';
type ResetPasswordFormValues = {
  password: string;
  confirmPassword: string;
};

const ResetPassword = () => {
  const [searchParams] = useSearchParams();
  const resetPasswordToken = searchParams.get('token');
  const [tokenValid, setTokenValid] = useState(false);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [isDark, setIsDark] = useState(
    (localStorage.getItem(THEME_KEY) as 'light' | 'dark') === 'dark',
  );
  const { token } = theme.useToken();
  const [messageApi, contextHolder] = message.useMessage();
  const intl = useIntl();

  // Listen for theme changes from ThemeSwitcherAuth
  useEffect(() => {
    const handleThemeChange = (e: Event) => {
      const customEvent = e as CustomEvent<{ theme: 'light' | 'dark' }>;
      setIsDark(customEvent.detail.theme === 'dark');
    };

    window.addEventListener('theme-change', handleThemeChange as EventListener);
    return () => {
      window.removeEventListener(
        'theme-change',
        handleThemeChange as EventListener,
      );
    };
  }, []);

  useEffect(() => {
    const tokenParsed = resetPasswordToken
      ? parseAccessToken(resetPasswordToken)
      : null;
    setTokenValid(
      tokenParsed?.expriresAt
        ? tokenParsed.expriresAt * 1000 > Date.now()
        : true,
    );
  }, [resetPasswordToken]);

  const handleSubmit = async (values: ResetPasswordFormValues) => {
    setLoading(true);
    try {
      const resp = await apiUserResetPassword({
        token: resetPasswordToken!,
        password: values.password,
        confirm_password: values.confirmPassword,
      });

      messageApi.success(
        intl.formatMessage({
          id: 'master.auth.reset.success',
          defaultMessage: 'Đặt lại mật khẩu thành công!',
        }),
      );
      setSuccess(true);
      setTimeout(() => {
        history.push(ROUTE_LOGIN);
      }, 2000);
    } catch (error) {
      console.error('Reset password error:', error);
      messageApi.error(
        intl.formatMessage({
          id: 'master.auth.reset.error',
          defaultMessage: 'Có lỗi xảy ra, vui lòng thử lại!',
        }),
      );
    } finally {
      setLoading(false);
    }
  };

  // Token invalid state
  if (!tokenValid) {
    return (
      <ConfigProvider
        theme={{
          algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,
        }}
      >
        <div
          style={{
            backgroundColor: isDark ? '#000' : token.colorBgContainer,
            height: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <div
            style={{
              backgroundColor: token.colorBgSolidActive,
              backdropFilter: 'blur(4px)',
              padding: '48px',
              borderRadius: '8px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
              maxWidth: '500px',
              width: '100%',
            }}
          >
            <Result
              icon={<Image src={getLogoImage()} preview={false} width={80} />}
              title={
                <span style={{ color: token.colorBgContainer }}>
                  {intl.formatMessage({
                    id: getDomainTitle(),
                    defaultMessage: 'Smatec',
                  })}
                </span>
              }
              subTitle={
                <span style={{ color: token.colorBgContainer }}>
                  {intl.formatMessage({
                    id: 'master.auth.reset.invalid',
                    defaultMessage:
                      'Liên kết đặt lại mật khẩu không hợp lệ hoặc đã hết hạn.',
                  })}
                </span>
              }
              extra={
                <Button
                  type="primary"
                  onClick={() => history.push(ROUTE_LOGIN)}
                >
                  {intl.formatMessage({
                    id: 'master.auth.backToLogin.title',
                    defaultMessage: 'Quay về trang Đăng nhập',
                  })}
                </Button>
              }
            />
          </div>
          <div className="absolute top-5 right-5 z-50 flex gap-4">
            <ThemeSwitcherAuth />
            <LangSwitches />
          </div>
        </div>
      </ConfigProvider>
    );
  }

  // Success state
  if (success) {
    return (
      <ConfigProvider
        theme={{
          algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,
        }}
      >
        <div
          style={{
            backgroundImage: `url(${backgroundImg})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            height: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <div
            style={{
              backgroundColor: token.colorBgLayout,
              padding: '48px',
              borderRadius: '8px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
              maxWidth: '500px',
              width: '100%',
            }}
          >
            <Result
              status="success"
              title={
                <span style={{ color: token.colorText }}>
                  {intl.formatMessage({
                    id: 'master.auth.reset.successTitle',
                    defaultMessage: 'Mật khẩu đã được đặt lại!',
                  })}
                </span>
              }
              subTitle={
                <span style={{ color: token.colorTextDescription }}>
                  {intl.formatMessage({
                    id: 'master.auth.reset.successMessage',
                    defaultMessage: 'Đang chuyển hướng đến trang đăng nhập...',
                  })}
                </span>
              }
            />
          </div>
          <div className="absolute top-5 right-5 z-50 flex gap-4">
            <ThemeSwitcherAuth />
            <LangSwitches />
          </div>
        </div>
      </ConfigProvider>
    );
  }

  // Reset password form
  return (
    <ConfigProvider
      theme={{
        algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,
      }}
    >
      <div
        style={{
          backgroundColor: 'transparent',
          height: '100vh',
          backgroundImage: `url(${backgroundImg})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
      >
        {contextHolder}
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100%',
            position: 'relative',
          }}
        >
          <div
            style={{
              backgroundColor: 'rgba(0, 0, 0, 0.65)',
              backdropFilter: 'blur(4px)',
              padding: '40px',
              borderRadius: '8px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
              width: '100%',
              maxWidth: '400px',
            }}
          >
            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
              <Image
                src={getLogoImage()}
                preview={false}
                width={60}
                style={{ marginBottom: '16px' }}
              />
              <h2
                style={{
                  color: token.colorBgContainer,
                  fontSize: '24px',
                  fontWeight: 'bold',
                  marginBottom: '8px',
                }}
              >
                {intl.formatMessage({
                  id: getDomainTitle(),
                  defaultMessage: 'Smatec',
                })}
              </h2>
              <Image preview={false} src={mobifontLogo} />
            </div>

            <ProForm
              submitter={{
                searchConfig: {
                  submitText: intl.formatMessage({
                    id: 'master.auth.reset.submit',
                    defaultMessage: 'Đặt lại mật khẩu',
                  }),
                },
                submitButtonProps: {
                  loading,
                  size: 'large',
                  block: true,
                },
                resetButtonProps: {
                  style: { display: 'none' },
                },
              }}
              onFinish={handleSubmit}
            >
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  placeholder: intl.formatMessage({
                    id: 'master.auth.reset.newPassword.placeholder',
                    defaultMessage: 'Nhập mật khẩu mới',
                  }),
                  autoComplete: 'password',
                }}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="master.users.password.required"
                        defaultMessage="Password is required"
                      />
                    ),
                  },
                  {
                    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 #, ?, !',
                    }),
                  },
                  {
                    validator: async (rule, value) => {
                      if (value && value.length < 8) {
                        return Promise.reject(
                          intl.formatMessage({
                            id: 'master.users.password.minimum',
                            defaultMessage: 'Minimum password length is 8',
                          }),
                        );
                      }
                      return Promise.resolve();
                    },
                  },
                ]}
              />
              <ProFormText.Password
                name="confirmPassword"
                fieldProps={{
                  size: 'large',
                  placeholder: intl.formatMessage({
                    id: 'master.users.confirmPassword',
                    defaultMessage: 'Xác nhận mật khẩu',
                  }),
                  autoComplete: 'confirmPassword',
                }}
                dependencies={['password']}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'master.users.confirmPassword.required',
                      defaultMessage: 'Vui lòng xác nhận mật khẩu!',
                    }),
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error(
                          intl.formatMessage({
                            id: 'master.users.confirmPassword.mismatch',
                            defaultMessage: 'Mật khẩu xác nhận không khớp!',
                          }),
                        ),
                      );
                    },
                  }),
                ]}
              />
            </ProForm>

            <div style={{ textAlign: 'center', marginTop: '16px' }}>
              <Button
                type="link"
                // style={{ color: token.colorBgContainer }}
                onClick={() => history.push(ROUTE_LOGIN)}
              >
                {intl.formatMessage({
                  id: 'master.auth.backToLogin.title',
                  defaultMessage: 'Quay về trang Đăng nhập',
                })}
              </Button>
            </div>
          </div>
        </div>

        <div className="absolute top-5 right-5 z-50 flex gap-4">
          <ThemeSwitcherAuth />
          <LangSwitches />
        </div>

        <div
          style={{
            backgroundColor: 'transparent',
            position: 'absolute',
            bottom: 0,
            zIndex: 99,
            width: '100%',
          }}
        >
          <Footer />
        </div>
      </div>
    </ConfigProvider>
  );
};

export default ResetPassword;
