"use client";

import { useRef, useState } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations, useLocale } from "next-intl";
import jsPDF from "jspdf";

interface ScaleResult {
  name: string;
  percentile: number;
}

export default function Results() {
  const router = useRouter();
  const t = useTranslations("individual");
  const locale = useLocale();
  const reportRef = useRef<HTMLDivElement>(null);
  const [isDownloading, setIsDownloading] = useState(false);

  const mockResults: ScaleResult[] = [
    { name: t("scales.somatization"), percentile: 57 },
    { name: t("scales.cognitiveIssues"), percentile: 70 },
    { name: t("scales.demoralization"), percentile: 45 },
    { name: t("scales.anhedonia"), percentile: 62 },
    { name: t("scales.anxiety"), percentile: 38 },
    { name: t("scales.suicidalIdeation"), percentile: 52 },
    { name: t("scales.activation"), percentile: 68 },
    { name: t("scales.disconstraint"), percentile: 25 },
    { name: t("scales.substanceUseProblems"), percentile: 15 },
  ];

  const handleBackToDashboard = () => {
    router.push("/individual");
  };

  const handleDownloadPDF = async () => {
    if (!reportRef.current || isDownloading) return;

    setIsDownloading(true);
    try {
      // Dynamic import to avoid SSR issues
      const domtoimage = (await import("dom-to-image-more")).default;

      const scale = 2;
      const element = reportRef.current;

      const imgData = await domtoimage.toPng(element, {
        quality: 1,
        bgcolor: "#ffffff",
        width: element.offsetWidth * scale,
        height: element.offsetHeight * scale,
        style: {
          transform: `scale(${scale})`,
          transformOrigin: "top left",
        },
      });

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

      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = pdf.internal.pageSize.getHeight();
      const imgWidth = element.offsetWidth * scale;
      const imgHeight = element.offsetHeight * scale;
      const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
      const imgX = (pdfWidth - imgWidth * ratio) / 2;
      const imgY = 0;

      pdf.addImage(imgData, "PNG", imgX, imgY, imgWidth * ratio, imgHeight * ratio);
      pdf.save(`MBHS-Screening-Report.pdf`);
    } catch (error) {
      console.error("Error generating PDF:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  const getRiskLevel = () => {
    const maxPercentile = Math.max(...mockResults.map((r) => r.percentile));
    if (maxPercentile >= 80) return { level: t("results.riskHigh"), color: "bg-red-500" };
    if (maxPercentile >= 66) return { level: t("results.riskModerate"), color: "bg-yellow-500" };
    if (maxPercentile >= 50) return { level: t("results.riskMild"), color: "bg-amber-500" };
    return { level: t("results.riskLow"), color: "bg-green-500" };
  };

  const riskInfo = getRiskLevel();

  return (
    <main className="pt-20 pb-8">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Top Navigation */}
          <div className="flex items-center justify-between mb-6">
            <button
              onClick={handleBackToDashboard}
              className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 transition cursor-pointer"
            >
              <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("results.backToDashboard")}
            </button>
            <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"
                    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"></circle>
                    <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"></path>
                  </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>

          {/* Main Report Card */}
          <div ref={reportRef} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
            {/* Report Header */}
            <div className="flex items-start justify-between mb-6">
              <div className="flex items-center gap-3">
                <svg
                  className="w-12 h-12"
                  viewBox="0 0 40 40"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <rect width="40" height="40" rx="8" fill="#3B9EC9" />
                  <rect x="8" y="10" width="24" height="4" rx="2" fill="white" />
                  <rect x="8" y="18" width="18" height="4" rx="2" fill="white" />
                  <rect x="8" y="26" width="24" height="4" rx="2" fill="white" />
                </svg>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">MBHS</h1>
                  <p className="text-xs text-gray-500">
                    Multidimensional Behavioral Health Screen
                  </p>
                </div>
              </div>
              <p className="text-sm text-gray-600">
                Date:{new Date().toLocaleDateString(locale === "es" ? "es-ES" : "en-GB", {
                  day: "numeric",
                  month: "short",
                  year: "numeric",
                })}
              </p>
            </div>

            <p className="text-sm text-gray-600 mb-6">
              {t("results.reportTitle")}
            </p>

            <div className="border-t border-gray-200 mb-8"></div>

            {/* Suicide Risk Classification */}
            <div className="bg-green-50 rounded-xl p-6 mb-8">
              <h2 className="text-sm font-bold text-gray-900 uppercase tracking-wide mb-3">
                {t("results.suicideRiskTitle")}
              </h2>
              <span
                className={`inline-block px-4 py-2 text-sm font-medium text-white ${riskInfo.color} rounded-full mb-3`}
              >
                {t("results.riskLevel")} {riskInfo.level}
              </span>
              <p className="text-sm text-gray-700">
                {t("results.riskDisclaimer")}
              </p>
            </div>

            {/* Your Results at a Glance */}
            <div 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-gray-50 rounded-xl p-4">
                <p className="text-sm text-gray-700 mb-1">
                  <span className="font-semibold">{t("results.percentile50")}</span> = {t("results.averageRange")}
                </p>
                <p className="text-sm text-gray-700">
                  <span className="font-semibold">{t("results.percentile66")}</span>{" "}
                  = {t("results.warrantAttention")}
                </p>
              </div>
            </div>

            {/* Detailed Results by Scale */}
            <div>
              <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: "32px" }}>
                    <span
                      className="absolute text-center leading-tight"
                      style={{ left: "50%", transform: "translateX(-50%)", bottom: 0 }}
                    >
                      {t("results.averageScore")}
                      <br />
                      ({t("results.percentile50")})
                    </span>
                    <span
                      className="absolute text-center leading-tight"
                      style={{ left: "83%", transform: "translateX(-50%)", bottom: 0 }}
                    >
                      {t("results.clinicalThreshold")}
                      <br />
                      ({t("results.percentile66")})
                    </span>
                  </div>
                </div>

                {/* Scale Bars */}
                <div className="space-y-4">
                  {mockResults.map((result, index) => {
                    // Color based on row position: first 3 light blue, middle 3 blue, last 3 purple
                    const getBarColor = () => {
                      if (index < 2) return "bg-[#00B0F0]"; // Light blue/cyan
                      if (index < 6) return "bg-[#0070C0]"; // Blue
                      return "bg-[#7030A0]"; // Purple
                    };
                    return (
                      <div key={result.name} className="flex items-center">
                        <div className="w-40 text-sm font-medium text-gray-700 pr-4">
                          {result.name}
                        </div>
                        <div className="flex-1 relative">
                          {/* Background bar */}
                          <div className="h-7 bg-gray-200 rounded-sm relative overflow-hidden">
                            {/* Filled bar */}
                            <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">
                                {result.percentile}%
                              </span>
                            </div>
                            {/* 50th percentile marker */}
                            <div
                              className="absolute top-0 bottom-0 w-px bg-gray-500"
                              style={{ left: "50%" }}
                            />
                            {/* 66th percentile marker */}
                            <div
                              className="absolute top-0 bottom-0 w-px bg-gray-700"
                              style={{ left: "66%" }}
                            />
                          </div>
                          {/* Scale labels */}
                          <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>
          </div>
        </div>
    </main>
  );
}
