/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import {FC, useState, useEffect} from 'react';
import text from './text';
import {useAppDispatch, useAppSelector} from 'store/index';
import {authenticateCredentialsThunk, selectIsLoading, selectError, setError, selectIsAuthenticated, setCredentials} from 'store/slices/Authentication.slice';
import {
  LoginFormBackground,
  LogoContainer,
  LoginContainer,
  LoginForm as StyledForm,
  LoginButton,
  LoginHeader,
  LoginText,
  ErrorText,
  InputContainer,
  InputField,
  InputIcon,
  Footer
} from './style';
import personImage from 'assets/images/symbol-person-24x24.png';
import lockImage from 'assets/images/symbol-lock-24x24.png';
import phenixLogo from 'assets/images/phenix-logo-101x41.png';
import {LoadingWheel} from 'components';
import {documentationLinks, phenixWebSiteLinks} from 'constants/links';
import {useNavigate} from 'react-router-dom';

export const LoginForm: FC = () => {
  const {headerText, headerTextSmall, signInText} = text;
  const [applicationId, setApplicationId] = useState('phenixrts.com-alex.zinn');
  const [secret, setSecret] = useState('AMAsDzr.dIuGMZ.Zu52Dt~MQvP!DZwYg');
  const dispatch = useAppDispatch();
  const error = useAppSelector(selectError);
  const isLoading = useAppSelector(selectIsLoading);
  const navigate = useNavigate();
  const isAuthenticated = useAppSelector(selectIsAuthenticated);

  useEffect(() => {
    if (isAuthenticated) {
      navigate('/channels', {replace: true});
    }
  }, [isAuthenticated, navigate]);

  useEffect(() => {
    if (error) {
      const timeoutId = setTimeout(() => {
        dispatch(setError(null));
      }, 3000);

      return () => clearTimeout(timeoutId);
    }
  }, [dispatch, error]);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    dispatch(setCredentials({applicationId, secret}));
    dispatch(authenticateCredentialsThunk({applicationId, secret}));
  };

  const handleInputChange = (setter: (value: string) => void) => (e: React.ChangeEvent<HTMLInputElement>) => {
    // Clear error when user starts typing
    if (error) {
      dispatch(setError(null));
    }
    setter(e.target.value);
  };

  return (
    <LoginFormBackground>
      <LogoContainer>
        <img src={phenixLogo} alt="Phenix RTS" />
      </LogoContainer>
      <LoginContainer>
        <LoginHeader>{headerText}</LoginHeader>
        <LoginText>{headerTextSmall}</LoginText>

        <StyledForm onSubmit={handleSubmit}>
          <InputContainer>
            <InputIcon src={personImage} alt="User" />
            <InputField
              type="text"
              value={applicationId}
              placeholder="Application ID"
              onChange={handleInputChange(setApplicationId)}
              disabled={isLoading}
              required
            />
          </InputContainer>

          <InputContainer>
            <InputIcon src={lockImage} alt="Lock" />
            <InputField type="password" value={secret} placeholder="Secret" onChange={handleInputChange(setSecret)} disabled={isLoading} required />
          </InputContainer>

          {error && <ErrorText className="error-message testId-displayMessage">{error}</ErrorText>}

          <LoginButton type="submit" disabled={isLoading} className="testId-loginButton">
            {isLoading ? <LoadingWheel size={'small'} /> : signInText}
          </LoginButton>
        </StyledForm>

        <Footer>
          © 2025 Phenix RTS
          <br />
          <a href={phenixWebSiteLinks.privacyPolicyProduction} target="_blank">
            Privacy Policy
          </a>{' '}
          •{' '}
          <a href={phenixWebSiteLinks.termsOfServiceProduction} target="_blank">
            Terms of Service
          </a>{' '}
          •{' '}
          <a href={documentationLinks.portal} target="_blank">
            Documentation
          </a>
        </Footer>
      </LoginContainer>
    </LoginFormBackground>
  );
};
