import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
import { authService } from "@/services/auth.service";
import { clearToken, getActiveEntityId, setActiveEntityId } from "@/lib/api-client";
import type { User, UserRole } from "@/types/auth";

export type { UserRole };

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  selectedEntityId: number | null;
  selectedEntity: User["entities"][number] | null;
  setSelectedEntityId: (entityId: number | null) => void;
  login: (email: string, password: string) => Promise<User>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [selectedEntityId, setSelectedEntityIdState] = useState<number | null>(getActiveEntityId());
  const [isLoading, setIsLoading] = useState(true);

  const syncEntitySelection = useCallback((nextUser: User | null) => {
    const available = nextUser?.entities ?? [];
    if (available.length === 0) {
      setSelectedEntityIdState(null);
      setActiveEntityId(null);
      return;
    }
    const stored = getActiveEntityId();
    const validStored = stored && available.some((e) => e.id === stored) ? stored : null;
    const next = validStored ?? available[0].id;
    setSelectedEntityIdState(next);
    setActiveEntityId(next);
  }, []);

  useEffect(() => {
    const token = localStorage.getItem("encoach_token");
    if (!token) {
      setIsLoading(false);
      return;
    }

    authService
      .getUser()
      .then((u) => {
        setUser(u);
        syncEntitySelection(u);
      })
      .catch(() => {
        clearToken();
        setActiveEntityId(null);
      })
      .finally(() => setIsLoading(false));
  }, [syncEntitySelection]);

  const login = useCallback(async (email: string, password: string): Promise<User> => {
    const res = await authService.login({ login: email, password });
    setUser(res.user);
    syncEntitySelection(res.user);
    return res.user;
  }, [syncEntitySelection]);

  const setSelectedEntityId = useCallback((entityId: number | null) => {
    if (!user) {
      setSelectedEntityIdState(null);
      setActiveEntityId(null);
      return;
    }
    if (entityId == null) {
      setSelectedEntityIdState(null);
      setActiveEntityId(null);
      return;
    }
    if (!user.entities.some((e) => e.id === entityId)) return;
    setSelectedEntityIdState(entityId);
    setActiveEntityId(entityId);
  }, [user]);

  const logout = useCallback(async () => {
    await authService.logout();
    setUser(null);
    setSelectedEntityIdState(null);
    setActiveEntityId(null);
  }, []);

  const selectedEntity =
    user?.entities.find((e) => e.id === selectedEntityId) ??
    user?.entities[0] ??
    null;

  return (
    <AuthContext.Provider
      value={{
        user,
        isAuthenticated: !!user,
        isLoading,
        selectedEntityId,
        selectedEntity,
        setSelectedEntityId,
        login,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

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