/**
 * Shared layout for staff viewing a submitted application bundle from the API.
 * Admin (`/dashboard/admin/applications/review`) sees applicant tabs only — no Phiếu đánh giá.
 * Council/editor (`/dashboard/council/applications/review`) includes Phiếu đánh giá + approve/reject workflow.
 */
import { useCallback, useMemo, useState } from "react";
import { Link, Navigate, useSearchParams } from "react-router-dom";
import { ArrowLeft } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { Button } from "@/components/ui/button";
import { ReviewFormsPanel } from "@/components/application-review/ReviewFormsPanel";
import { useApplicationReviewDetail } from "@/hooks/useApplicationReviewDetail";
import type { ApplicantPrefill } from "@/types/applicantPrefill";
import { ApplicationBackupDownloadButton } from "@/components/admin/ApplicationBackupDownloadButton";

export type StaffApplicationReviewVariant = "admin" | "council";

export function StaffApplicationReviewShell({ variant }: { variant: StaffApplicationReviewVariant }) {
  const [searchParams] = useSearchParams();
  const applicationId = searchParams.get("applicationId") ?? "";
  const returnToRaw = searchParams.get("returnTo") ?? "/dashboard";
  const returnToSafe = returnToRaw.startsWith("/dashboard") ? returnToRaw : "/dashboard";

  const { hasRole, loading: authLoading, hasPermission } = useAuth();
  const isAdminAccount = hasRole("admin");
  const isCouncilAccount = hasRole("editor");

  const mayAccess =
    (variant === "admin" && isAdminAccount) || (variant === "council" && isCouncilAccount);

  /** List page to return to (inbox, projects, council deep-link); restricted to `/dashboard/*`. */
  const backToListHref = returnToSafe;

  const canViewEvaluation = variant === "council" && hasPermission("evaluation.view");
  const enableCouncilEvaluationReview = variant === "council";
  const canViewChat = hasPermission("chat.view");
  const canInteractChat = hasPermission("chat.interact");
  const canVerify = hasPermission("application.verify");
  const reviewFormsReadOnly = true;

  const { detailQuery, draftBundleQuery, detail, draftCaseIdForDetail } = useApplicationReviewDetail(applicationId, {
    enabled: Boolean(applicationId) && mayAccess,
    syncLocalSubmission: false,
  });

  const [verificationRequest, setVerificationRequest] = useState<{ fieldName: string; content: string } | null>(null);

  const handleVerify = useCallback(
    (fieldName: string, content: string) => {
      if (canVerify) setVerificationRequest({ fieldName, content });
    },
    [canVerify],
  );
  const handleVerificationHandled = useCallback(() => setVerificationRequest(null), []);

  const applicantPrefill = useMemo((): ApplicantPrefill | undefined => {
    if (!detail) return undefined;
    return {
      initiativeName: detail.name,
      authorName: detail.author.name,
    };
  }, [detail]);

  const mainPanelSize = canViewChat ? 70 : 100;
  const chatPanelSize = canViewChat ? 30 : 0;

  const heading =
    variant === "admin" ? "Xem hồ sơ đã nộp (quản trị)" : "Xem hồ sơ đã nộp (Hội đồng)";
  const descriptionLead =
    variant === "admin"
      ? "Dữ liệu từ máy chủ: Báo cáo mô tả, Đơn đề nghị, Xác nhận đóng góp."
      : `Dữ liệu từ máy chủ: Báo cáo mô tả, Đơn đề nghị, Xác nhận đóng góp${
          canViewEvaluation ? ", Phiếu đánh giá (Hội đồng)" : ""
        }.`;

  if (authLoading) {
    return <div className="text-sm text-muted-foreground">Đang xác thực…</div>;
  }

  if (!mayAccess) {
    return <Navigate to="/unauthorized" replace />;
  }

  if (!applicationId) {
    return <Navigate to="/dashboard" replace />;
  }

  if (detailQuery.isLoading) {
    return <div className="text-sm text-muted-foreground">Đang tải hồ sơ…</div>;
  }

  if (!detail) {
    return (
      <div className="space-y-4">
        <Button variant="ghost" size="sm" asChild className="gap-2">
          <Link to={backToListHref}>
            <ArrowLeft className="h-4 w-4" />
            Quay lại danh sách
          </Link>
        </Button>
        <p className="text-muted-foreground">Không tìm thấy hồ sơ với mã đã chọn.</p>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col overflow-hidden animate-fade-in">
      <div className="mb-4 flex shrink-0 flex-wrap items-start justify-between gap-3">
        <div className="space-y-1">
          <Button variant="ghost" size="sm" asChild className="gap-2 -ml-2">
            <Link to={backToListHref}>
              <ArrowLeft className="h-4 w-4" />
              Quay lại danh sách
            </Link>
          </Button>
          <h1 className="text-xl font-semibold tracking-tight">{heading}</h1>
          <p className="text-sm text-muted-foreground max-w-3xl">{descriptionLead}</p>
        </div>
        <div className="flex flex-col items-end gap-2 shrink-0">
          {variant === "admin" ? (
            <ApplicationBackupDownloadButton applicationId={applicationId} author={detail.author} />
          ) : null}
        </div>
      </div>

      <div className="min-h-0 flex-1">
        {draftBundleQuery.isError ? (
          <p className="text-sm text-amber-700 dark:text-amber-500 py-2">
            Không tải được bản nháp đầy đủ từ cơ sở dữ liệu (thiếu mã case hoặc lỗi máy chủ). Kiểm tra trường mã bản nháp trên hồ sơ hoặc thử lại sau.
          </p>
        ) : null}
        <ReviewFormsPanel
          caseKey={draftCaseIdForDetail || applicationId}
          applicantPrefill={applicantPrefill}
          draftTabs={draftBundleQuery.data?.tabs}
          reviewApplicationId={applicationId}
          enableCouncilEvaluationReview={enableCouncilEvaluationReview}
          formsReadOnly={reviewFormsReadOnly}
          canViewEvaluation={canViewEvaluation}
          canViewChat={canViewChat}
          canInteractChat={canInteractChat}
          canVerify={canVerify}
          mainPanelSize={mainPanelSize}
          chatPanelSize={chatPanelSize}
          verificationRequest={verificationRequest}
          onVerify={handleVerify}
          onVerificationHandled={handleVerificationHandled}
        />
      </div>
    </div>
  );
}
