"use client";

import { useRef, useCallback } from "react";
import { QRCodeSVG } from "qrcode.react";
import { CheckCircle2, Download, ArrowLeft } from "lucide-react";
import Link from "next/link";

interface SuccessViewProps {
  patientId: string;
}

export default function SuccessView({ patientId }: SuccessViewProps) {
  const qrRef = useRef<SVGSVGElement>(null);

  const handleDownload = useCallback(() => {
    const svg = qrRef.current;
    if (!svg) return;

    const serializer = new XMLSerializer();
    const svgString = serializer.serializeToString(svg);
    const svgBlob = new Blob([svgString], {
      type: "image/svg+xml;charset=utf-8",
    });
    const url = URL.createObjectURL(svgBlob);

    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement("canvas");
      const size = 1024;
      canvas.width = size;
      canvas.height = size;
      const ctx = canvas.getContext("2d");
      if (!ctx) return;

      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, size, size);
      ctx.drawImage(img, 0, 0, size, size);
      URL.revokeObjectURL(url);

      const pngUrl = canvas.toDataURL("image/png");
      const link = document.createElement("a");
      link.href = pngUrl;
      link.download = `patient-${patientId}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };
    img.src = url;
  }, [patientId]);

  const qrValue = `${typeof window !== "undefined" ? window.location.origin : ""}/patient/${patientId}`;

  return (
    <div className="flex flex-col items-center text-center">
      <div className="mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-900/30">
        <CheckCircle2 className="h-8 w-8 text-emerald-400" />
      </div>

      <h2 className="text-xl font-bold text-zinc-100">
        Patient Created Successfully!
      </h2>
      <p className="mt-2 max-w-md text-sm text-zinc-400">
        The patient has been registered. Share or print the QR code below so
        caregivers and medical staff can quickly access the patient profile.
      </p>

      <div className="mt-8 rounded-xl border border-zinc-800 bg-zinc-900 p-6">
        <div className="rounded-lg border border-zinc-800 bg-white p-3">
          <QRCodeSVG
            ref={qrRef}
            value={qrValue}
            size={200}
            level="H"
            includeMargin
          />
        </div>
      </div>

      <div className="mt-6 flex flex-col gap-3 sm:flex-row">
        <button
          type="button"
          onClick={handleDownload}
          className="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-indigo-500"
        >
          <Download className="h-4 w-4" />
          Download QR Code
        </button>
        <Link
          href="/dashboard"
          className="inline-flex items-center gap-2 rounded-lg bg-zinc-800 px-5 py-2.5 text-sm font-medium text-zinc-200 transition-colors hover:bg-zinc-700"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to Dashboard
        </Link>
      </div>
    </div>
  );
}

