'use client';

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react';
import { api, type VerificationStatusResponse } from './api-client';

interface VerificationContextValue {
  status: VerificationStatusResponse | null;
  loading: boolean;
  refresh: () => Promise<void>;
}

const VerificationContext = createContext<VerificationContextValue>({
  status: null,
  loading: true,
  refresh: async () => {},
});

/**
 * Provides the doctor's verification + profile-completeness rollup to
 * every page in the portal. Refreshes on mount and every 60s so the
 * banner reflects backend state shortly after the admin approves.
 */
export function VerificationProvider({ children }: { children: ReactNode }) {
  const [status, setStatus] = useState<VerificationStatusResponse | null>(null);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    try {
      const next = await api.getVerificationStatus();
      setStatus(next);
    } catch {
      // Silent — the banner stays hidden when the API is unreachable.
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void refresh();
    const id = setInterval(() => void refresh(), 60_000);
    return () => clearInterval(id);
  }, [refresh]);

  const value = useMemo(
    () => ({ status, loading, refresh }),
    [status, loading, refresh],
  );

  return (
    <VerificationContext.Provider value={value}>
      {children}
    </VerificationContext.Provider>
  );
}

export function useVerification(): VerificationContextValue {
  return useContext(VerificationContext);
}
