import { useMemo } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import {
  buildInitiativeDraftFromReviewTabs,
  type ReviewDraftTabs,
} from '@/components/admin/review/buildInitiativeDraftFromReviewTabs';
import { useOptionalDraft } from '@/components/applicant/initiative-draft/useDraft';
import {
  ReviewSnapshotSections,
  type ContributionDraftShape,
} from '@/components/applicant/initiative-draft/ReviewSnapshotSections';

interface ReviewPanelProps {
  contributionDraft?: Record<string, unknown>;
  caseId?: string;
  /**
   * Tab JSON when there is no DraftProvider (or context failed to attach).
   * Applicant dashboard should pass application + report here so the tab still renders.
   */
  fallbackDraftTabs?: ReviewDraftTabs;
  onSaveAllDrafts?: (payload: {
    report: Record<string, unknown>;
    application: Record<string, unknown>;
    contribution: Record<string, unknown>;
  }) => Promise<void>;
}

/** Applicant review tab: read-only field snapshot and DOCX preview (see ReviewSnapshotSections). */
export function ReviewPanel({
  contributionDraft,
  caseId,
  fallbackDraftTabs,
  onSaveAllDrafts,
}: ReviewPanelProps) {
  const draftCtx = useOptionalDraft();
  const fallbackDraft = useMemo(
    () => buildInitiativeDraftFromReviewTabs(caseId ?? '', fallbackDraftTabs),
    [caseId, fallbackDraftTabs],
  );
  const draft = draftCtx?.draft ?? fallbackDraft;
  const c = (contributionDraft ?? {}) as ContributionDraftShape;

  return (
    <Card>
      <CardContent className="pt-6">
        <ReviewSnapshotSections
          draft={draft}
          contribution={c}
          caseId={caseId}
          onSaveAllDrafts={onSaveAllDrafts}
        />
      </CardContent>
    </Card>
  );
}
