"use client";

import { useRef, useState } from "react";
import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import { Link } from "@/i18n/navigation";
import { useTranslations, useLocale } from "next-intl";
import { useRouter as useIntlRouter, usePathname } from "@/i18n/navigation";
import FlagIcon from "@/components/ui/FlagIcon";
import jsPDF from "jspdf";

interface ScaleResult {
  name: string;
  percentage: number;
  color: string;
}

export default function ReportPage() {
  const t = useTranslations();
  const locale = useLocale();
  const intlRouter = useIntlRouter();
  const pathname = usePathname();
  const reportRef = useRef<HTMLDivElement>(null);
  const [isDownloading, setIsDownloading] = useState(false);

  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-Report.pdf`);
    } catch (error) {
      console.error("Error generating PDF:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  const scaleResults: ScaleResult[] = [
    { name: "Somatization", percentage: 57, color: "bg-cyan-400" },
    { name: "Cognitive Issues", percentage: 70, color: "bg-cyan-400" },
    { name: "Depression", percentage: 45, color: "bg-cyan-400" },
    { name: "Anxiety", percentage: 62, color: "bg-cyan-400" },
    { name: "Sleep Issues", percentage: 38, color: "bg-cyan-400" },
    { name: "Substance Use", percentage: 25, color: "bg-cyan-400" },
  ];

  const DownloadIcon = () => (
    <svg className="w-5 h-5" 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>
  );

  const ArrowLeftIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
    </svg>
  );

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <div className="flex items-center gap-2">
              <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
              <span className="text-xl font-bold text-gray-900">MBHS</span>
            </div>

            {/* Navigation */}
            <nav className="hidden md:flex items-center gap-8">
              <Link href="/practitioner" className="text-sm font-medium text-gray-600 hover:text-gray-900">
                {t("practitioner.nav.dashboard")}
              </Link>
              <Link href="/practitioner/clients" className="text-sm font-medium text-gray-600 hover:text-gray-900">
                {t("practitioner.nav.clients")}
              </Link>
              <Link href="/practitioner/subscription" className="text-sm font-medium text-gray-600 hover:text-gray-900">
                {t("practitioner.nav.subscription")}
              </Link>
            </nav>

            {/* Right side */}
            <div className="flex items-center gap-4">
              {/* Language Toggle Button */}
              <button
                onClick={() => intlRouter.replace(pathname, { locale: locale === "en" ? "es" : "en" })}
                className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition"
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <span>{locale === "en" ? "EN" : "ES"}</span>
              </button>
              <button className="relative p-2 text-gray-400 hover:text-gray-600">
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
                </svg>
                <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
              </button>
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                  <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                  </svg>
                </div>
                <span className="text-sm font-medium text-gray-700">Oliver James</span>
                <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Top Bar */}
        <div className="flex items-center justify-between mb-6">
          <button
            onClick={() => intlRouter.push('/practitioner')}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-900 transition"
          >
            <ArrowLeftIcon />
            <span className="text-sm font-medium">{t("practitioner.report.backToDashboard")}</span>
          </button>
          <button
            onClick={handleDownloadPDF}
            disabled={isDownloading}
            className="flex items-center gap-2 px-6 py-2.5 bg-[#3B9EC9] text-white rounded-full hover:bg-[#2D8AB5] transition disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isDownloading ? (
              <>
                <svg className="animate-spin w-5 h-5" 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>
                <span className="text-sm font-medium">{t("practitioner.report.downloading")}</span>
              </>
            ) : (
              <>
                <span className="text-sm font-medium">{t("practitioner.report.downloadPDF")}</span>
                <DownloadIcon />
              </>
            )}
          </button>
        </div>

        {/* 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 pb-6 border-b border-gray-100">
            <div className="flex items-center gap-3">
              <Image src={mbhsLogo} alt="MBHS" width={48} height={48} className="w-12 h-12 rounded-lg" />
              <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("practitioner.report.selfScreeningReport")}</p>
              </div>
            </div>
            <p className="text-sm text-gray-500">{locale === "en" ? "Date" : "Fecha"}:15 Nov 2024</p>
          </div>

          {/* Your Results at a Glance */}
          <div className="mb-8">
            <h2 className="text-xl font-bold text-gray-900 mb-3">{t("practitioner.report.resultsGlance")}</h2>
            <p className="text-sm text-gray-600 mb-4">
              {t("practitioner.report.resultsDescription")}
            </p>
            <div className="bg-gray-50 rounded-xl p-4 space-y-2">
              <p className="text-sm text-gray-700">
                <span className="font-semibold">{t("practitioner.report.percentile50")}</span> = {t("practitioner.report.averageRange")}
              </p>
              <p className="text-sm text-gray-700">
                <span className="font-semibold">{t("practitioner.report.percentile66")}</span> = {t("practitioner.report.warrantAttention")}
              </p>
            </div>
          </div>

          {/* Detailed Results by Scale */}
          <div>
            <h2 className="text-xl font-bold text-gray-900 mb-6">{t("practitioner.report.detailedResults")}</h2>

            {/* Scale Legend */}
            <div className="flex items-center gap-4 mb-4 text-sm text-gray-500">
              <div className="w-20 sm:w-32"></div>
              <div className="flex-1 relative" style={{ height: "36px" }}>
                <span className="absolute text-center leading-tight" style={{ left: "50%", transform: "translateX(-50%)", bottom: 0, whiteSpace: "nowrap" }}>
                  {t("practitioner.report.averageScore")}<br />({t("practitioner.report.percentile50")})
                </span>
                <span className="absolute text-center leading-tight" style={{ left: "83%", transform: "translateX(-50%)", bottom: 0, whiteSpace: "nowrap" }}>
                  {t("practitioner.report.clinicalThreshold")}<br />(≥66th percentile)
                </span>
              </div>
            </div>

            {/* Scale Results */}
            <div className="space-y-4">
              {scaleResults.map((scale, 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={index}>
                    <div className="flex items-center gap-4">
                      <span className="text-sm font-medium text-gray-700 w-20 sm:w-32">{scale.name}</span>
                      <div className="flex-1 relative">
                        {/* Background track */}
                        <div className="h-7 bg-gray-200 rounded-sm relative overflow-hidden">
                          {/* Progress bar */}
                          <div
                            className={`h-full rounded-sm flex items-center justify-end pr-2 ${getBarColor()}`}
                            style={{ width: `${scale.percentage}%` }}
                          >
                            <span className="text-xs font-semibold text-white">{scale.percentage}%</span>
                          </div>
                          {/* 50th percentile marker */}
                          <div className="absolute top-0 bottom-0 w-px bg-gray-500" style={{ left: '50%' }}></div>
                          {/* 66th percentile marker */}
                          <div className="absolute top-0 bottom-0 w-px bg-gray-700" style={{ left: '66%' }}></div>
                        </div>
                        {/* Scale labels */}
                        <div className="relative flex 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 className="bg-green-50 rounded-xl p-6 mt-8">
            <h2 className="text-base font-bold text-gray-900 mb-3">{t("practitioner.report.suicideRiskClassification")}</h2>
            <span className="inline-block px-4 py-2 bg-green-500 text-white text-sm font-medium rounded-full mb-3">
              {t("practitioner.report.suicideRiskLevel")}: {t("practitioner.common.low")}
            </span>
            <p className="text-sm text-gray-600 leading-relaxed">
              {t("practitioner.report.suicideRiskNarrativeLow")}
            </p>
          </div>

          {/* Self-Directed Client Resources */}
          <div className="bg-gray-50 rounded-xl p-5 mt-8">
            <h2 className="text-lg font-bold text-gray-900 mb-3">{t("practitioner.report.singleSessionTitle")}</h2>
            <p className="text-sm text-gray-600 leading-relaxed">
              {t("practitioner.report.singleSessionDescPart1")}
              <a href="https://www.schleiderlab.org/" target="_blank" rel="noopener noreferrer" className="text-[#3B9EC9] underline">
                {t("practitioner.report.singleSessionLabLinkText")}
              </a>
              {t("practitioner.report.singleSessionDescPart2")}
              <a href="https://tryprojectyes.org/" target="_blank" rel="noopener noreferrer" className="text-[#3B9EC9] underline">
                {t("practitioner.report.singleSessionCoursesLinkText")}
              </a>
              {t("practitioner.report.singleSessionDescPart3")}
            </p>
          </div>

          {/* Important Information */}
          <div className="mt-8">
            <h2 className="text-xl font-bold text-gray-900 mb-4">{t("practitioner.report.importantInformation")}</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">
                <li className="text-[13px] text-gray-600 leading-relaxed">{t("practitioner.report.noMedicalDiagnosis")}</li>
                <li className="text-[13px] text-gray-600 leading-relaxed">{t("practitioner.report.selfReportedResults")}</li>
                <li className="text-[13px] text-gray-600 leading-relaxed">{t("practitioner.report.qualifiedProfessional")}</li>
                <li className="text-[13px] text-gray-600 leading-relaxed">{t("practitioner.report.resultsChange")}</li>
              </ul>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
