import React, { useEffect, useState } from 'react';
import { LoginComponentProps } from './types';
import { getTranslations } from '../../shared/utils/localization-util';
import { confirmMember } from './login-services';

interface TouchedFields {
  password?: boolean;
  repeatPassword?: boolean;
}

interface FormFields {
  password: string;
  repeatPassword: string;
}

const ConfirmComponent: React.FC<LoginComponentProps> = ({ tideClientConfig, languageCode, handleBackToLogin }) => {
  const [isConfirmed, setIsConfirmed] = useState<boolean>(false);
  const [touched, setTouched] = useState<TouchedFields>();
  const [formValues, setFormValues] = useState<FormFields>({
    password: '',
    repeatPassword: ''
  });
  const [errors, setErrors] = useState({} as any);
  const [token, setToken] = useState<string | null>(null);

  const translations = getTranslations(languageCode ?? 'en-GB');

  useEffect(() => {
    if (typeof window !== 'undefined') {
      setToken(new URLSearchParams(window.location.search).get('token'));
    }
  }, []);

  const handleBlur = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (!touched) {
      setTouched({ password: false, repeatPassword: false });
    }
    setTouched({
      ...touched,
      [event.target.name]: true
    });

    validate();
  };

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFormValues({ ...formValues, [event.target.name]: event.target.value });

    validate();
  };

  const validate = () => {
    let validationErrors = {} as any;
    if (formValues) {
      if (!formValues.password || formValues.password.length === 0) {
        validationErrors.password = true;
      }
      if (!formValues.repeatPassword || formValues.repeatPassword.length === 0) {
        validationErrors.repeatPassword = true;
      } else if (formValues.password !== formValues.repeatPassword) {
        validationErrors.passwordMatch = true;
      }
      if (!token || token.length === 0) {
        validationErrors.token = true;
      }
    }

    setErrors(validationErrors);
    return Object.keys(validationErrors).length === 0;
  };

  const handleConfirmation = async () => {
    setTouched({ password: true, repeatPassword: true });
    const isValid = validate();
    if (!isValid) return;

    if (token) {
      try {
        const response = await confirmMember(token, formValues.password, true, tideClientConfig);
        if (response.ok) {
          setIsConfirmed(true);
        }
      } catch {
        // Optional: handle unexpected API issues
      }
    }
  };

  useEffect(() => {
    validate();
  }, [formValues, token]);

  return (
    <>
      {!isConfirmed && (
        <>
          <h4 className="login__card__title">{translations.LOGIN.RESET_PASSWORD_TITLE}</h4>

          <form className="login__form" onSubmit={(e) => e.preventDefault()} noValidate>
            <div className="login__form__group">
              <label htmlFor="password">{translations.LOGIN.RESET_PASSWORD_LABEL}</label>
              <input type="password" id="password" name="password" value={formValues.password} onChange={onChange} onBlur={handleBlur} required />
              {(touched?.password || touched?.repeatPassword) && errors.password && (
                <div id="username-error" className="login__error">
                  {translations.LOGIN.PASSWORD_REQUIRED}
                </div>
              )}
            </div>

            <div className="login__form__group">
              <label htmlFor="repeatPassword">{translations.LOGIN.RESET_REPEAT_PASSWORD_LABEL}</label>
              <input
                type="password"
                id="repeatPassword"
                name="repeatPassword"
                value={formValues.repeatPassword}
                onChange={onChange}
                onBlur={handleBlur}
                required
              />
              {(touched?.repeatPassword || touched?.password) && (errors.repeatPassword || errors.passwordMatch) && (
                <div id="username-error" className="login__error">
                  {errors.repeatPassword === 'required' && translations.LOGIN.REPEAT_PASSWORD_REQUIRED}
                  {errors.passwordMatch === 'mismatch' && translations.LOGIN.PASSWORDS_DO_NOT_MATCH}
                </div>
              )}
            </div>

            <button type="button" className="cta cta--primary" onClick={handleConfirmation}>
              {translations.LOGIN.RESET_PASSWORD_SUBMIT_LABEL}
            </button>
          </form>
        </>
      )}

      {isConfirmed && (
        <div className="login__welcome">
          <h3 className="login__card__title">{translations.LOGIN.RECEIVED_REQUEST}</h3>
          <p>{translations.LOGIN.ACCOUNT_ACTIVATED_LOGIN}</p>
          <button className="cta cta--primary" onClick={handleBackToLogin}>
            {translations.LOGIN.BACK_TO_LOGIN}
          </button>
        </div>
      )}
    </>
  );
};

export default ConfirmComponent;
