import {JSX, useState, useEffect} from 'react';
import {useAppSelector, useAppDispatch} from '../../hooks';
import {useNavigate} from 'react-router-dom';
import Routes from '../../routers/static-routes';
import {authenticateCredentialsThunk, selectIsAuthenticated, selectIsAuthenticating, selectStatus} from '../../store/slices/Authentication.slice';
import {InputField} from '../InputField';

export function LoginForm(): JSX.Element | null {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [applicationId, setApplicationId] = useState<string>('phenixrts.com-alex.zinn');
  const [secret, setSecret] = useState<string>('AMAsDzr.dIuGMZ.Zu52Dt~MQvP!DZwYg');

  const isAuthenticating = useAppSelector(selectIsAuthenticating);
  const connectionStatus = useAppSelector(selectStatus);
  const isAuthenticated = useAppSelector(selectIsAuthenticated);

  const isConnectionReady = connectionStatus === 'Online';
  const isDisabled = isAuthenticating || !isConnectionReady;

  // Redirect to dashboard if already authenticated
  useEffect(() => {
    if (isAuthenticated) {
      const dashboardUrl = Routes.dashboardUrl() + window.location.search;
      navigate(dashboardUrl, {replace: true});
    }
  }, [isAuthenticated, navigate]);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!isConnectionReady) {
      alert('Please wait for WebSocket connection to be established before attempting to authenticate.');
      return;
    }

    dispatch(authenticateCredentialsThunk({applicationId, secret}));
    setApplicationId('');
    setSecret('');
  };

  // Don't render login form if already authenticated
  if (isAuthenticated) {
    return null;
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <InputField
          type="text"
          placeholder="Application Id"
          value={applicationId}
          onValueChange={value => setApplicationId(value)}
          disabled={isDisabled}
          isRequired={true}
        />
        <InputField type="password" placeholder="secret" value={secret} onValueChange={value => setSecret(value)} disabled={isDisabled} isRequired={true} />
        <button type="submit" disabled={isDisabled}>
          {isConnectionReady ? 'Login' : 'Connecting...'}
        </button>
        {!isConnectionReady && <div style={{color: 'orange', fontSize: '12px', marginTop: '5px'}}>Waiting for WebSocket connection...</div>}
      </form>
    </>
  );
}
