import { ROUTES } from '@/constants';
import { useNurseProfile } from '@/services/profiles';
import { useMyVariants } from '@/services/catalog';
import { useServiceAreas } from '@/services/serviceAreas';
import { useNurseBankAccounts } from '@/services/nurse';
import { deriveBankStatus } from '@/services/nurse/types';
import { useVerificationStatus } from '@/services/verification';
import { isApproved } from '@/services/verification/types';

export interface ActivationRow {
  key: 'identity' | 'profile' | 'services' | 'coverage' | 'bank';
  labelKey: string;
  passed: boolean;
  href: string;
}

export interface ActivationChecklistState {
  isLoading: boolean;
  isError: boolean;
  retry: () => void;
  /** The four conditions the server's `is_searchable` gate actually checks. */
  searchRows: ActivationRow[];
  /** Verified-primary-IBAN — drives getting paid, NOT search visibility. Kept separate on purpose. */
  bankRow: ActivationRow;
  isSearchVisible: boolean;
  isAcceptingBookings: boolean;
  /** Nothing left to do at all — every row passes and the nurse is actively accepting bookings. */
  isFullyLive: boolean;
}

function isProfileComplete(bio: string, avatarUrl: string | null): boolean {
  return bio.trim().length > 0 && avatarUrl != null;
}

/**
 * The single source of the nurse's go-live state — five already-cached queries folded into the rows
 * `ActivationChecklist` renders and the state `PublishGate` gates on, so the two components (and the
 * dashboard slot) never compute this twice with drifting logic. **Two-tier honesty**: the first four
 * rows are exactly the server's `is_searchable` gate (verification, profile, ≥1 active service, ≥1
 * coverage area); the bank row is a separate "getting paid" concern the search index never reads.
 */
export function useActivationChecklist(): ActivationChecklistState {
  const verification = useVerificationStatus();
  const profile = useNurseProfile();
  const variants = useMyVariants();
  const areas = useServiceAreas();
  const bank = useNurseBankAccounts();

  const isLoading =
    verification.isLoading || profile.isLoading || variants.isLoading || areas.isLoading || bank.isLoading;
  const isError = verification.isError || profile.isError || variants.isError || areas.isError || bank.isError;

  const retry = () => {
    if (verification.isError) verification.refetch();
    if (profile.isError) profile.refetch();
    if (variants.isError) variants.refetch();
    if (areas.isError) areas.refetch();
    if (bank.isError) bank.refetch();
  };

  const hasActiveService = (variants.data?.items ?? []).some((variant) => variant.isActive);
  const hasCoverageArea = (areas.data?.items ?? []).length > 0;
  const hasVerifiedBank = (bank.data ?? []).some((account) => deriveBankStatus(account) === 'verified');

  const searchRows: ActivationRow[] = [
    {
      key: 'identity',
      labelKey: 'row_identity',
      passed: isApproved(verification.data),
      href: ROUTES.NURSE_VERIFICATION,
    },
    {
      key: 'profile',
      labelKey: 'row_profile',
      passed: isProfileComplete(profile.data?.bio ?? '', profile.data?.avatarUrl ?? null),
      href: ROUTES.NURSE_PROFILE,
    },
    { key: 'services', labelKey: 'row_services', passed: hasActiveService, href: ROUTES.NURSE_SERVICES },
    { key: 'coverage', labelKey: 'row_coverage', passed: hasCoverageArea, href: ROUTES.NURSE_COVERAGE },
  ];
  const bankRow: ActivationRow = {
    key: 'bank',
    labelKey: 'row_bank',
    passed: hasVerifiedBank,
    href: ROUTES.NURSE_BANK,
  };

  const isSearchVisible = searchRows.every((row) => row.passed);
  const isAcceptingBookings = profile.data?.isAcceptingBookings ?? false;

  return {
    isLoading,
    isError,
    retry,
    searchRows,
    bankRow,
    isSearchVisible,
    isAcceptingBookings,
    isFullyLive: isSearchVisible && bankRow.passed && isAcceptingBookings,
  };
}
