"use client";

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

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

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

  const qrCode = row.qrCode || null;
  const verificationUrl = row.verification_url || "";

  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);
      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}>📱 Training Certificate QR</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>
            <div
              style={{
                fontSize: 12,
                color: "#475569",
                marginTop: 4,
                fontWeight: 500,
              }}
            >
              {row.participant_name}
              {row.participant_company ? ` — ${row.participant_company}` : ""}
            </div>
            <div style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}>
              {row.course_title}
            </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" }}>
                Refresh the list and try again.
              </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 the printed
            training certificate before signing and scanning it.
          </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>
  );
}
