import React, { useState, useEffect, useCallback } from "react";
import { Paper, Typography } from "@mui/material";

import { Session } from "./GlobalContext";
import "./App.css";
import { base } from "./Common";
import { Box } from "@mui/material";
import { BrowserRouter as Router, Route, Routes, useNavigate } from "react-router-dom";
import { ReadyState } from "react-use-websocket";
import { ConnectionStatus } from "./ConnectionStatus";
import { RoomView } from "./RoomView";
import { sessionApi } from "./api-client";

console.log(`Peddlers of Ketran Build: ${import.meta.env.VITE_APP_POK_BUILD}`);

interface LoadingProps {
  setError: (error: string | null) => void;
}

const Loading = (props: LoadingProps) => {
  const navigate = useNavigate();
  const { setError } = props;

  useEffect(() => {
    const createRoom = async () => {
      try {
        const room = await sessionApi.createRoom();
        console.log(`Loading - created room`, room);
        navigate(`${base}/${room.name}`);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : "Unknown error occurred";
        console.error("Failed to create room:", errorMessage);
        setError(errorMessage);
      }
    };
    createRoom();
  }, [setError]);

  return (
    <Paper sx={{ p: 2, m: 2, width: "fit-content", backgroundColor: "#ddddff" }}>
      <Typography>Loading...</Typography>
    </Paper>
  );
};

const App = () => {
  const [session, setSession] = useState<Session | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [sessionRetryAttempt, setSessionRetryAttempt] = useState<number>(0);

  useEffect(() => {
    if (error) {
      setTimeout(() => {
        setError(null);
      }, 5000);
      console.error(`app - error`, error);
    }
  }, [error]);

  useEffect(() => {
    if (!session) {
      return;
    }
    console.log(`app - sessionId`, session.id);
  }, [session]);

  const getSession = useCallback(async () => {
    try {
      const session = await sessionApi.getCurrent();
      console.log(`app - got sessionId`, session.id);
      setSession(session);
      setSessionRetryAttempt(0);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Unknown error occurred";
      console.error("Failed to get session:", errorMessage);
      setError(errorMessage);

      // Schedule retry after 5 seconds
      setSessionRetryAttempt((prev) => prev + 1);
      setTimeout(() => {
        getSession(); // Retry
      }, 5000);
    }
  }, []);

  useEffect(() => {
    if (session) {
      return;
    }
    getSession();
  }, [session, getSession]);

  return (
    <Box
      sx={{
        p: 0,
        m: 0,
        // maxWidth: { xs: "100%", sm: 800 },
        margin: "0 auto",
        height: "100dvh",
        width: "100dvw",
        display: "flex",
        flexDirection: "column",
        overflowY: "auto",
      }}
    >
      {!session && (
        <ConnectionStatus
          readyState={sessionRetryAttempt > 0 ? ReadyState.CLOSED : ReadyState.CONNECTING}
          reconnectAttempt={sessionRetryAttempt}
        />
      )}
      {session && (
        <Router
          future={{
            v7_startTransition: true,
            v7_relativeSplatPath: true,
          }}
        >
          <Routes>
            <Route element={<RoomView {...{ setError, session, setSession }} />} path={`${base}/:roomName`} />
            <Route element={<Loading {...{ setError }} />} path={`${base}`} />
          </Routes>
        </Router>
      )}
      {error && (
        <Paper
          className="Error"
          sx={{
            position: "absolute",
            top: 0,
            left: 0,
            zIndex: 32767,
            p: 2,
            m: 2,
            width: "fit-content",
            backgroundColor: "#ffdddd",
          }}
        >
          <Typography color="red">{error}</Typography>
        </Paper>
      )}
    </Box>
  );
};

export default App;
