"use client";

import { useState, useRef, useEffect } from "react";
import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import Modal from "@/components/Modal";
import { useTranslations } from "next-intl";
import { useDashboardControllerGetScreeningDetailV1 } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { generatePDFFromElement } from "@/lib/generateScreeningPDF";
import { computeSuicideRisk } from "@/lib/suicideRiskAlgorithm";
import ReportCard from "@/components/practitioner/ReportCard";

interface ViewReportModalProps {
  isOpen: boolean;
  onClose: () => void;
  clientId?: number;
  screeningId?: number | null;
  suicideRisk?: string;
  clientName?: string;
  clientAge?: number | null;
  autoDownload?: boolean;
}

interface ScaleResult {
  name: string;
  key: string;
  percentage: number;
  color: string;
  raw_score?: number;
}

const SCALE_ORDER = [
  "somatization",
  "cognitive_issues",
  "demoralization",
  "anhedonia",
  "anxiety",
  "suicidal_ideation",
  "activation",
  "disconstraint",
  "substance_use_problems",
];

const SCALE_NAME_KEYS: Record<string, string> = {
  somatization: "practitioner.scales.somatization",
  cognitive_issues: "practitioner.scales.cognitiveIssues",
  demoralization: "practitioner.scales.demoralization",
  anhedonia: "practitioner.scales.anhedonia",
  anxiety: "practitioner.scales.anxiety",
  suicidal_ideation: "practitioner.scales.suicidalIdeation",
  activation: "practitioner.scales.activation",
  disconstraint: "practitioner.scales.disconstraint",
  substance_use_problems: "practitioner.scales.substanceUseProblems",
};

const SCALE_INTERPRETATION_KEYS: Record<string, string> = {
  somatization: "somatizationInterpretation",
  cognitive_issues: "cognitiveIssuesInterpretation",
  demoralization: "demoralizationInterpretation",
  anhedonia: "anhedoniaInterpretation",
  anxiety: "anxietyInterpretation",
  suicidal_ideation: "suicidalIdeationInterpretation",
  activation: "activationInterpretation",
  disconstraint: "disconstraintInterpretation",
  substance_use_problems: "substanceUseInterpretation",
};

const SCALE_DESCRIPTION_KEYS: Record<string, string> = {
  somatization: "somatizationDescription",
  cognitive_issues: "cognitiveIssuesDescription",
  demoralization: "demoralizationDescription",
  anhedonia: "anhedoniaDescription",
  anxiety: "anxietyDescription",
  suicidal_ideation: "suicidalIdeationDescription",
  activation: "activationDescription",
  disconstraint: "disconstraintDescription",
  substance_use_problems: "substanceUseDescription",
};

const SCALE_NOT_ELEVATED_KEYS: Record<string, string> = {
  somatization: "somatizationNotElevated",
  cognitive_issues: "cognitiveIssuesNotElevated",
  demoralization: "demoralizationNotElevated",
  anhedonia: "anhedoniaNotElevated",
  anxiety: "anxietyNotElevated",
  suicidal_ideation: "suicidalIdeationNotElevated",
  activation: "activationNotElevated",
  disconstraint: "disconstraintNotElevated",
  substance_use_problems: "substanceUseNotElevated",
};

const PRACTITIONER_SCALE_GROUPS = [
  { key: "somaticCognitive", scales: ["somatization", "cognitive_issues"] },
  { key: "internalizing", scales: ["demoralization", "anhedonia", "anxiety", "suicidal_ideation"] },
  { key: "externalizing", scales: ["activation", "disconstraint", "substance_use_problems"] },
];

