"use client";

import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { apiClient } from "@/lib/api-client";
import type { Employee, LoginResponse } from "@/lib/types";

const STORAGE_KEY = "absentic-hz.auth";

interface StoredAuth {
  token: string;
  employee: Employee;
}

interface AuthContextValue {
  token: string | null;
  employee: Employee | null;
  isReady: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextValue | null>(null);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [{ token, employee, isReady }, setAuthState] = useState<{
    token: string | null;
    employee: Employee | null;
    isReady: boolean;
  }>({ token: null, employee: null, isReady: false });

  useEffect(() => {
    let stored: StoredAuth | null = null;
    try {
      const raw = window.localStorage.getItem(STORAGE_KEY);
      if (raw) {
        stored = JSON.parse(raw) as StoredAuth;
      }
    } catch {
      window.localStorage.removeItem(STORAGE_KEY);
    }

    // Restoring the Sanctum token from localStorage can only happen after
    // mount (no `window` on the server) — this is the standard SSR-safe
    // hydration pattern, not state that should be derived during render.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setAuthState({ token: stored?.token ?? null, employee: stored?.employee ?? null, isReady: true });

    if (stored?.token) {
      apiClient
        .get<{ data: Employee }>("/auth/me", stored.token)
        .then(({ data: employee }) => {
          const refreshed: StoredAuth = { token: stored!.token, employee };
          window.localStorage.setItem(STORAGE_KEY, JSON.stringify(refreshed));
          // eslint-disable-next-line react-hooks/set-state-in-effect
          setAuthState((current) => ({ ...current, employee }));
        })
        .catch(() => {
          // Stale cached profile is still usable; the next successful
          // refresh (or re-login) will pick up any changes.
        });
    }
  }, []);

  const login = async (email: string, password: string) => {
    const response = await apiClient.postJson<LoginResponse>("/auth/login", {
      email,
      password,
    });

    if (response.type !== "employee") {
      throw new Error(
        "Akun ini adalah akun admin/HR. Portal admin belum tersedia di aplikasi ini.",
      );
    }

    const stored: StoredAuth = { token: response.token, employee: response.user };
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(stored));
    setAuthState({ token: stored.token, employee: stored.employee, isReady: true });
  };

  const logout = () => {
    window.localStorage.removeItem(STORAGE_KEY);
    setAuthState({ token: null, employee: null, isReady: true });
  };

  const value = useMemo(
    () => ({ token, employee, isReady, login, logout }),
    [token, employee, isReady],
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth(): AuthContextValue {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}
