"use client";

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

interface Props {
  data: CreateCertificateResponse;
  onClose: () => void;
}

export default function CertificateSuccessModal({ data, onClose }: Props) {
  const { summary, certificates } = data;

  const downloadQR = (qrCode: string, certNo: string) => {
    const link = document.createElement("a");
    link.href = qrCode;
    link.download = `${certNo}-qr.png`;
    link.click();
  };

  const downloadAllQRs = () => {
    certificates.forEach((c, i) => {
      setTimeout(
        () => downloadQR(c.qrCode, c.certificate.certificate_no),
        i * 150,
      );
    });
  };

  return (
    <div className={styles.modalOverlay}>
      <div
        className={styles.modalContent}
        style={{ maxWidth: 900, width: "95%" }}
      >
        <div className={styles.modalHeader}>
          <h2 className={styles.modalTitle}>
            ✅ Certificates Created Successfully
          </h2>
          <button
            className={styles.closeBtn}
            onClick={onClose}
            type="button"
          >
            ×
          </button>
        </div>

        <div className={styles.formBody}>
          {/* Summary */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3,1fr)",
              gap: 12,
              marginBottom: 20,
            }}
          >
            <SummaryCard label="Total Created" value={summary.total} color="#2563eb" />
            <SummaryCard
              label="Generated (New)"
              value={summary.generated}
              color="#15803d"
            />
            <SummaryCard
              label="Reused (Renewal)"
              value={summary.reused}
              color="#b45309"
            />
          </div>

          {/* Certificates list */}
          <div
            style={{
              fontSize: 11,
              fontWeight: 800,
              color: "#94a3b8",
              letterSpacing: ".08em",
              textTransform: "uppercase",
              marginBottom: 10,
            }}
          >
            Certificates ({certificates.length})
          </div>

          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: 12,
            }}
          >
            {certificates.map((c, idx) => (
              <div
                key={idx}
                style={{
                  border: "1px solid #e2e8f0",
                  borderRadius: 8,
                  padding: 14,
                  background: "#fff",
                  display: "flex",
                  gap: 14,
                  alignItems: "flex-start",
                }}
              >
                {/* QR */}
                <div
                  style={{
                    border: "1px solid #e2e8f0",
                    borderRadius: 6,
                    padding: 4,
                    background: "#fff",
                    flexShrink: 0,
                  }}
                >
                  <img
                    src={c.qrCode}
                    alt="QR"
                    style={{
                      width: 100,
                      height: 100,
                      display: "block",
                    }}
                  />
                </div>

                {/* Details */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 8,
                      marginBottom: 4,
                    }}
                  >
                    <span
                      style={{
                        fontFamily: "'IBM Plex Mono', monospace",
                        fontSize: 14,
                        fontWeight: 700,
                        color: "#0f172a",
                      }}
                    >
                      {c.certificate.certificate_no}
                    </span>
                    <ActionBadge action={c.action} />
                    <SourceBadge source={c.source} />
                  </div>
                  <div style={{ fontSize: 12, color: "#64748b" }}>
                    {c.certificate.standard_name}
                  </div>
                  <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 2 }}>
                    Company: {c.certificate.company_name_snapshot}
                  </div>
                  <div
                    style={{
                      marginTop: 6,
                      fontSize: 11,
                      fontFamily: "'IBM Plex Mono', monospace",
                      color: "#2563eb",
                      wordBreak: "break-all",
                    }}
                  >
                    {c.verification_url}
                  </div>
                </div>

                {/* Download QR button */}
                <button
                  onClick={() =>
                    downloadQR(c.qrCode, c.certificate.certificate_no)
                  }
                  style={{
                    border: "1px solid #e2e8f0",
                    background: "#f8fafc",
                    padding: "6px 12px",
                    borderRadius: 6,
                    fontSize: 12,
                    cursor: "pointer",
                    fontWeight: 600,
                    color: "#475569",
                    flexShrink: 0,
                  }}
                >
                  ⬇️ QR
                </button>
              </div>
            ))}
          </div>

          {/* Next step hint */}
          <div className={styles.alertSuccess} style={{ marginTop: 18 }}>
            <strong>📌 Next step:</strong> Place the QR code on your paper
            certificate design, print it, get it signed by the director, scan it
            as a PDF named exactly as the cert number (e.g.{" "}
            <code
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                background: "#dbeafe",
                padding: "1px 6px",
                borderRadius: 3,
              }}
            >
              {certificates[0]?.certificate.certificate_no}.pdf
            </code>
            ), then use <strong>Bulk Upload Scans</strong> to attach it. The
            certificate becomes publicly verifiable only after the scan is
            uploaded.
          </div>
        </div>

        <div className={styles.modalFooter}>
          {certificates.length > 1 && (
            <button
              className={styles.btnCancel}
              onClick={downloadAllQRs}
              type="button"
            >
              ⬇️ Download All QRs
            </button>
          )}
          <button
            className={styles.btnSubmit}
            onClick={onClose}
            type="button"
          >
            Done
          </button>
        </div>
      </div>
    </div>
  );
}

function SummaryCard({
  label,
  value,
  color,
}: {
  label: string;
  value: number;
  color: string;
}) {
  return (
    <div
      style={{
        padding: 14,
        border: `1px solid ${color}33`,
        background: `${color}0a`,
        borderRadius: 8,
        textAlign: "center",
      }}
    >
      <div style={{ fontSize: 28, fontWeight: 800, color, lineHeight: 1 }}>
        {value}
      </div>
      <div
        style={{
          fontSize: 11,
          color: "#64748b",
          marginTop: 4,
          fontWeight: 600,
          letterSpacing: ".04em",
          textTransform: "uppercase",
        }}
      >
        {label}
      </div>
    </div>
  );
}

function ActionBadge({ action }: { action: string }) {
  const meta: Record<string, { bg: string; color: string }> = {
    GENERATED: { bg: "#dcfce7", color: "#15803d" },
    REUSED: { bg: "#fef3c7", color: "#b45309" },
  };
  const m = meta[action] ?? { bg: "#f1f5f9", color: "#64748b" };
  return (
    <span
      style={{
        padding: "2px 8px",
        borderRadius: 4,
        fontSize: 9,
        fontWeight: 800,
        letterSpacing: ".05em",
        color: m.color,
        background: m.bg,
      }}
    >
      {action}
    </span>
  );
}

function SourceBadge({ source }: { source: string }) {
  if (source === "new") return null;
  const label =
    source === "api_excel"
      ? "FROM LEGACY"
      : source === "new_certificate"
        ? "FROM RECORDS"
        : source;
  return (
    <span
      style={{
        padding: "2px 8px",
        borderRadius: 4,
        fontSize: 9,
        fontWeight: 600,
        letterSpacing: ".05em",
        color: "#64748b",
        background: "#f1f5f9",
      }}
    >
      {label}
    </span>
  );
}