"use client";

import useHandleSuccessfulLogin from "@/auth/use-handle-successful-login";
import {
  createContext,
  Dispatch,
  ReactNode,
  SetStateAction,
  useContext,
  useState,
} from "react";

export type LoginContext = {
  path: "greeting" | "phoneLogin" | "phoneVerification" | "complete_personal";
  setPath: Dispatch<SetStateAction<LoginContext["path"]>>;
  lastSession?: {
    username: string;
    image: string;
    phone: string;
    email: string;
  };
  phoneNumber: string;
  setPhoneNumber: Dispatch<SetStateAction<string>>;
  email: string;
  setEmail: Dispatch<SetStateAction<string>>;
  token?: string;
  setToken: Dispatch<SetStateAction<string | undefined>>;
  handleSuccessfulLogin: () => void;
};

const loginContext = createContext<LoginContext | undefined>(undefined);

function initialPhoneFromLastSession(
  lastSession?: LoginContext["lastSession"],
): string {
  const raw = lastSession?.phone?.trim();
  if (!raw) return "";
  return raw.replace(/\D/g, "");
}

export function LoginContextProvider({
  children,
  lastSession,
}: {
  children: ReactNode;
  lastSession?: LoginContext["lastSession"];
}) {
  // Always start on phone entry. The modal never implemented a "greeting" step;
  // using "greeting" incorrectly showed the OTP screen with an empty number.
  const [path, setPath] = useState<LoginContext["path"]>("phoneLogin");
  const [phoneNumber, setPhoneNumber] = useState(() =>
    initialPhoneFromLastSession(lastSession),
  );
  const [email, setEmail] = useState("");
  const [token, setToken] = useState<string | undefined>();
  const handleSuccessfulLogin = useHandleSuccessfulLogin();
  const contextState: LoginContext = {
    path,
    setPath,
    lastSession,
    phoneNumber,
    setPhoneNumber,
    email,
    setEmail,
    token,
    setToken,
    handleSuccessfulLogin,
  };

  return (
    <loginContext.Provider value={contextState}>
      {children}
    </loginContext.Provider>
  );
}

export function useLoginContext() {
  const context = useContext(loginContext);
  if (!context)
    throw new Error("useLoginContext must be used inside LoginContextProvider");
  return context;
}
