import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { Lock } from "lucide-react";
import InitiativeReportForm from "@/components/InitiativeReportForm";
import InitiativeApplicationForm from "@/components/InitiativeApplicationForm";
import ContributionConfirmationForm from "@/components/ContributionConfirmationForm";
import InitiativeEvaluationForm from "@/components/InitiativeEvaluationForm";
import ChatAssistant from "@/components/ChatAssistant";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable";
import { reviveContributionDraft } from "@/components/applicant/applicationDrafts";
import type { ApplicationFormState, Author, InitiativeFormState } from "@/components/applicant/initiativeFormTypes";
import type { ApplicantPrefill } from "@/types/applicantPrefill";
import { REVIEW_FORMS_TAB_SEARCH_PARAM } from "@/lib/applicationReviewNavigation";
import { CouncilEvaluationSnapshotProvider } from "@/components/admin/review/councilEvaluationSnapshotContext";
import { StaffApplicationBundleReviewTab } from "@/components/admin/review/StaffApplicationBundleReviewTab";

/** Đồ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 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). */
  reviewApplicationId?: string;
  /** When true, Phiếu đánh giá shows DOCX preview + Duyệt/Từ chối (council review route only). */
  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;
  /**
   * Tab « Mẫu hồ sơ và Minh chứng » (DOCX từ DB + trạng thái MinIO qua API).
   * Mặc định: bật khi xem hồ sơ chỉ đọc có mã nộp và case (không blank-slate).
   */
  showBundleDocxReviewTab?: boolean;
};

export function ReviewFormsPanel({
  caseKey,
  applicantPrefill,
  draftTabs,
  reviewApplicationId,
  enableCouncilEvaluationReview,
  onAdminEvaluationApprove,
  onAdminEvaluationReject,
  formsReadOnly,
  canViewEvaluation,
  canViewChat,
  canInteractChat,
  canVerify,
  mainPanelSize,
  chatPanelSize,
  verificationRequest,
  onVerify,
  onVerificationHandled,
  showBundleDocxReviewTab: showBundleDocxReviewTabProp,
}: ReviewFormsPanelProps) {
  const [searchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState("report");

  const showBundleDocxReviewTab =
    showBundleDocxReviewTabProp ??
    Boolean(
      reviewApplicationId?.trim() &&
        caseKey?.trim() &&
        caseKey !== "blank-slate" &&
        formsReadOnly,
    );

  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", "bundle_review", "evaluation"]);
    const tab = reviewTabFromUrl && allowed.has(reviewTabFromUrl) ? reviewTabFromUrl : "report";
    if (tab === "bundle_review" && !showBundleDocxReviewTab) {
      setActiveTab("report");
      return;
    }
    if (tab === "evaluation" && !canViewEvaluation) {
      setActiveTab("report");
      return;
    }
    setActiveTab(tab);
  }, [caseKey, reviewTabFromUrl, canViewEvaluation, showBundleDocxReviewTab]);

  return (
    <ResizablePanelGroup direction="horizontal" className="h-full min-h-[480px] overflow-hidden">
      <ResizablePanel defaultSize={mainPanelSize} minSize={0}>
        <div className="h-full overflow-auto pr-2">
          <CouncilEvaluationSnapshotProvider>
          <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>
              {showBundleDocxReviewTab ? (
                <TabsTrigger value="bundle_review">Mẫu hồ sơ và Minh chứng</TabsTrigger>
              ) : null}
              {canViewEvaluation && (
                <TabsTrigger value="evaluation" className="h-full gap-1">
                  <Lock size={14} />
                  Phiếu Đánh Giá
                </TabsTrigger>
              )}
            </TabsList>
            <TabsContent value="report">
              <InitiativeReportForm
                key={`${caseKey}-report`}
                applicantPrefill={applicantPrefill}
                initialDraft={draftTabs?.report as Partial<InitiativeFormState> | undefined}
                onVerify={canVerify ? onVerify : undefined}
                readOnly={formsReadOnly}
                showVerifyButton={canVerify}
                onNext={formsReadOnly ? undefined : () => setActiveTab("application")}
              />
            </TabsContent>
            <TabsContent value="application">
              <InitiativeApplicationForm
                key={`${caseKey}-application`}
                applicantPrefill={applicantPrefill}
                initialDraft={draftTabs?.application as Partial<ApplicationFormState> | undefined}
                onVerify={canVerify ? onVerify : undefined}
                readOnly={formsReadOnly}
                showVerifyButton={canVerify}
                onNext={formsReadOnly ? undefined : () => setActiveTab("contribution")}
              />
            </TabsContent>
            <TabsContent value="contribution">
              <ContributionConfirmationForm
                key={`${caseKey}-contribution`}
                applicantPrefill={applicantPrefill}
                initialDraft={reviveContributionDraft(draftTabs?.contribution)}
                mirrorApplicationAuthors={mirrorApplicationAuthors}
                mirrorInitiativeNameFromApplication={mirrorInitiativeNameFromApplication}
                onVerify={canVerify ? onVerify : undefined}
                readOnly={formsReadOnly}
                showVerifyButton={canVerify}
                onNext={
                  formsReadOnly
                    ? undefined
                    : () =>
                        setActiveTab(
                          showBundleDocxReviewTab
                            ? "bundle_review"
                            : canViewEvaluation
                              ? "evaluation"
                              : "report",
                        )
                }
              />
            </TabsContent>
            {showBundleDocxReviewTab ? (
              <TabsContent value="bundle_review" className="min-h-[320px]">
                <StaffApplicationBundleReviewTab
                  key={`${caseKey}-bundle-review`}
                  caseId={caseKey}
                  applicationId={reviewApplicationId ?? ""}
                  draftTabs={draftTabs}
                  enableCouncilReviewActions={Boolean(
                    enableCouncilEvaluationReview && reviewApplicationId?.trim() && caseKey?.trim(),
                  )}
                  onCouncilApprove={onAdminEvaluationApprove}
                  onCouncilReject={onAdminEvaluationReject}
                />
              </TabsContent>
            ) : null}
            {canViewEvaluation && (
              <TabsContent value="evaluation">
                <InitiativeEvaluationForm
                  key={`${caseKey}-evaluation`}
                  applicantReviewContext={applicantPrefill}
                  onVerify={canVerify ? onVerify : undefined}
                  councilReviewMode={Boolean(
                    enableCouncilEvaluationReview && reviewApplicationId?.trim() && caseKey?.trim(),
                  )}
                />
              </TabsContent>
            )}
          </Tabs>
          </CouncilEvaluationSnapshotProvider>
        </div>
      </ResizablePanel>

      {canViewChat && (
        <>
          <ResizableHandle withHandle />
          <ResizablePanel defaultSize={chatPanelSize} minSize={0}>
            <div className="h-full p-2 pl-4">
              <ChatAssistant
                verificationRequest={verificationRequest}
                onVerificationHandled={onVerificationHandled}
                readOnly={!canInteractChat}
              />
            </div>
          </ResizablePanel>
        </>
      )}
    </ResizablePanelGroup>
  );
}
