"use client";

import { useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useTranslations } from "next-intl";
import jsPDF from "jspdf";
import { toast } from "react-hot-toast";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import {
  JANE_DOE_CLIENT,
  JANE_DOE_RESULTS,
  JANE_DOE_SUICIDE_RISK,
} from "@/lib/sampleReportData";

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

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

const 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 SampleIndividualReportPage() {
  const t = useTranslations("individual");
  const reportRef = useRef<HTMLDivElement>(null);
  const [isDownloading, setIsDownloading] = useState(false);

  const results = JANE_DOE_RESULTS;
  const suicideRisk = JANE_DOE_SUICIDE_RISK;

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

  const getRiskInfo = () => {
    const normalized = suicideRisk.toLowerCase();
    if (normalized.includes("at least moderate") || normalized.includes("high") || normalized.includes("moderate"))
      return { level: t("results.riskHigh"), bgColor: "bg-red-50", badgeColor: "bg-red-100 text-red-600" };
    if (normalized.includes("mild"))
      return { level: t("results.riskMild"), bgColor: "bg-yellow-50", badgeColor: "bg-yellow-100 text-yellow-600" };
    return { level: t("results.riskLow"), bgColor: "bg-green-50", badgeColor: "bg-green-100 text-green-600" };
  };

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

  const riskInfo = getRiskInfo();

  const handleDownloadPDF = async () => {
    if (!reportRef.current || isDownloading) return;
    setIsDownloading(true);
    try {
      const html2canvas = (await import("html2canvas-pro")).default;
      const canvasScale = 2;
      const element = reportRef.current;

      const canvas = await html2canvas(element, {
        scale: canvasScale,
        useCORS: true,
        allowTaint: true,
        backgroundColor: "#ffffff",
        logging: false,
      });

      const pdfWidth = 210;
      const pdfHeight = 297;
      const margin = 10;
      const availableWidth = pdfWidth - margin * 2;
      const availableHeight = pdfHeight - margin * 2;
      const imgWidthPx = canvas.width;
      const imgHeightPx = canvas.height;
      const ratio = availableWidth / imgWidthPx;
      const pageHeightPx = availableHeight / ratio;

      const sectionElements = element.querySelectorAll("[data-pdf-section]");
      const elementRect = element.getBoundingClientRect();
      const breakPoints: number[] = [];
      sectionElements.forEach((el) => {
        const rect = el.getBoundingClientRect();
        const yPx = Math.round((rect.top - elementRect.top) * canvasScale);
        if (yPx > 0 && yPx < imgHeightPx) breakPoints.push(yPx);
      });

      const uniqueBreakPoints = [...new Set(breakPoints)].sort((a, b) => a - b);
      const pages: { startY: number; endY: number }[] = [];
      let currentY = 0;

      while (currentY < imgHeightPx) {
        const idealEnd = currentY + pageHeightPx;
        if (idealEnd >= imgHeightPx) {
          pages.push({ startY: currentY, endY: imgHeightPx });
          break;
        }
        let bestBreak = -1;
        for (const bp of uniqueBreakPoints) {
          if (bp <= currentY) continue;
          if (bp <= idealEnd) bestBreak = bp;
          else break;
        }
        if (bestBreak > currentY) {
          pages.push({ startY: currentY, endY: bestBreak });
          currentY = bestBreak;
        } else {
          pages.push({ startY: currentY, endY: Math.min(idealEnd, imgHeightPx) });
          currentY = Math.min(idealEnd, imgHeightPx);
        }
      }

      if (pages.length === 0) pages.push({ startY: 0, endY: imgHeightPx });

      const pdf = new jsPDF({ orientation: "portrait", unit: "mm", format: "a4", compress: true });

      for (let i = 0; i < pages.length; i++) {
        if (i > 0) pdf.addPage();
        const { startY, endY } = pages[i];
        const sliceH = endY - startY;
        if (sliceH <= 0) continue;
        const sliceCanvas = document.createElement("canvas");
        sliceCanvas.width = imgWidthPx;
        sliceCanvas.height = Math.ceil(sliceH);
        const ctx = sliceCanvas.getContext("2d");
        if (!ctx) continue;
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, sliceCanvas.width, sliceCanvas.height);
        ctx.drawImage(canvas, 0, startY, imgWidthPx, sliceH, 0, 0, imgWidthPx, Math.ceil(sliceH));
        pdf.addImage(
          sliceCanvas.toDataURL("image/png"),
          "PNG",
          margin,
          margin,
          availableWidth,
          sliceH * ratio,
          undefined,
          "FAST"
        );
      }

      pdf.save("MBHS-SampleReport-Individual.pdf");
    } catch (error) {
      console.error("Error generating PDF:", error);
      toast.error("Failed to generate PDF. Please try again.");
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <main className="min-h-screen bg-gray-50 pb-8">
      {/* Sample Banner */}
      <div className="bg-amber-50 border-b border-amber-200 px-4 py-3 text-center">
        <p className="text-sm font-medium text-amber-800">
          {t("sample.bannerText")}{" "}
          <Link href="/signup" className="underline hover:text-amber-900">
            {t("sample.createAccount")}
          </Link>{" "}
          {t("sample.bannerSuffix")}
        </p>
      </div>

      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 pt-6">
        {/* Top Navigation */}
        <div className="flex items-center justify-between mb-6">
          <Link
            href="/"
            className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 transition"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
            </svg>
            {t("sample.backToMBHS")}
          </Link>
          <button
            onClick={handleDownloadPDF}
            disabled={isDownloading}
            className="flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            {isDownloading ? (
              <>
                <svg className="animate-spin w-4 h-4" 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>
                {t("downloading")}
              </>
            ) : (
              <>
                {t("results.downloadPDF")}
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
              </>
            )}
          </button>
        </div>

        {/* Report Card */}
        <div className="bg-white rounded-xl border border-gray-200">
          <div ref={reportRef} className="bg-white rounded-xl p-8 w-full">
            {/* Report Header */}
            <div data-pdf-section="header" className="flex items-start justify-between mb-6 pb-6 border-b border-gray-100">
              <div className="flex items-center gap-3">
                <Image
                  src={mbhsLogo}
                  alt="MBHS"
                  width={48}
                  height={48}
                  className="rounded-lg w-12 h-12"
                />
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">MBHS</h1>
                  <p className="text-xs text-gray-400">Multidimensional Behavioral Health Screen</p>
                  <p className="text-sm text-gray-600 mt-1">{t("results.reportTitle")}</p>
                </div>
              </div>
              <div className="text-right">
                <p className="text-sm text-gray-500">{t("results.date")} {formatDate(JANE_DOE_CLIENT.screening_date)}</p>
                <p className="text-sm font-medium text-gray-700 mt-1">{JANE_DOE_CLIENT.name}</p>
                <p className="text-xs text-gray-500">{JANE_DOE_CLIENT.email}</p>
              </div>
            </div>

            {/* Results at a Glance */}
            <div data-pdf-section="results-glance" className="mb-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-3">{t("results.resultsGlance")}</h2>
              <p className="text-sm text-gray-600 mb-4">{t("results.resultsDescription")}</p>
              <div className="bg-slate-50 rounded-xl p-4">
                <p className="text-sm text-gray-600 mb-1">
                  <span className="font-semibold text-slate-700">{t("results.percentile50")}</span> ={" "}
                  {t("results.averageRange")}
                </p>
                <p className="text-sm text-gray-600">
                  <span className="font-semibold text-slate-700">{t("results.percentile66")}</span>{" "}
                  = {t("results.warrantAttention")}
                </p>
              </div>
            </div>

            {/* Detailed Results by Scale */}
            <div data-pdf-section="detailed-results">
              <h2 className="text-xl font-semibold text-gray-900 mb-4">{t("results.detailedResults")}</h2>
              <div className="bg-gray-50 rounded-xl p-6">
                {/* Scale Headers */}
                <div className="flex items-center mb-6">
                  <div className="w-40"></div>
                  <div className="flex-1 relative text-xs text-gray-500" style={{ height: "36px" }}>
                    <span
                      className="absolute text-center leading-tight"
                      style={{ left: "50%", transform: "translateX(-50%)", bottom: 0, whiteSpace: "nowrap" }}
                    >
                      {t("results.averageScore")}
                      <br />
                      ({t("results.percentile50")})
                    </span>
                    <span
                      className="absolute text-center leading-tight"
                      style={{ left: "83%", transform: "translateX(-50%)", bottom: 0, whiteSpace: "nowrap" }}
                    >
                      {t("results.clinicalThreshold")}
                      <br />
                      ({t("results.percentile66")})
                    </span>
                  </div>
                </div>

                {/* Scale Bars */}
                <div className="space-y-4">
                  {results.map((result, index) => {
                    const getBarColor = () => {
                      if (index < 2) return "bg-[#00B0F0]";
                      if (index < 6) return "bg-[#0070C0]";
                      return "bg-[#7030A0]";
                    };
                    const scaleName = t(scaleNameMap[result.scale_name] || result.scale_name);
                    return (
                      <div
                        key={result.scale_name}
                        data-pdf-section={`scale-${result.scale_name}`}
                        className="flex items-center"
                      >
                        <div className="w-40 text-sm font-medium text-gray-700 pr-4">{scaleName}</div>
                        <div className="flex-1 relative">
                          <div className="h-7 bg-gray-200 rounded-sm relative overflow-hidden">
                            <div
                              className={`absolute left-0 top-0 h-full rounded-sm flex items-center justify-end pr-2 ${getBarColor()}`}
                              style={{ width: `${result.percentile}%` }}
                            >
                              <span className="text-xs font-semibold text-white">
                                {Math.round(result.percentile)}%
                              </span>
                            </div>
                            <div className="absolute top-0 bottom-0 w-px bg-gray-500" style={{ left: "50%" }} />
                            <div className="absolute top-0 bottom-0 w-px bg-gray-700" style={{ left: "66%" }} />
                          </div>
                          <div className="relative text-xs text-gray-400 mt-1">
                            <span
                              className="absolute"
                              style={{ left: "50%", transform: "translateX(-50%)" }}
                            >
                              50
                            </span>
                            <span
                              className="absolute"
                              style={{ left: "66%", transform: "translateX(-50%)" }}
                            >
                              66
                            </span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>

            {/* Suicide Risk Classification */}
            <div data-pdf-section="suicide-risk" className={`rounded-xl p-6 mt-8 ${riskInfo.bgColor}`}>
              <h2 className="text-sm font-bold text-gray-900 uppercase tracking-wide mb-3">
                {t("results.suicideRiskTitle")}
              </h2>
              <span
                className={`inline-flex items-center justify-center h-9 px-4 text-sm font-semibold ${riskInfo.badgeColor} rounded-full mb-3`}
              >
                {t("results.riskCategory")} {riskInfo.level}
              </span>
              <p className="text-sm text-gray-700">{getSuicideRiskNarrative()}</p>
            </div>

            {/* Scale Interpretations */}
            <div data-pdf-section="interpretations-header" className="mt-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-4">{t("results.interpretationsTitle")}</h2>
              {SCALE_GROUPS.map((group) => {
                const groupResults = group.scales
                  .map((s) => results.find((r) => r.scale_name === s))
                  .filter(Boolean) as typeof results;
                if (groupResults.length === 0) return null;
                return (
                  <div key={group.key} className="mb-6">
                    <h3 className="text-base font-semibold text-gray-800 mb-3 border-b border-gray-200 pb-1">
                      {t(`results.scaleGroups.${group.key}`)}
                    </h3>
                    <div className="space-y-5">
                      {groupResults.map((result) => {
                        const scaleName = t(scaleNameMap[result.scale_name] || result.scale_name);
                        const interpKey = interpretationKeyMap[result.scale_name] || result.scale_name;
                        const isElevated = result.percentile >= 66;
                        return (
                          <div
                            key={result.scale_name}
                            data-pdf-section={`interpretation-${result.scale_name}`}
                            className={isElevated ? "border-l-4 border-[#3B9EC9] pl-4" : "pl-4"}
                          >
                            <h4 className="text-sm font-bold text-gray-900 mb-1">
                              {scaleName} -{" "}
                              {isElevated ? t("results.elevated") : t("results.notElevated")}
                            </h4>
                            <p className="text-sm text-gray-600 leading-relaxed mb-1">
                              {t(`results.interpretations.${interpKey}Description`)}
                            </p>
                            <p
                              className={`text-sm leading-relaxed ${
                                isElevated ? "text-gray-800 font-medium" : "text-gray-600"
                              }`}
                            >
                              {isElevated
                                ? t(`results.interpretations.${interpKey}`)
                                : t(`results.interpretations.${interpKey}NotElevated`)}
                            </p>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Recommended Next Steps — shown only when suicide risk is elevated (not Low) */}
            {!suicideRisk.toLowerCase().includes("low") && (
            <div data-pdf-section="next-steps" className="mt-8 bg-sky-50 border-2 border-[#3B9EC9] rounded-xl p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-3">{t("results.nextSteps.title")}</h2>
              <p className="text-sm text-gray-600 mb-4">{t("results.nextSteps.intro")}</p>
              <ul className="list-disc pl-5 flex flex-col gap-1.5">
                {([1, 2, 3] as const).map((n) => (
                  <li key={n} className="text-[13px] text-gray-700 leading-relaxed">
                    {t(`results.nextSteps.bullet${n}`)}
                  </li>
                ))}
              </ul>
            </div>
            )}

            {/* Single-Session Support */}
            <div data-pdf-section="single-session" className="mt-8 bg-gray-50 rounded-xl p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-3">{t("results.singleSession.title")}</h2>
              <p className="text-sm text-gray-600 mb-4">{t("results.singleSession.description")}</p>
              <a
                href="https://www.tryprojectyes.org"
                target="_blank"
                rel="noopener noreferrer"
                data-html2canvas-ignore="true"
                className="inline-block px-6 py-2.5 text-sm font-medium text-[#3B9EC9] border-2 border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 transition cursor-pointer"
              >
                {t("results.singleSession.consultNow")}
              </a>
            </div>

            {/* Important Information */}
            <div data-pdf-section="important-info" className="mt-8">
              <h2 className="text-xl font-bold text-gray-900 mb-4">{t("results.importantInfo.title")}</h2>
              <div className="bg-gray-50 rounded-xl p-5 border border-gray-200">
                <ul className="list-disc pl-5 flex flex-col gap-1.5">
                  {([1, 2, 3, 4] as const).map((n) => (
                    <li key={n} className="text-[13px] text-gray-600 leading-relaxed">
                      {t(`results.importantInfo.bullet${n}`)}
                    </li>
                  ))}
                </ul>
              </div>
            </div>

            {/* Footer */}
            <div data-pdf-section="footer" className="mt-10 pt-6 border-t border-gray-200 text-center">
              <p className="text-sm font-medium text-gray-700">{t("results.footer.version")}</p>
              <p className="text-xs text-gray-500 mt-1">{t("results.footer.copyright")}</p>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}
