"use client";

import React, { createContext, useContext, useState, useEffect } from "react";
import { userInfo } from "@/lib/user";

export interface UserType {
  id: string;
  name: string;
  phone: string;
}

interface CommonContextType {
  user: UserType | null;
  setUser: (user: UserType | null) => void;
  redirectAfterLogin: string;
  setRedirectAfterLogin: (path: string) => void;
}

const CommonContext = createContext<CommonContextType | undefined>(undefined);

export function CommonProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<UserType | null>(null);
  const [redirectAfterLogin, setRedirectAfterLogin] = useState<string>("/");

  useEffect(() => {
    userInfo().then(({ data: data }) => {
      if (data) {
        const currentUser = {
          id: data.id,
          name: data.name,
          phone: data.phone,
        };
        setUser(currentUser);
      }
    });
  }, []);

  return (
    <CommonContext.Provider value={{ user, setUser, redirectAfterLogin, setRedirectAfterLogin }}>
      {children}
    </CommonContext.Provider>
  );
}

export const useCommonContext = (): CommonContextType => {
  const context = useContext(CommonContext);
  if (context === undefined) {
    throw new Error("useCommon must be used within a CommonProvider");
  }
  return context;
};
