import { useMemo, useState } from "react";
import { Check, X } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import type { InitiativeDraft } from "@/components/applicant/initiative-draft/types";
import type { ContributionDraftShape } from "@/components/applicant/initiative-draft/contributionDraftTypes";
import { ReviewSnapshotSections } from "@/components/applicant/initiative-draft/ReviewSnapshotSections";
import { AdminApplicationFormDocxPreview } from "@/components/admin/review/AdminApplicationFormDocxPreview";
import { AdminEvaluationFormActions } from "@/components/admin/review/AdminEvaluationFormActions";
import { EvidenceVaultLinkButton } from "@/components/evidence/EvidenceVaultLinkButton";
import { getApplicationMeritCategoryHint } from "@/components/admin/review/applicationMeritCategoryHint";
import {
  AdminStaffReadonlyReviewDialog,
  type StaffReadonlyDialogVariant,
} from "@/components/admin/review/AdminStaffReadonlyReviewDialog";
import { useEvidenceStaffReviewAck } from "@/hooks/useEvidenceStaffReviewAck";

export type AdminDocxTemplatePreviewProps = {
  draft: InitiativeDraft;
  contribution: ContributionDraftShape;
  caseId: string;
  applicationId: string;
  /**
   * Hội đồng: Từ chối / Kho minh chứng / Duyệt.
   * Quản trị (chỉ đọc): bỏ qua — footer chỉ còn nút mở kho minh chứng.
   */
  councilReviewActions?: {
    onReject: () => void;
    onApprove: () => void;
  };
  /**
   * Quản trị (chỉ đọc): kết quả {@link collectDocxTemplateCompletenessGaps} để hiển thị trong hộp thoại Từ chối / Duyệt.
   * Không truyền thì coi như không có thiếu sót (tránh báo đỏ sai khi tích hợp chưa truyền prop).
   */
  docxCompletenessGaps?: string[];
};

/**
 * Giống tab xem lại của ứng viên ({@link ReviewPanel}): DOCX từ ba tab Đơn / Báo cáo / Đóng góp.
 */
export function AdminDocxTemplatePreview({
  draft,
  contribution,
  caseId,
  applicationId,
  councilReviewActions,
  docxCompletenessGaps = [],
}: AdminDocxTemplatePreviewProps) {
  const meritHint = useMemo(
    () => getApplicationMeritCategoryHint(draft.application),
    [draft.application],
  );

  const [staffDialog, setStaffDialog] = useState<StaffReadonlyDialogVariant | null>(null);
  const evidenceStaffReviewAcknowledged = useEvidenceStaffReviewAck(caseId.trim() ? caseId : undefined);

  const docxStaffFooter = councilReviewActions ? (
    <AdminEvaluationFormActions
      caseId={caseId}
      applicationId={applicationId}
      onReject={councilReviewActions.onReject}
      onApprove={councilReviewActions.onApprove}
    />
  ) : (
    <>
      <div className="flex flex-wrap justify-end gap-2 items-center">
        <EvidenceVaultLinkButton caseId={caseId} applicationId={applicationId} />
        {evidenceStaffReviewAcknowledged ? (
          <>
            <Button
              type="button"
              variant="outline"
              className="border-destructive/50 text-destructive bg-red-500 text-white hover:bg-destructive/10 px-3"
              aria-label="Từ chối (xem trước)"
              title="Từ chối (xem trước)"
              onClick={() => setStaffDialog("reject")}
            >
              <X className="h-4 w-4 shrink-0" aria-hidden />
            </Button>
            <Button
              type="button"
              className="px-3 bg-green-500 text-white hover:bg-green-600"
              aria-label="Duyệt (xem trước)"
              title="Duyệt (xem trước)"
              onClick={() => setStaffDialog("approve")}
            >
              <Check className="h-4 w-4 shrink-0" aria-hidden />
            </Button>
          </>
        ) : (
          <>
            <Button
              type="button"
              variant="outline"
              className="border-destructive/50 text-destructive hover:bg-destructive/10"
              onClick={() => setStaffDialog("reject")}
            >
              Từ chối
            </Button>
            <Button type="button" onClick={() => setStaffDialog("approve")}>
              Duyệt
            </Button>
          </>
        )}
      </div>
      <AdminStaffReadonlyReviewDialog
        open={staffDialog !== null}
        onOpenChange={(open) => {
          if (!open) setStaffDialog(null);
        }}
        applicationId={applicationId}
        variant={staffDialog ?? "approve"}
        meritHint={meritHint}
        docxCompletenessGaps={docxCompletenessGaps}
        staffEvidenceReviewAcknowledged={evidenceStaffReviewAcknowledged}
      />
    </>
  );

  return (
    <Card>
      <CardContent className="h-full pt-6">
        {councilReviewActions ? (
          <ReviewSnapshotSections
            draft={draft}
            contribution={contribution}
            caseId={caseId}
            docxStaffFooter={docxStaffFooter}
          />
        ) : (
          <AdminApplicationFormDocxPreview
            draft={draft}
            contribution={contribution}
            caseId={caseId}
            docxStaffFooter={docxStaffFooter}
          />
        )}
      </CardContent>
    </Card>
  );
}
