import React, { useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useUser } from "../components/UserContext";
import { User } from "../types/types";
import { Box } from "@mui/material";
import { connectionBase } from "../Global";
import { SetSnackType } from '../components/Snack';
import { LoadingComponent } from "../components/LoadingComponent";

interface UserRouteProps {
  sessionId?: string | null;
  setSnack: SetSnackType,
};

const UserRoute: React.FC<UserRouteProps> = (props: UserRouteProps) => {
  const { sessionId, setSnack } = props;
  const { username } = useParams<{ username: string }>();
  const { user, setUser } = useUser();
  const navigate = useNavigate();

  useEffect(() => {
    if (!sessionId) {
      return;
    }

    const fetchUser = async (username: string): Promise<User | null> => {
      try {
        let response;
        response = await fetch(`${connectionBase}/api/u/${username}/${sessionId}`, {
          method: 'POST',
          credentials: 'include',
        });
        if (!response.ok) {
          throw new Error('Session not found');
        }
        const user: User = await response.json();
        console.log("Loaded user:", user);
        setUser(user);
        navigate('/chat');
      } catch (err) {
        setSnack("" + err);
        setUser(null);
        navigate('/');
      }
      return null;
    };

    if (user?.username !== username && username) {
      fetchUser(username);
    } else {
      if (user?.username) {
        navigate('/chat');
      } else {
        navigate('/');
      }
    }
  }, [user, username, setUser, sessionId, setSnack, navigate]);

  if (sessionId === undefined || !user) {
    return (<Box>
      <LoadingComponent
        loadingText="Fetching user information..."
        loaderType="linear"
        withFade={true}
        fadeDuration={1200} />
    </Box>);
  } else {
    return (<></>);
  }
};

export { UserRoute };
