import { QrCode, Download, ExternalLink } from "lucide-react";
import { Button } from "@/components/ui/button";

export default function QRCodeDisplay({ sppgId, sppgNama }) {
  const publicUrl = `${window.location.origin}/detail-sppg/${sppgId}`;
  const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${encodeURIComponent(publicUrl)}&margin=10&color=1a3a5c`;

  const handleDownload = () => {
    const a = document.createElement("a");
    a.href = qrUrl;
    a.download = `QR-SPPG-${sppgNama}.png`;
    a.target = "_blank";
    a.click();
  };

  return (
    <div className="bg-card rounded-xl border border-border p-5 sm:p-6">
      <div className="flex items-center gap-2 mb-4">
        <QrCode className="w-5 h-5 text-primary" />
        <h3 className="font-bold text-foreground">QR Code Transparansi</h3>
      </div>

      <div className="flex flex-col sm:flex-row items-center gap-5">
        <div className="bg-white p-3 rounded-xl border-2 border-primary/20 shadow-sm">
          <img src={qrUrl} alt={`QR ${sppgNama}`} className="w-40 h-40" />
        </div>
        <div className="flex-1 text-center sm:text-left space-y-3">
          <p className="text-sm font-semibold text-foreground">{sppgNama}</p>
          <p className="text-xs text-muted-foreground leading-relaxed">
            Scan QR code ini untuk mengakses data publik SPPG secara transparan. Bisa dipasang di papan informasi sekolah.
          </p>
          <div className="bg-muted/50 rounded-lg px-3 py-2">
            <p className="text-xs font-mono text-muted-foreground break-all">{publicUrl}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button size="sm" className="rounded-full text-xs" onClick={handleDownload}>
              <Download className="w-3.5 h-3.5 mr-1" />
              Unduh QR
            </Button>
            <Button size="sm" variant="outline" className="rounded-full text-xs" onClick={() => window.open(publicUrl, "_blank")}>
              <ExternalLink className="w-3.5 h-3.5 mr-1" />
              Buka Link
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}