import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { api } from '@/api';

export interface User {
  id: number;
  username?: string;
  role?: string;
  display_name?: string;
  displayName?: string;
  name?: string;
  is_default_admin?: boolean;
  [key: string]: unknown;
}

interface MeResponse {
  user?: User | null;
  single_user_mode?: boolean;
  has_new_version?: boolean;
}

interface AuthContextValue {
  user: User | null | undefined; // undefined = loading
  singleUserMode: boolean;
  setUser: (user: User | null | undefined) => void;
  logout: () => void | Promise<void>;
  refresh: () => void;
  hasNewVersion: boolean;
  setHasNewVersion: (v: boolean) => void;
}

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

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user,          setUser]          = useState<User | null | undefined>(undefined); // undefined = loading
  const [singleUserMode, setSUM]          = useState(false);
  const [hasNewVersion,  setHasNewVersion] = useState(false);

  function applyMeResponse(raw: unknown) {
    const d = raw as MeResponse;
    setUser(d.user);
    setSUM(d.single_user_mode || false);
    setHasNewVersion(!!d.has_new_version);
  }

  useEffect(() => {
    api.authMode().then(d => {
      if ((d as { auth_mode?: string }).auth_mode === 'single') setSUM(true);
    }).catch(err => console.error('[useAuth] authMode check failed', err));

    api.me().then(applyMeResponse).catch(() => setUser(null));
  }, []);

  const logout = async () => {
    await api.logout();
    setUser(null);
    setSUM(false);
    setHasNewVersion(false);
  };

  const refresh = () => {
    api.me().then(applyMeResponse).catch(() => {
      setUser(null);
      setSUM(false);
    });
  };

  return (
    <AuthContext.Provider value={{
      user, singleUserMode, setUser, logout, refresh,
      hasNewVersion, setHasNewVersion,
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth(): AuthContextValue {
  return useContext(AuthContext) || {
    user: null, setUser: () => {}, logout: () => {}, refresh: () => {},
    singleUserMode: false, hasNewVersion: false, setHasNewVersion: () => {},
  };
}
