"use client";

import LoadingScreen from "@/components/LoadingScreen";
import { useAppSession } from "@/hooks/useAppSession";
import useCheckSession from "@/hooks/useCheckSession";
import { ActiveSession, AppSession } from "@/types/app";
import { useSession } from "next-auth/react";
import React from "react";

type AppHeaderType = {
  title: {
    link?: string;
    text?: string;
    path?: {
      text?: string;
      link?: string;
    }[];
  };
  opt?: React.ReactNode;
};

type AppType = {
  header?: AppHeaderType;
  activeSession: ActiveSession | Record<string, never>;
  signal: boolean;
  setHeader: React.Dispatch<React.SetStateAction<AppHeaderType | undefined>>;
  sendSignal: React.Dispatch<React.SetStateAction<boolean>>;
};
const AppContext = React.createContext<AppType | undefined>(undefined);

type AppProviderProps = { children: React.ReactNode };

export const App: FCC<AppProviderProps> = ({
  children,
}: AppProviderProps) => {
  const { data, status } = useSession() as AppSession;

  const { isInactive } = useCheckSession();
  const { activeSession } = useAppSession(data);

  isInactive(status);

  const [header, setHeader] = React.useState<AppHeaderType>();
  const [signal, sendSignal] = React.useState<boolean>(false);

  return (
    <AppContext.Provider
      value={{
        header,
        activeSession,
        signal,
        setHeader,
        sendSignal,
      }}
    >
      {status === "loading" ? <LoadingScreen /> : children}
    </AppContext.Provider>
  );
};

export const useApp = (): AppType => {
  const context = React.useContext(AppContext);

  if (!context) {
    throw new Error("useApp must be used within an AppProvider");
  }

  return context;
};
