"use client";

import React from "react";
import styles from "../../commonstyle/FormStyles.module.css";
import type { CertificateRow } from "@/lib/api/types/certificate.types";

interface Props {
  row: CertificateRow | null;
  onClose: () => void;
}

export default function CertificateQRModal({ row, onClose }: Props) {
  if (!row) return null;

  // Try multiple possible field names for the QR code
  const qrCode =
    (row as any).qr_code ||
    (row as any).qrCode ||
    (row as any).qr_code_data ||
    (row as any).qr_image ||
    null;

  // Try multiple possible field names for the verification URL
  const verificationUrl =
    (row as any).verification_url ||
    (row as any).verificationUrl ||
    (row as any).verify_url ||
    `https://qrsyst.com/verify-certificate?cert=${row.certificate_no}`;

  const downloadQR = () => {
    if (!qrCode) return;

    const link = document.createElement("a");
    link.href = qrCode;
    link.download = `${row.certificate_no}-qr.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const copyVerificationUrl = async () => {
    try {
      await navigator.clipboard.writeText(verificationUrl);
      // Toast feedback
      const toast = (await import("react-hot-toast")).default;
      toast.success("✅ Verification URL copied!");
    } catch (err) {
      const toast = (await import("react-hot-toast")).default;
      toast.error("Failed to copy URL");
    }
  };

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        style={{ maxWidth: 540, width: "95%" }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>📱 Certificate QR Code</h2>
            <p
              style={{
                margin: "4px 0 0",
                fontSize: 12,
                color: "#64748b",
              }}
            >
              Scan or download to verify this certificate
            </p>
          </div>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            type="button"
          >
            ×
          </button>
        </div>

        <div className={styles.formBody}>
          {/* ── Certificate Info Header ─────────────────────────── */}
          <div
            style={{
              padding: "12px 16px",
              background:
                "linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%)",
              border: "1px solid #99f6e4",
              borderRadius: 10,
              marginBottom: 18,
            }}
          >
            <div
              style={{
                fontSize: 11,
                fontWeight: 700,
                color: "#0f766e",
                textTransform: "uppercase",
                letterSpacing: 0.5,
                marginBottom: 4,
              }}
            >
              Certificate Number
            </div>
            <div
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                fontSize: 18,
                fontWeight: 800,
                color: "#0f172a",
                wordBreak: "break-all",
              }}
            >
              {row.certificate_no}
            </div>
            {row.company_name && (
              <div
                style={{
                  fontSize: 12,
                  color: "#475569",
                  marginTop: 4,
                  fontWeight: 500,
                }}
              >
                {row.company_name}
              </div>
            )}
            {row.standard_name && (
              <div
                style={{
                  fontSize: 11,
                  color: "#64748b",
                  marginTop: 2,
                }}
              >
                {row.standard_name}
              </div>
            )}
          </div>

          {/* ── QR Code Display ─────────────────────────────────── */}
          {qrCode ? (
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                padding: 20,
                background: "#fff",
                border: "2px solid #e2e8f0",
                borderRadius: 12,
                marginBottom: 16,
              }}
            >
              <div
                style={{
                  padding: 12,
                  background: "#fff",
                  border: "1px solid #e2e8f0",
                  borderRadius: 8,
                  marginBottom: 14,
                }}
              >
                <img
                  src={qrCode}
                  alt={`QR code for ${row.certificate_no}`}
                  style={{
                    width: 240,
                    height: 240,
                    display: "block",
                    imageRendering: "pixelated",
                  }}
                />
              </div>

              <div
                style={{
                  fontSize: 11,
                  color: "#9ca3af",
                  fontWeight: 500,
                  textAlign: "center",
                }}
              >
                📱 Scan this QR code to verify the certificate online
              </div>
            </div>
          ) : (
            <div
              style={{
                padding: 30,
                textAlign: "center",
                background: "#fef2f2",
                border: "1px solid #fecaca",
                borderRadius: 10,
                marginBottom: 16,
                color: "#991b1b",
              }}
            >
              <div style={{ fontSize: 32, marginBottom: 8 }}>⚠️</div>
              <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 4 }}>
                No QR Code Found
              </div>
              <div style={{ fontSize: 12, color: "#b91c1c" }}>
                This certificate doesn't have a QR code stored. Please
                regenerate the certificate.
              </div>
            </div>
          )}

          {/* ── Verification URL ──────────────────────────────── */}
          {verificationUrl && (
            <div
              style={{
                padding: "10px 14px",
                background: "#f8fafc",
                border: "1px solid #e2e8f0",
                borderRadius: 8,
                marginBottom: 14,
              }}
            >
              <div
                style={{
                  fontSize: 10,
                  fontWeight: 700,
                  color: "#94a3b8",
                  textTransform: "uppercase",
                  letterSpacing: 0.5,
                  marginBottom: 4,
                }}
              >
                Verification URL
              </div>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                }}
              >
                <code
                  style={{
                    flex: 1,
                    fontFamily: "'IBM Plex Mono', monospace",
                    fontSize: 11,
                    color: "#2563eb",
                    wordBreak: "break-all",
                    minWidth: 0,
                  }}
                >
                  {verificationUrl}
                </code>
                <button
                  onClick={copyVerificationUrl}
                  type="button"
                  title="Copy URL"
                  style={{
                    padding: "4px 10px",
                    background: "#fff",
                    border: "1px solid #e2e8f0",
                    borderRadius: 6,
                    fontSize: 11,
                    fontWeight: 600,
                    color: "#475569",
                    cursor: "pointer",
                    flexShrink: 0,
                  }}
                >
                  📋 Copy
                </button>
              </div>
            </div>
          )}

          {/* ── Helpful tip ───────────────────────────────────── */}
          <div
            style={{
              padding: "10px 14px",
              background: "#fef9c3",
              border: "1px solid #fde047",
              borderRadius: 8,
              fontSize: 11.5,
              color: "#854d0e",
              lineHeight: 1.5,
            }}
          >
            💡 <strong>Tip:</strong> Download the QR and place it on your
            printed certificate. Customers can scan it to verify authenticity
            on{" "}
            <code
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                background: "#fef3c7",
                padding: "1px 6px",
                borderRadius: 3,
              }}
            >
              qrsyst.com
            </code>
            .
          </div>
        </div>

        <div className={styles.modalFooter}>
          <button
            type="button"
            className={styles.btnCancel}
            onClick={onClose}
          >
            Close
          </button>
          {qrCode && (
            <button
              type="button"
              className={styles.btnSubmit}
              onClick={downloadQR}
              style={{
                background:
                  "linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)",
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              ⬇️ Download QR Code
            </button>
          )}
        </div>
      </div>
    </div>
  );
}