export default function ViewReportModal({
  isOpen,
  onClose,
  clientId,
  screeningId,
  suicideRisk: suicideRiskProp,
  clientName: clientNameProp,
  clientAge: clientAgeProp,
  autoDownload,
}: ViewReportModalProps) {
  const t = useTranslations();

  const [isDownloading, setIsDownloading] = useState(false);
  const reportRef = useRef<HTMLDivElement>(null);
  const hasAutoDownloaded = useRef(false);

  const { data: response, isLoading } = useDashboardControllerGetScreeningDetailV1(
    clientId || 0,
    screeningId || 0,
    { query: { enabled: (isOpen || !!autoDownload) && !!clientId && !!screeningId } }
  );

  const reportData = (response as any)?.data;

  const baseRisk =
    suicideRiskProp ||
    reportData?.suicide_risk_category ||
    reportData?.highest_risk ||
    reportData?.screening?.suicide_risk_category ||
    reportData?.screening?.highest_risk ||
    reportData?.overall_risk ||
    reportData?.screening?.overall_risk ||
    reportData?.risk_level ||
    "";
  const _itemResponsesArr: any[] = Array.isArray(reportData?.item_responses) ? reportData.item_responses : [];
  const _resultsArr: any[] = reportData?.results || [];
  const suicideRisk = computeSuicideRisk({
    itemResponses: _itemResponsesArr,
    results: _resultsArr,
    backendRisk: baseRisk,
  });

  const getRiskLabel = (risk: string) => {
    if (!risk) return "-";
    const normalized = risk.toLowerCase();
    if (normalized.includes("at least moderate") || normalized.includes("high") || normalized.includes("moderate") || normalized.includes("medium")) return t("practitioner.common.high");
    if (normalized.includes("mild")) return t("practitioner.common.mild");
    if (normalized.includes("low")) return t("practitioner.common.low");
    return risk.charAt(0).toUpperCase() + risk.slice(1).toLowerCase();
  };

  const getSuicideRiskNarrative = () => {
    const normalized = suicideRisk.toLowerCase();
    if (normalized.includes("high") || normalized.includes("moderate"))
      return t("practitioner.report.suicideRiskNarrativeModerate");
    if (normalized.includes("mild"))
      return t("practitioner.report.suicideRiskNarrativeMild");
    return t("practitioner.report.suicideRiskNarrativeLow");
  };

  const getScaleResults = (): ScaleResult[] => {
    const scales = reportData?.results || reportData?.scale_results || reportData?.scales || [];
    if (!Array.isArray(scales) || scales.length === 0) return [];

    const mapped = scales.map((scale: any) => {
      const scaleName = scale.scale_name || scale.name || scale.label || "unknown";
      return {
        name: SCALE_NAME_KEYS[scaleName] ? t(SCALE_NAME_KEYS[scaleName]) : scaleName,
        key: scaleName,
        percentage: Math.round(
          parseFloat(scale.percentile || scale.percentage || scale.score || scale.value || "0")
        ),
        color: "bg-cyan-400",
        sortOrder: SCALE_ORDER.indexOf(scaleName),
        raw_score: scale.raw_score != null ? Number(scale.raw_score) : undefined,
      };
    });

    return mapped
      .sort((a: any, b: any) => {
        if (a.sortOrder === -1) return 1;
        if (b.sortOrder === -1) return -1;
        return a.sortOrder - b.sortOrder;
      })
      .map(({ name, key, percentage, color, raw_score }: any) => ({ name, key, percentage, color, raw_score }));
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return "-";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" });
  };

  const handleDownloadPDF = async () => {
    if (isDownloading || !reportRef.current) return;
    setIsDownloading(true);
    try {
      await generatePDFFromElement(
        reportRef.current,
        screeningId?.toString() ?? "",
        clientNameProp || reportData?.client_name
      );
    } catch (error) {
      console.error("Failed to download PDF:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  const scaleResults = reportData ? getScaleResults() : [];

  useEffect(() => {
    if (!autoDownload || isLoading || !reportData || hasAutoDownloaded.current || !reportRef.current) return;
    hasAutoDownloaded.current = true;
    handleDownloadPDF().then(() => onClose());
  }, [autoDownload, isLoading, reportData]);

  const renderReportContent = () => (
    <>
      {/* Report Header */}
      <div
        data-pdf-section="header"
        style={{
          display: "flex",
          alignItems: "flex-start",
          justifyContent: "space-between",
          marginBottom: "24px",
          paddingBottom: "24px",
          borderBottom: "1px solid #f3f4f6",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
          <Image
            src={mbhsLogo}
            alt="MBHS"
            width={48}
            height={48}
            style={{ width: "48px", height: "48px", borderRadius: "8px" }}
          />
          <div>
            <h1 style={{ fontSize: "24px", fontWeight: 700, color: "#111827", margin: 0 }}>
              MBHS
            </h1>
            <p style={{ fontSize: "12px", color: "#9ca3af", margin: 0 }}>
              Multidimensional Behavioral Health Screen
            </p>
            <p style={{ fontSize: "14px", color: "#4b5563", marginTop: "4px" }}>
              {t("practitioner.report.selfScreeningReport")}
            </p>
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <p style={{ fontSize: "14px", color: "#6b7280", margin: 0 }}>
            {t("practitioner.report.date")}:{" "}
            {formatDate(reportData?.screening_date || reportData?.completed_at)}
          </p>
          <p style={{ fontSize: "14px", fontWeight: 500, color: "#374151", marginTop: "4px" }}>
            {clientNameProp || reportData?.client_name}
          </p>
          {(clientAgeProp != null || reportData?.client_age || reportData?.age) && (
            <p style={{ fontSize: "13px", color: "#6b7280", margin: 0 }}>
              {t("practitioner.report.age")}: {clientAgeProp ?? reportData?.client_age ?? reportData?.age}
            </p>
          )}
          <p style={{ fontSize: "12px", color: "#6b7280", margin: 0 }}>
            {reportData?.client_email || "-"}
          </p>
        </div>
      </div>

      {/* Your Results at a Glance */}
      <div data-pdf-section="results-glance" style={{ marginBottom: "32px" }}>
        <h2 style={{ fontSize: "20px", fontWeight: 700, color: "#111827", marginBottom: "12px" }}>
          {t("practitioner.report.resultsGlance")}
        </h2>
        <p style={{ fontSize: "14px", color: "#4b5563", marginBottom: "16px" }}>
          {t("practitioner.report.resultsDescription")}
        </p>
        <div style={{ backgroundColor: "#f9fafb", borderRadius: "12px", padding: "16px" }}>
          <p style={{ fontSize: "14px", color: "#374151", marginBottom: "8px" }}>
            <span style={{ fontWeight: 600 }}>{t("practitioner.report.percentile50")}</span> ={" "}
            {t("practitioner.report.averageRange")}
          </p>
          <p style={{ fontSize: "14px", color: "#374151", margin: 0 }}>
            <span style={{ fontWeight: 600 }}>{t("practitioner.report.percentile66")}</span> ={" "}
            {t("practitioner.report.warrantAttention")}
          </p>
        </div>
      </div>

      {/* Detailed Results by Scale */}
      <div data-pdf-section="detailed-results">
        <h2 style={{ fontSize: "20px", fontWeight: 700, color: "#111827", marginBottom: "24px" }}>
          {t("practitioner.report.detailedResults")}
        </h2>

        {scaleResults.length > 0 ? (
          <>
            {/* Scale Legend */}
            <div
              style={{
                display: "flex",
                alignItems: "flex-end",
                gap: "16px",
                marginBottom: "16px",
                fontSize: "12px",
                color: "#6b7280",
              }}
            >
              <div style={{ width: "180px", minWidth: "180px", flexShrink: 0 }} />
              <div style={{ flex: 1, position: "relative", height: "36px", fontSize: "14px" }}>
                <span style={{ position: "absolute", left: "50%", transform: "translateX(-50%)", textAlign: "center", lineHeight: 1.3, bottom: 0 }}>
                  <span style={{ display: "block" }}>{t("practitioner.report.averageScore")}</span>
                  <span style={{ display: "block" }}>({t("practitioner.report.percentile50")})</span>
                </span>
                <span style={{ position: "absolute", left: "83%", transform: "translateX(-50%)", textAlign: "center", lineHeight: 1.3, bottom: 0 }}>
                  <span style={{ display: "block" }}>{t("practitioner.report.clinicalThreshold")}</span>
                  <span style={{ display: "block" }}>({t("practitioner.report.percentile66")})</span>
                </span>
              </div>
            </div>

            {/* Scale Results */}
            <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
              {scaleResults.map((scale, index) => {
                const getBarColor = () => {
                  if (index < 2) return "#00B0F0"; // Light blue (somatization, cognitive_issues)
                  if (index < 6) return "#0070C0"; // Blue (demoralization, anhedonia, anxiety, suicidal_ideation)
                  return "#7030A0"; // Purple (activation, disconstraint, substance_use_problems)
                };
                return (
                  <div key={index} data-pdf-section={`scale-${scale.key}`} style={{ display: "flex", alignItems: "center", gap: "16px" }}>
                    <span
                      style={{
                        fontSize: "13px",
                        fontWeight: 600,
                        color: "#000000",
                        width: "180px",
                        minWidth: "180px",
                        flexShrink: 0,
                        lineHeight: 1.3,
                      }}
                    >
                      {scale.name}
                    </span>
                    <div style={{ flex: 1, position: "relative" }}>
                      <div
                        style={{
                          height: "28px",
                          backgroundColor: "#e5e7eb",
                          borderRadius: "4px",
                          position: "relative",
                          overflow: "hidden",
                        }}
                      >
                        <div
                          style={{
                            height: "100%",
                            backgroundColor: getBarColor(),
                            borderRadius: "4px",
                            width: `${scale.percentage}%`,
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "flex-end",
                            paddingRight: "8px",
                            minWidth: scale.percentage > 0 ? "40px" : "0",
                          }}
                        >
                          <span style={{ fontSize: "12px", fontWeight: 600, color: "#ffffff" }}>
                            {scale.percentage}%
                          </span>
                        </div>
                        {/* 50th percentile marker */}
                        <div
                          style={{
                            position: "absolute",
                            top: 0,
                            bottom: 0,
                            width: "1px",
                            backgroundColor: "#6b7280",
                            left: "50%",
                          }}
                        />
                        {/* 66th percentile marker */}
                        <div
                          style={{
                            position: "absolute",
                            top: 0,
                            bottom: 0,
                            width: "1px",
                            backgroundColor: "#374151",
                            left: "66%",
                          }}
                        />
                      </div>
                      <div
                        style={{
                          position: "relative",
                          display: "flex",
                          fontSize: "12px",
                          color: "#374151",
                          marginTop: "4px",
                        }}
                      >
                        <span style={{ position: "absolute", left: "50%", transform: "translateX(-50%)" }}>
                          50
                        </span>
                        <span style={{ position: "absolute", left: "66%", transform: "translateX(-50%)" }}>
                          66
                        </span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </>
        ) : (
          <div
            style={{
              textAlign: "center",
              padding: "32px 0",
              backgroundColor: "#f9fafb",
              borderRadius: "12px",
            }}
          >
            <p style={{ color: "#6b7280", margin: 0 }}>
              {t("practitioner.report.noScaleData")}
            </p>
          </div>
        )}
      </div>

      {/* Suicide Risk Classification */}
      <div
        data-pdf-section="suicide-risk"
        style={{
          backgroundColor: suicideRisk?.toLowerCase()?.includes("high") || suicideRisk?.toLowerCase()?.includes("moderate")
            ? "#fef2f2"
            : suicideRisk?.toLowerCase()?.includes("mild")
              ? "#fffbeb"
              : suicideRisk?.toLowerCase()?.includes("low")
                ? "#f0fdf4"
                : "#f9fafb",
          borderRadius: "12px",
          padding: "24px",
          marginTop: "32px",
          marginBottom: "32px",
        }}
      >
        <h2 style={{ fontSize: "16px", fontWeight: 700, color: "#111827", marginBottom: "12px" }}>
          {t("practitioner.report.suicideRiskClassification")}
        </h2>
        <span
          style={{
            display: "inline-block",
            padding: "8px 16px",
            backgroundColor: suicideRisk?.toLowerCase()?.includes("high") || suicideRisk?.toLowerCase()?.includes("moderate")
              ? "#FEE2E2"
              : suicideRisk?.toLowerCase()?.includes("mild")
                ? "#FEF9C3"
                : suicideRisk?.toLowerCase()?.includes("low")
                  ? "#DCFCE7"
                  : "#F3F4F6",
            color: suicideRisk?.toLowerCase()?.includes("high") || suicideRisk?.toLowerCase()?.includes("moderate")
              ? "#DC2626"
              : suicideRisk?.toLowerCase()?.includes("mild")
                ? "#CA8A04"
                : suicideRisk?.toLowerCase()?.includes("low")
                  ? "#16A34A"
                  : "#6b7280",
            fontSize: "14px",
            fontWeight: 600,
            borderRadius: "9999px",
            marginBottom: "12px",
          }}
        >
          {t("practitioner.report.suicideRiskLevel")}: {getRiskLabel(suicideRisk)}
        </span>
        <p style={{ fontSize: "14px", color: "#4b5563", lineHeight: 1.6, margin: 0 }}>
          {getSuicideRiskNarrative()}
        </p>
      </div>

      {/* Scale Interpretations */}
      {scaleResults.length > 0 && (
        <div data-pdf-section="interpretations-header" style={{ marginTop: "32px" }}>
          <h2 style={{ fontSize: "20px", fontWeight: 700, color: "#111827", marginBottom: "20px" }}>
            {t("practitioner.report.scaleInterpretations")}
          </h2>
          {PRACTITIONER_SCALE_GROUPS.map((group) => {
            const groupScales = group.scales
              .map((scaleName) => scaleResults.find((s) => s.key === scaleName))
              .filter(Boolean) as typeof scaleResults;
            if (groupScales.length === 0) return null;
            return (
              <div key={group.key} style={{ marginBottom: "24px" }}>
                <h3 style={{ fontSize: "16px", fontWeight: 600, color: "#1F2937", margin: "0 0 12px 0", paddingBottom: "4px", borderBottom: "1px solid #E5E7EB" }}>
                  {t(`practitioner.report.scaleGroups.${group.key}`)}
                </h3>
                <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                  {groupScales.map((scale) => {
                    const isElevated = scale.percentage >= 66;
                    const textKey = SCALE_INTERPRETATION_KEYS[scale.key];
                    const descKey = SCALE_DESCRIPTION_KEYS[scale.key];
                    const notElevatedKey = SCALE_NOT_ELEVATED_KEYS[scale.key];
                    return (
                      <div
                        key={scale.key}
                        data-pdf-section={`interpretation-${scale.key}`}
                        style={{
                          borderLeft: isElevated ? "4px solid #3B9EC9" : "none",
                          paddingLeft: "16px",
                        }}
                      >
                        <h4 style={{ fontSize: "14px", fontWeight: 700, color: "#111827", margin: "0 0 4px 0" }}>
                          {scale.name} - {isElevated ? t("practitioner.report.elevated") : t("practitioner.report.notElevated")}
                        </h4>
                        {descKey && (
                          <p style={{ fontSize: "13px", color: "#4b5563", lineHeight: 1.6, margin: "0 0 4px 0" }}>
                            {t(`practitioner.report.${descKey}`)}
                          </p>
                        )}
                        <p style={{ fontSize: "13px", lineHeight: 1.6, margin: 0, color: isElevated ? "#1F2937" : "#4b5563", fontWeight: isElevated ? 500 : 400 }}>
                          {isElevated
                            ? textKey && t(`practitioner.report.${textKey}`)
                            : notElevatedKey && t(`practitioner.report.${notElevatedKey}`)}
                        </p>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* SSI-Based Clinical Resources — hidden for first release, retain for future use */}
      {false && scaleResults.length > 0 && (
        <div data-pdf-section="ssi-resources" style={{ marginTop: "32px" }}>
          <h2 style={{ fontSize: "20px", fontWeight: 700, color: "#111827", marginBottom: "16px" }}>
            {t("practitioner.report.ssiResources")}
          </h2>
          <div style={{ backgroundColor: "#f9fafb", borderRadius: "12px", padding: "20px" }}>
            {/* Demoralization */}
            <div data-pdf-section="ssi-demoralization" style={{ marginBottom: "20px" }}>
              <h3 style={{ fontSize: "15px", fontWeight: 700, color: "#111827", marginBottom: "4px" }}>
                {t("practitioner.report.ssiDemoralizationTitle")}
              </h3>
              <p style={{ fontSize: "13px", color: "#4b5563", lineHeight: 1.6, margin: "0 0 8px 0" }}>
                {t("practitioner.report.ssiDemoralizationDescription")}
              </p>
              <button
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: "6px",
                  padding: "6px 14px",
                  fontSize: "13px",
                  fontWeight: 500,
                  color: "#374151",
                  backgroundColor: "#ffffff",
                  border: "1px solid #d1d5db",
                  borderRadius: "8px",
                  cursor: "pointer",
                }}
              >
                <svg style={{ width: "14px", height: "14px" }} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                </svg>
                {t("practitioner.report.viewSSIResource")}
              </button>
            </div>
            {/* Anhedonia */}
            <div data-pdf-section="ssi-anhedonia">
              <h3 style={{ fontSize: "15px", fontWeight: 700, color: "#111827", marginBottom: "4px" }}>
                {t("practitioner.report.ssiAnhedoniaTitle")}
              </h3>
              <p style={{ fontSize: "13px", color: "#4b5563", lineHeight: 1.6, margin: "0 0 8px 0" }}>
                {t("practitioner.report.ssiAnhedoniaDescription")}
              </p>
              <button
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: "6px",
                  padding: "6px 14px",
                  fontSize: "13px",
                  fontWeight: 500,
                  color: "#374151",
                  backgroundColor: "#ffffff",
                  border: "1px solid #d1d5db",
                  borderRadius: "8px",
                  cursor: "pointer",
                }}
              >
                <svg style={{ width: "14px", height: "14px" }} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                </svg>
                {t("practitioner.report.viewSSIResource")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Self-Directed Client Resources */}
      <div data-pdf-section="single-session" style={{ marginTop: "32px", backgroundColor: "#f9fafb", borderRadius: "12px", padding: "20px" }}>
        <h2 style={{ fontSize: "18px", fontWeight: 700, color: "#111827", marginBottom: "12px" }}>
          {t("practitioner.report.singleSessionTitle")}
        </h2>
        <p style={{ fontSize: "14px", color: "#4b5563", lineHeight: 1.6 }}>
          {t("practitioner.report.singleSessionDescPart1")}
          <a href="https://www.schleiderlab.org/" target="_blank" rel="noopener noreferrer" style={{ color: "#3B9EC9", textDecoration: "underline" }}>
            {t("practitioner.report.singleSessionLabLinkText")}
          </a>
          {t("practitioner.report.singleSessionDescPart2")}
          <a href="https://tryprojectyes.org/" target="_blank" rel="noopener noreferrer" style={{ color: "#3B9EC9", textDecoration: "underline" }}>
            {t("practitioner.report.singleSessionCoursesLinkText")}
          </a>
          {t("practitioner.report.singleSessionDescPart3")}
        </p>
      </div>

      {/* Important Information */}
      <div data-pdf-section="important-info" style={{ marginTop: "32px" }}>
        <h2 style={{ fontSize: "20px", fontWeight: 700, color: "#111827", marginBottom: "16px" }}>
          {t("practitioner.report.importantInformation")}
        </h2>
        <div style={{ backgroundColor: "#f9fafb", borderRadius: "12px", padding: "20px", border: "1px solid #e5e7eb" }}>
          <ul style={{ margin: 0, paddingLeft: "20px", listStyleType: "disc" }}>
            <li style={{ fontSize: "13px", color: "#4b5563", lineHeight: 1.6, marginBottom: "6px", display: "list-item" }}>{t("practitioner.report.noMedicalDiagnosis")}</li>
            <li style={{ fontSize: "13px", color: "#4b5563", lineHeight: 1.6, marginBottom: "6px", display: "list-item" }}>{t("practitioner.report.selfReportedResults")}</li>
            <li style={{ fontSize: "13px", color: "#4b5563", lineHeight: 1.6, marginBottom: "6px", display: "list-item" }}>{t("practitioner.report.qualifiedProfessional")}</li>
            <li style={{ fontSize: "13px", color: "#4b5563", lineHeight: 1.6, display: "list-item" }}>{t("practitioner.report.resultsChange")}</li>
          </ul>
        </div>
      </div>

      {/* Item-Level Report Card */}
      {_itemResponsesArr.length > 0 && (
        <div data-pdf-section="report-card" style={{ marginTop: "32px" }}>
          <ReportCard itemResponses={_itemResponsesArr} />
        </div>
      )}

      {/* Footer */}
      <div
        data-pdf-section="footer"
        style={{
          marginTop: "32px",
          paddingTop: "16px",
          borderTop: "1px solid #e5e7eb",
          textAlign: "center",
        }}
      >
        <p style={{ fontSize: "13px", fontWeight: 600, color: "#374151", margin: 0 }}>
          {t("practitioner.report.mbhsVersion")}
        </p>
        <p style={{ fontSize: "12px", color: "#9ca3af", marginTop: "4px" }}>
          {t("practitioner.report.copyright")}
        </p>
      </div>
    </>
  );

  if (autoDownload) {
    return (
      <div
        ref={reportRef}
        style={{ position: "absolute", left: "-9999px", top: 0, width: "800px", backgroundColor: "#ffffff", padding: "32px", pointerEvents: "none" }}
      >
        {!isLoading && reportData ? renderReportContent() : null}
      </div>
    );
  }

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="3xl">
      {isLoading ? (
        <div className="flex items-center justify-center py-16">
          <div className="text-center">
            <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-[#3B9EC9] mx-auto mb-4"></div>
            <p className="text-gray-600">{t("practitioner.common.loading")}</p>
          </div>
        </div>
      ) : !reportData ? (
        <div className="flex items-center justify-center py-16">
          <div className="text-center">
            <h2 className="text-xl font-semibold text-gray-900 mb-2">
              {t("practitioner.report.notFound")}
            </h2>
            <p className="text-gray-600">{t("practitioner.report.notFoundDescription")}</p>
          </div>
        </div>
      ) : (
        <div>
          {/* Download button */}
          <div className="flex justify-end mb-4">
            <button
              onClick={handleDownloadPDF}
              disabled={isDownloading}
              className="flex items-center gap-2 px-5 py-2 bg-[#3B9EC9] text-white rounded-full hover:bg-[#2D8AB5] transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer text-sm font-medium"
            >
              {isDownloading ? (
                <>
                  <svg
                    className="animate-spin w-4 h-4"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    />
                  </svg>
                  <span>{t("practitioner.report.downloading")}</span>
                </>
              ) : (
                <>
                  <span>{t("practitioner.report.downloadPDF")}</span>
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
                  </svg>
                </>
              )}
            </button>
          </div>

          {/* Report Content */}
          <div
            style={{
              borderRadius: "12px",
              border: "1px solid #e5e7eb",
            }}
          >
            <div
              ref={reportRef}
              style={{
                backgroundColor: "#ffffff",
                borderRadius: "12px",
                padding: "32px",
              }}
            >
              {renderReportContent()}
            </div>
          </div>
        </div>
      )}
    </Modal>
  );
}
