import { Link, NavLink, Outlet, useParams, useSearchParams } from "react-router-dom";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useAuth } from "@/contexts/AuthContext";
import { buildCouncilApplicationReviewHref, buildStaffApplicationReviewHref } from "@/lib/applicationReviewNavigation";

export interface ApplicationEvidenceOutletContext {
  caseId: string;
  applicationId: string;
}

/**
 * Lớp vỏ `/dashboard/documents/:caseId/evidence` với thanh tab và {@link Outlet} cho trang tổng hợp / xem trước từng loại.
 */
export function ApplicationEvidenceLayout() {
  const { caseId } = useParams();
  const [searchParams] = useSearchParams();
  const applicationId = searchParams.get("applicationId")?.trim() ?? "";
  const { hasRole } = useAuth();
  const isStaff = hasRole("admin") || hasRole("editor");
  const isCouncil = hasRole("editor");

  if (!caseId) {
    return <p className="text-sm text-destructive">Thiếu mã hồ sơ (case).</p>;
  }

  const enc = encodeURIComponent(caseId);
  const base = `/dashboard/documents/${enc}/evidence`;
  const appQ = applicationId ? `?applicationId=${encodeURIComponent(applicationId)}` : "";
  const evidenceReturnTo = `${base}${appQ}`;

  /** Staff: return to council Phiếu đánh giá or admin bundle (no evaluation tab). */
  const backButtonTo =
    isStaff && applicationId
      ? isCouncil
        ? buildCouncilApplicationReviewHref({
            applicationId,
            returnTo: evidenceReturnTo,
            reviewTab: "evaluation",
          })
        : buildStaffApplicationReviewHref({
            applicationId,
            returnTo: evidenceReturnTo,
            reviewTab: "report",
          })
      : "/dashboard/documents";

  const tabClass = ({ isActive }: { isActive: boolean }) =>
    cn(
      "inline-flex items-center rounded-md px-3 py-1.5 text-sm font-medium transition-colors",
      isActive
        ? "bg-primary text-primary-foreground"
        : "text-muted-foreground hover:bg-muted hover:text-foreground",
    );

  return (
    <div className="space-y-4 animate-fade-in w-full min-w-0 max-w-6xl md:max-w-7xl xl:max-w-[min(100%,80rem)] 2xl:max-w-[min(100%,96rem)]">
      <div className="flex flex-wrap items-center gap-2">
        <Button variant="ghost" size="sm" asChild className="gap-1.5 -ml-2">
          <Link to={backButtonTo}>
            <ArrowLeft className="h-4 w-4" />
            Lịch sử hồ sơ
          </Link>
        </Button>
        <span className="text-sm text-muted-foreground">
          Mã sáng kiến: <span className="font-mono text-foreground">{caseId}</span>
        </span>
      </div>

      <div>
        <h1 className="text-2xl font-serif font-semibold tracking-tight">Minh chứng & thẩm định</h1>
      </div>

      <div className="flex flex-wrap gap-1 border-b border-border pb-2">
        <NavLink to={`${base}${appQ}`} end className={tabClass}>
          Quản lý
        </NavLink>
        <NavLink to={`${base}/research${appQ}`} className={tabClass}>
          Xem 2.1 (nghiên cứu)
        </NavLink>
        <NavLink to={`${base}/textbook${appQ}`} className={tabClass}>
          Xem 2.2 (giáo trình)
        </NavLink>
        <NavLink to={`${base}/technical${appQ}`} className={tabClass}>
          Xem kỹ thuật
        </NavLink>
      </div>

      <Outlet
        context={
          { caseId, applicationId: applicationId } satisfies ApplicationEvidenceOutletContext
        }
      />
    </div>
  );
}
