'use client';

import { createContext, useCallback, useContext, useEffect, useState } from 'react';

interface SuperAdmin {
  id: string;
  email: string;
  name: string | null;
}

interface SuperAdminState {
  admin: SuperAdmin | null;
  loading: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
}

const SuperAdminContext = createContext<SuperAdminState | null>(null);

export function SuperAdminProvider({ children }: { children: React.ReactNode }) {
  const [admin, setAdmin] = useState<SuperAdmin | null>(null);
  const [loading, setLoading] = useState(true);

  const checkSession = useCallback(async () => {
    try {
      const res = await fetch('/api/auth/super/me', { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setAdmin(data);
      } else {
        setAdmin(null);
      }
    } catch {
      setAdmin(null);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { void checkSession(); }, [checkSession]);

  const login = useCallback(async (email: string, password: string) => {
    const res = await fetch('/api/auth/super/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Login failed' }));
      throw new Error(err.message ?? 'Login failed');
    }
    const data = await res.json();
    setAdmin(data.superAdmin);
  }, []);

  const logout = useCallback(async () => {
    await fetch('/api/auth/super/logout', { method: 'POST', credentials: 'include' });
    setAdmin(null);
  }, []);

  return (
    <SuperAdminContext.Provider value={{ admin, loading, login, logout }}>
      {children}
    </SuperAdminContext.Provider>
  );
}

export function useSuperAdmin(): SuperAdminState {
  const ctx = useContext(SuperAdminContext);
  if (!ctx) throw new Error('useSuperAdmin must be used within <SuperAdminProvider>');
  return ctx;
}
