import { useEffect, useState } from "react";
import QRCode from "qrcode";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Copy, Download, QrCode, Check, Loader2 } from "lucide-react";
import { toast } from "sonner";

interface OrderQRCodeProps {
  orderId: string;
  courseTitle?: string;
  open: boolean;
  onClose: () => void;
}

export const OrderQRCode = ({ orderId, courseTitle, open, onClose }: OrderQRCodeProps) => {
  const [copied, setCopied] = useState(false);
  const [dataUrl, setDataUrl] = useState<string | null>(null);

  const onboardingUrl = `${window.location.origin}/onboarding?order_id=${orderId}`;

  // Generate the QR as a data-URL each time the dialog opens for this order.
  // Avoids canvas-ref timing issues with Radix's portal mounting.
  useEffect(() => {
    if (!open) {
      setDataUrl(null);
      return;
    }
    let cancelled = false;
    QRCode.toDataURL(onboardingUrl, {
      width: 280,
      margin: 2,
      color: { dark: '#1a1a2e', light: '#ffffff' },
    })
      .then((url) => {
        if (!cancelled) setDataUrl(url);
      })
      .catch((err) => {
        console.error('QR generation failed', err);
        if (!cancelled) setDataUrl(null);
      });
    return () => { cancelled = true; };
  }, [open, onboardingUrl]);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(onboardingUrl);
    setCopied(true);
    toast.success("Link copied to clipboard");
    setTimeout(() => setCopied(false), 2000);
  };

  const handleDownload = () => {
    if (!dataUrl) return;
    const link = document.createElement("a");
    link.download = `onboarding-qr-${orderId.slice(0, 8)}.png`;
    link.href = dataUrl;
    link.click();
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-sm">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <QrCode className="w-5 h-5 text-primary" />
            Delegate Onboarding QR
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {courseTitle && (
            <p className="text-sm text-muted-foreground text-center">{courseTitle}</p>
          )}

          <div className="flex items-center justify-center bg-white rounded-xl p-4 border border-border min-h-[312px]">
            {dataUrl ? (
              <img
                src={dataUrl}
                alt={`Onboarding QR for order ${orderId.slice(0, 8)}`}
                width={280}
                height={280}
              />
            ) : (
              <Loader2 className="w-8 h-8 text-muted-foreground animate-spin" />
            )}
          </div>

          <p className="text-xs text-muted-foreground text-center">
            Delegates scan this code to access their onboarding forms
          </p>

          <div className="bg-muted/50 rounded-lg px-3 py-2 text-xs font-mono text-muted-foreground break-all">
            {onboardingUrl}
          </div>

          <div className="flex gap-2">
            <Button variant="outline" className="flex-1" onClick={handleCopy}>
              {copied ? <Check className="w-4 h-4 mr-2 text-green-600" /> : <Copy className="w-4 h-4 mr-2" />}
              {copied ? "Copied!" : "Copy link"}
            </Button>
            <Button className="flex-1" onClick={handleDownload} disabled={!dataUrl}>
              <Download className="w-4 h-4 mr-2" />
              Download QR
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
