"use client";

import { useEffect, useState } from "react";
import QRCode from "qrcode";
import { Check, Copy, Download, X } from "lucide-react";

/*
  O QR code do link do cupom, para imprimir no balcão, na sacola ou no
  cartão de visita. Quem aponta a câmera chega na loja com o cupom guardado
  no carrinho. Gerado aqui mesmo, no navegador (biblioteca qrcode).
*/

export function QrDoCupom({ codigo, link, aoFechar }: { codigo: string | null; link: string; aoFechar: () => void }) {
  const [imagem, setImagem] = useState("");
  const [copiado, setCopiado] = useState(false);

  useEffect(() => {
    if (!codigo) return;
    let vivo = true;
    setImagem("");
    QRCode.toDataURL(link, { width: 720, margin: 1, errorCorrectionLevel: "M", color: { dark: "#1a1a2b", light: "#ffffff" } })
      .then((url) => {
        if (vivo) setImagem(url);
      })
      .catch(() => undefined);
    const aoTeclar = (e: KeyboardEvent) => {
      if (e.key === "Escape") aoFechar();
    };
    window.addEventListener("keydown", aoTeclar);
    return () => {
      vivo = false;
      window.removeEventListener("keydown", aoTeclar);
    };
  }, [codigo, link, aoFechar]);

  if (!codigo) return null;

  const copiar = async () => {
    try {
      await navigator.clipboard.writeText(link);
      setCopiado(true);
      window.setTimeout(() => setCopiado(false), 1600);
    } catch {
      /* Sem área de transferência: o link está à vista para copiar à mão. */
    }
  };

  return (
    <div role="dialog" aria-modal="true" aria-label={`QR code do cupom ${codigo}`} onClick={aoFechar} className="fixed inset-0 z-[140] flex items-center justify-center bg-[rgba(12,8,24,0.42)] p-4 backdrop-blur-[2px]">
      <div onClick={(e) => e.stopPropagation()} className="w-[min(380px,100%)] rounded-[22px] bg-white p-5 shadow-[0_24px_60px_rgba(26,26,43,0.28)]">
        <div className="flex items-start justify-between gap-3">
          <div>
            <p className="text-[11px] font-bold uppercase tracking-[0.14em] text-[var(--ks-color-text-soft)]">QR code do cupom</p>
            <p className="font-mono text-lg font-black tracking-[0.1em] text-[var(--ks-brand-600)]">{codigo}</p>
          </div>
          <button type="button" onClick={aoFechar} className="ks-icon-button" aria-label="Fechar">
            <X size={18} />
          </button>
        </div>
        <div className="mt-4 flex aspect-square items-center justify-center rounded-2xl bg-[var(--ks-color-bg-inset)] p-4">
          {imagem ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={imagem} alt={`QR code que abre a loja com o cupom ${codigo}`} className="h-full w-full rounded-xl" />
          ) : (
            <span className="text-sm text-[var(--ks-color-text-muted)]">Gerando...</span>
          )}
        </div>
        <p className="mt-3 break-all text-center font-mono text-[11px] text-[var(--ks-color-text-muted)]">{link}</p>
        <div className="mt-4 grid grid-cols-2 gap-2">
          <button type="button" onClick={copiar} className="ks-button ks-button-secondary">
            {copiado ? <Check size={15} /> : <Copy size={15} />} {copiado ? "Copiado" : "Copiar link"}
          </button>
          <a href={imagem || undefined} download={`cupom-${codigo.toLowerCase()}.png`} aria-disabled={!imagem} className="ks-button ks-button-primary">
            <Download size={15} /> Baixar
          </a>
        </div>
      </div>
    </div>
  );
}
