import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Box } from "@mui/material";

import { SetSnackType } from '../components/Snack';
import { LoadingComponent } from "../components/LoadingComponent";
import { User, Guest, Candidate } from 'types/types';
import { useAuth } from "hooks/AuthContext";

interface CandidateRouteProps {
  guest?: Guest | null;
  user?: User | null;
  setSnack: SetSnackType,
};

const CandidateRoute: React.FC<CandidateRouteProps> = (props: CandidateRouteProps) => {
  const { apiClient } = useAuth();
  const { setSnack } = props;
  const { username } = useParams<{ username: string }>();
  const [candidate, setCandidate] = useState<Candidate|null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    if (candidate?.username === username || !username) {
      return;
    }
    const getCandidate = async (reference: string) => {
      try {
        const result: Candidate = await apiClient.getCandidate(reference);
        setCandidate(result);
        navigate('/chat');
      } catch {
        setSnack(`Unable to obtain information for ${username}.`, "error");
        navigate('/');
      }
    }

    getCandidate(username);
  }, [candidate, username, setCandidate, navigate, setSnack, apiClient]);

  if (candidate === null) {
    return (<Box>
      <LoadingComponent
        loadingText="Fetching candidate information..."
        loaderType="linear"
        withFade={true}
        fadeDuration={1200} />
    </Box>);
  } else {
    return (<></>);
  }
};

export { CandidateRoute };
