import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  reviveContributionDraft,
  type ApplicantPrefill,
  type ApplicationFormState,
  type Author,
  type InitiativeFormState,
} from "@ump/shared";
import InitiativeReportForm from "@/components/InitiativeReportForm";
import InitiativeApplicationForm from "@/components/InitiativeApplicationForm";
import ContributionConfirmationForm from "@/components/ContributionConfirmationForm";
import { REVIEW_FORMS_TAB_SEARCH_PARAM } from "@/lib/applicationReviewNavigation";

/**
 * Applicant read-only review panel (frontend_user walking-skeleton).
 *
 * Renders the three submitted forms (Báo cáo / Đơn / Xác nhận đóng góp) — reused verbatim from
 * the slice-3 ports. The admin/AI surfaces of the fe0 `ReviewFormsPanel` are intentionally
 * deferred to slice 5: the `ChatAssistant` verify panel (no AI ported yet), the council
 * « Phiếu đánh giá » tab, and the staff « Mẫu hồ sơ và Minh chứng » bundle-review tab. Applicants
 * never see evaluation/bundle anyway (gated off by permission); chat/verify lands with the AI slice.
 *
 * The prop signature matches the fe0 component so `ApplicationReviewPage` compiles unchanged; the
 * chat/evaluation-related props are accepted but unused here.
 */
export type ReviewFormsPanelProps = {
  caseKey: string;
  applicantPrefill?: ApplicantPrefill;
  draftTabs?: {
    report?: Record<string, unknown>;
    application?: Record<string, unknown>;
    contribution?: Record<string, unknown>;
  };
  /** Submission id (`detail.id`) for evidence vault + evaluation actions (staff review) — slice 5. */
  reviewApplicationId?: string;
  enableCouncilEvaluationReview?: boolean;
  onAdminEvaluationApprove?: () => void | Promise<void>;
  onAdminEvaluationReject?: () => void | Promise<void>;
  formsReadOnly: boolean;
  canViewEvaluation: boolean;
  canViewChat: boolean;
  canInteractChat: boolean;
  canVerify: boolean;
  mainPanelSize: number;
  chatPanelSize: number;
  verificationRequest: { fieldName: string; content: string } | null;
  onVerify: (fieldName: string, content: string) => void;
  onVerificationHandled: () => void;
  showBundleDocxReviewTab?: boolean;
};

/** Đồng bộ tab Xác nhận đóng góp với `authors` của tab Đơn khi không có DraftProvider. */
function authorsForContributionMirror(
  applicationTab: Record<string, unknown> | undefined,
): Author[] | undefined {
  if (!applicationTab) return undefined;
  const raw = applicationTab.authors;
  if (!Array.isArray(raw) || raw.length === 0) return undefined;
  return raw as Author[];
}

function initiativeNameForContributionMirror(
  applicationTab: Record<string, unknown> | undefined,
): string | undefined {
  if (!applicationTab) return undefined;
  return String((applicationTab as { initiativeName?: unknown }).initiativeName ?? "");
}

export function ReviewFormsPanel({
  caseKey,
  applicantPrefill,
  draftTabs,
  formsReadOnly,
}: ReviewFormsPanelProps) {
  const [searchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState("report");

  const mirrorApplicationAuthors = useMemo(
    () => authorsForContributionMirror(draftTabs?.application),
    [caseKey, draftTabs?.application],
  );

  const mirrorInitiativeNameFromApplication = useMemo(
    () => initiativeNameForContributionMirror(draftTabs?.application),
    [caseKey, draftTabs?.application],
  );

  const reviewTabFromUrl = searchParams.get(REVIEW_FORMS_TAB_SEARCH_PARAM);

  useEffect(() => {
    const allowed = new Set(["report", "application", "contribution"]);
    setActiveTab(reviewTabFromUrl && allowed.has(reviewTabFromUrl) ? reviewTabFromUrl : "report");
  }, [caseKey, reviewTabFromUrl]);

  return (
    <div className="h-full overflow-auto pr-2">
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="b-4 flex-wrap h-auto gap-1">
          <TabsTrigger value="report">Báo cáo Mô tả Sáng kiến</TabsTrigger>
          <TabsTrigger value="application">Đơn Đề nghị Công nhận</TabsTrigger>
          <TabsTrigger value="contribution">Xác nhận Tỷ lệ Đóng góp</TabsTrigger>
        </TabsList>
        <TabsContent value="report">
          <InitiativeReportForm
            key={`${caseKey}-report`}
            applicantPrefill={applicantPrefill}
            initialDraft={draftTabs?.report as Partial<InitiativeFormState> | undefined}
            readOnly={formsReadOnly}
            showVerifyButton={false}
            onNext={formsReadOnly ? undefined : () => setActiveTab("application")}
          />
        </TabsContent>
        <TabsContent value="application">
          <InitiativeApplicationForm
            key={`${caseKey}-application`}
            applicantPrefill={applicantPrefill}
            initialDraft={draftTabs?.application as Partial<ApplicationFormState> | undefined}
            readOnly={formsReadOnly}
            showVerifyButton={false}
            onNext={formsReadOnly ? undefined : () => setActiveTab("contribution")}
          />
        </TabsContent>
        <TabsContent value="contribution">
          <ContributionConfirmationForm
            key={`${caseKey}-contribution`}
            applicantPrefill={applicantPrefill}
            initialDraft={reviveContributionDraft(draftTabs?.contribution)}
            mirrorApplicationAuthors={mirrorApplicationAuthors}
            mirrorInitiativeNameFromApplication={mirrorInitiativeNameFromApplication}
            readOnly={formsReadOnly}
            showVerifyButton={false}
            onNext={formsReadOnly ? undefined : () => setActiveTab("report")}
          />
        </TabsContent>
      </Tabs>
    </div>
  );
}
