"use client";

import { useState } from "react";
import Link from "next/link";
import { Pencil, Trash2, QrCode, X } from "lucide-react";
import { deletePatient } from "@/app/actions/patient";

interface PatientActionsProps {
  patientId: string;
  qrCodeUrl?: string | null;
}

export default function PatientActions({
  patientId,
  qrCodeUrl,
}: PatientActionsProps) {
  const [showQr, setShowQr] = useState(false);

  async function handleRemove() {
    if (!confirm("Are you sure you want to remove this patient?")) return;
    const result = await deletePatient(patientId);
    if (result.success) {
      window.location.reload();
    } else {
      alert(result.error || "Failed to remove patient");
    }
  }

  return (
    <>
      <div className="flex items-center gap-2">
        <Link
          href={`/dashboard/family/edit-patient/${patientId}`}
          className="rounded-md bg-zinc-800 p-2 text-zinc-300 transition-colors hover:bg-zinc-700 hover:text-white"
          title="Edit"
        >
          <Pencil className="h-4 w-4" />
        </Link>
        <button
          onClick={handleRemove}
          className="rounded-md bg-zinc-800 p-2 text-zinc-300 transition-colors hover:bg-red-900/30 hover:text-red-400"
          title="Remove"
        >
          <Trash2 className="h-4 w-4" />
        </button>
        <button
          onClick={() => setShowQr(true)}
          className="rounded-md bg-zinc-800 p-2 text-zinc-300 transition-colors hover:bg-zinc-700 hover:text-white"
          title="View QR"
        >
          <QrCode className="h-4 w-4" />
        </button>
      </div>

      {showQr && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
          onClick={() => setShowQr(false)}
        >
          <div
            className="relative w-full max-w-sm rounded-xl border border-zinc-800 bg-zinc-900 p-6"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={() => setShowQr(false)}
              className="absolute right-3 top-3 rounded-md p-1 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100"
              aria-label="Close QR modal"
            >
              <X className="h-5 w-5" />
            </button>
            <h3 className="mb-4 text-lg font-semibold text-zinc-100">
              Patient QR Code
            </h3>
            {qrCodeUrl ? (
              <img
                src={qrCodeUrl}
                alt="Patient QR Code"
                className="mx-auto h-48 w-48 rounded-lg border border-zinc-800"
              />
            ) : (
              <div className="flex h-48 w-48 items-center justify-center rounded-lg border border-zinc-800 bg-zinc-950 text-sm text-zinc-500">
                No QR code available
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
}

