import { createContext, useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import type { AuthSession, AuthUser, ChangePasswordPayload, LoginPayload, RegisterPayload } from '@/types';
import { changePassword as changePasswordService, login as loginService, logout as logoutService, register as registerService, restoreSession } from '@/services/authService';
import { getSupabaseClient, isSupabaseConfigured } from '@/lib/supabase';

type AuthContextValue = {
  user: AuthUser | null;
  session: AuthSession | null;
  isAuthenticated: boolean;
  isBootstrapping: boolean;
  isAdmin: boolean;
  login: (payload: LoginPayload) => Promise<AuthSession>;
  register: (payload: RegisterPayload) => Promise<AuthSession>;
  logout: () => Promise<void>;
  changePassword: (payload: ChangePasswordPayload) => Promise<void>;
};

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

export function AuthProvider({ children }: { children: ReactNode }) {
  const [session, setSession] = useState<AuthSession | null>(null);
  const [isBootstrapping, setIsBootstrapping] = useState(true);

  useEffect(() => {
    let disposed = false;

    restoreSession()
      .then(restoredSession => {
        if (!disposed) {
          setSession(restoredSession);
        }
      })
      .catch(() => {
        if (!disposed) {
          setSession(null);
        }
      })
      .finally(() => {
        if (!disposed) {
          setIsBootstrapping(false);
        }
      });

    // 监听 Supabase Auth 状态：token 刷新 / 跨 tab 登出
    if (!isSupabaseConfigured()) return;

    const supabase = getSupabaseClient();
    const { data: { subscription } } = supabase.auth.onAuthStateChange((event, supabaseSession) => {
      if (disposed) return;
      if (event === 'SIGNED_OUT' || !supabaseSession) {
        setSession(null);
        return;
      }
      if (event === 'TOKEN_REFRESHED' && supabaseSession) {
        setSession(prev => prev ? { ...prev, token: supabaseSession.access_token } : prev);
      }
    });

    return () => {
      disposed = true;
      subscription.unsubscribe();
    };
  }, []);

  async function handleLogin(payload: LoginPayload) {
    const nextSession = await loginService(payload);
    setSession(nextSession);
    return nextSession;
  }

  async function handleRegister(payload: RegisterPayload) {
    const nextSession = await registerService(payload);
    setSession(nextSession);
    return nextSession;
  }

  async function handleLogout() {
    await logoutService();
    setSession(null);
  }

  async function handleChangePassword(payload: ChangePasswordPayload) {
    if (!session) {
      throw new Error('当前未登录');
    }

    await changePasswordService(session.user.id, payload);
  }

  return (
    <AuthContext.Provider
      value={{
        user: session?.user ?? null,
        session,
        isAuthenticated: Boolean(session),
        isBootstrapping,
        isAdmin: session?.user?.role === 'admin',
        login: handleLogin,
        register: handleRegister,
        logout: handleLogout,
        changePassword: handleChangePassword,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}