import React, { createContext, useContext, useEffect, useState } from "react";
import { Tunables } from '../../Components/ChatQuery';
import { SetSnackType } from '../../Components/Snack';
import { connectionBase } from '../../Global';

// Define the UserInfo interface for type safety
interface UserQuestion {
  question: string;
  tunables?: Tunables;
};

interface UserInfo {
  type: 'candidate' | 'employer' | 'guest';
  description: string;
  rag_content_size: number;
  username: string;
  first_name: string;
  last_name: string;
  full_name: string;
  contact_info: Record<string, string>;
  questions: UserQuestion[],
  isAuthenticated: boolean,
  has_profile: boolean,
  title: string;
  location: string;
  email: string;
  phone: string;
  // Fields used in AI generated personas
  age?: number,
  ethnicity?: string,
  gender?: string,
};

type UserContextType = {
  user: UserInfo | null;
  setUser: (user: UserInfo | null) => void;
};

const UserContext = createContext<UserContextType | undefined>(undefined);

const useUser = () => {
  const ctx = useContext(UserContext);
  if (!ctx) throw new Error("useUser must be used within a UserProvider");
  return ctx;
};

interface UserProviderProps {
  children: React.ReactNode;
  sessionId: string | undefined;
  setSnack: SetSnackType;
};
const UserProvider: React.FC<UserProviderProps> = (props: UserProviderProps) => {
  const { sessionId, children, setSnack } = props;
  const [user, setUser] = useState<UserInfo | null>(null);

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

    const fetchUserFromSession = async (): Promise<UserInfo | null> => {
      try {
        let response;
        response = await fetch(`${connectionBase}/api/user/${sessionId}`, {
          method: 'GET',
          credentials: 'include',
        });
        if (!response.ok) {
          throw new Error('Session not found');
        }
        const user: UserInfo = {
          ...(await response.json()),
          type: "guest",
          isAuthenticated: false,
          logout: () => { },
        }
        console.log("Loaded user:", user);
        setUser(user);
      } catch (err) {
        setSnack("" + err);
        setUser(null);
      }
      return null;
    };

    fetchUserFromSession();
  }, [sessionId, user, setUser]);

  if (sessionId === undefined) {
    return <></>;
  }
  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
};

export type {
  UserInfo
};

export {
    UserProvider,
    useUser
};