'use client';

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

interface OrgProfile {
  id: string;
  email: string;
  name: string | null;
  role: 'ORG_OWNER' | 'ORG_ADMIN';
  organization: { id: string; slug: string; name: string };
}

interface OrgAdminState {
  orgAdmin: OrgProfile | null;
  loading: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
}

const OrgAdminContext = createContext<OrgAdminState | null>(null);

export function OrgAdminProvider({ children }: { children: React.ReactNode }) {
  const [orgAdmin, setOrgAdmin] = useState<OrgProfile | null>(null);
  const [loading, setLoading] = useState(true);

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

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

  const login = useCallback(async (email: string, password: string) => {
    const res = await fetch('/api/auth/org/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();
    setOrgAdmin(data.orgAdmin);
    // Refresh full profile (includes organization object)
    void checkSession();
  }, [checkSession]);

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

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

export function useOrgAdmin(): OrgAdminState {
  const ctx = useContext(OrgAdminContext);
  if (!ctx) throw new Error('useOrgAdmin must be used within <OrgAdminProvider>');
  return ctx;
}
