"use client";

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

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

// ✅ NEW — API base URL for downloads
const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "https://crm.qrsyst.com/api";

// ✅ NEW — Same downloadFile pattern as InquiryRow / CertificateRow
async function downloadFile(url: string, fileName: string) {
  try {
    const token =
      localStorage.getItem("access_token") ||
      localStorage.getItem("token") ||
      sessionStorage.getItem("access_token");

    const res = await fetch(url, {
      method: "GET",
      headers: {
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
      },
      credentials: "include",
    });

    if (!res.ok) throw new Error(`Download failed: ${res.status}`);

    const blob = await res.blob();
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
  } catch (err: any) {
    alert(err.message || "Download failed");
  }
}

// ─── Small helpers ────────────────────────────────────────────────────────────
function SectionHeader({ title }: { title: string }) {
  return (
    <div className={styles.sectionHeader} style={{ marginTop: 20 }}>
      <span className={styles.sectionDot} />
      {title}
    </div>
  );
}

function Field({
  label,
  value,
  mono = false,
  fullWidth = false,
}: {
  label: string;
  value?: string | null;
  mono?: boolean;
  fullWidth?: boolean;
}) {
  return (
    <div
      className={
        fullWidth ? `${styles.formGroup} ${styles.full}` : styles.formGroup
      }
    >
      <label className={styles.label}>{label}</label>
      <div
        style={{
          padding: "8px 12px",
          borderRadius: 8,
          border: "1px solid #e5e7eb",
          backgroundColor: "#f9fafb",
          fontSize: 13,
          color: value ? "#0f172a" : "#9ca3af",
          fontFamily: mono ? "'IBM Plex Mono', monospace" : "inherit",
          minHeight: 36,
          lineHeight: 1.5,
        }}
      >
        {value || "—"}
      </div>
    </div>
  );
}

function formatDisplayDate(s?: string | null): string {
  if (!s) return "";
  try {
    return new Date(s)
      .toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      })
      .replace(/ /g, "-");
  } catch {
    return "";
  }
}

function resolveScanUrl(url?: string | null): string | undefined {
  if (!url) return undefined;
  if (url.startsWith("http://") || url.startsWith("https://")) return url;
  const apiBase = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007";
  const baseUrl = apiBase.replace(/\/api\/?$/, "");
  const cleanPath = url.startsWith("/") ? url : `/${url}`;
  return `${baseUrl}${cleanPath}`;
}

// ─── Component ────────────────────────────────────────────────────────────────
export default function CertificateViewModal({ row, onClose }: Props) {
  if (!row) return null;

  const scanPdfUrl = resolveScanUrl(row.scan_pdf_url);

  // ✅ NEW — Build download URLs and filenames
  const pdfUrl = `${API_BASE_URL}/certificates/${row.id}/download/pdf`;
  const docxUrl = `${API_BASE_URL}/certificates/${row.id}/download/docx`;
  const draftPdfUrl = `${API_BASE_URL}/certificates/${row.id}/download/pdf?draft=true`;

  const safeCertNo = (row.certificate_no || `cert-${row.id}`).replace(
    /[^a-zA-Z0-9-]/g,
    "_",
  );
  const pdfFileName = `${safeCertNo}.pdf`;
  const docxFileName = `${safeCertNo}.docx`;
  const draftFileName = `${safeCertNo}_DRAFT.pdf`;

  const typeCfg = CERT_TYPE_META[row.cert_type] ?? {
    label: row.cert_type,
    color: "#6b7280",
    bg: "#f3f4f6",
  };
  const statusCfg = STATUS_META[row.status] ?? {
    label: row.status,
    color: "#6b7280",
    bg: "#f3f4f6",
  };

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 860 }}
      >
        {/* ── Header ──────────────────────────────────────────────── */}
        <div
          className={styles.modalHeader}
          style={{
            background:
              "linear-gradient(135deg, #052e16 0%, #0d7a45 50%, #16a34a 100%)",
          }}
        >
          <div>
            <p
              className={styles.modalSubtitle}
              style={{
                color: "rgba(255,255,255,0.7)",
                marginBottom: 2,
                marginLeft: 0,
              }}
            >
              Certificate Details
            </p>
            <h2
              className={styles.modalTitle}
              style={{
                color: "#fff",
                fontFamily: "'IBM Plex Mono', monospace",
              }}
            >
              {row.certificate_no}
            </h2>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span
              style={{
                padding: "4px 12px",
                borderRadius: 99,
                fontSize: 11,
                fontWeight: 700,
                backgroundColor: "rgba(255,255,255,0.2)",
                color: "#fff",
              }}
            >
              {typeCfg.label}
            </span>
            <button
              className={styles.closeBtn}
              onClick={onClose}
              type="button"
              style={{
                color: "#fff",
                background: "rgba(255,255,255,0.2)",
                border: "none",
              }}
            >
              ✕
            </button>
          </div>
        </div>

        {/* ── Status strip ────────────────────────────────────────── */}
        <div
          style={{
            padding: "8px 24px",
            backgroundColor: statusCfg.bg,
            borderBottom: "1px solid #e2e8f0",
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          <span
            style={{
              width: 8,
              height: 8,
              borderRadius: "50%",
              backgroundColor: statusCfg.color,
              display: "inline-block",
            }}
          />
          <span
            style={{ fontSize: 12, fontWeight: 700, color: statusCfg.color }}
          >
            {statusCfg.label}
          </span>
          {row.company_name && (
            <>
              <span style={{ color: "#cbd5e1", fontSize: 12 }}>·</span>
              <span
                style={{ fontSize: 12, color: "#64748b", fontWeight: 500 }}
              >
                {row.company_name}
              </span>
            </>
          )}
          {row.verification_domain && (
            <>
              <span
                style={{ color: "#cbd5e1", fontSize: 12, marginLeft: "auto" }}
              >
                ·
              </span>
              <span
                style={{
                  fontSize: 11,
                  color: "#64748b",
                  fontWeight: 500,
                  textTransform: "uppercase",
                  letterSpacing: "0.05em",
                }}
              >
                {row.verification_domain === "international"
                  ? "🌐 International"
                  : "🇦🇪 Local"}
              </span>
            </>
          )}
        </div>

        {/* ── Body ────────────────────────────────────────────────── */}
        <div className={styles.formBody}>
          {/* ✅ NEW — Download Documents Section (top of body for visibility) */}
          <SectionHeader title="📥 Download Certificate DRAFT/Print copy" />
          <div
            style={{
              display: "flex",
              gap: 10,
              flexWrap: "wrap",
              padding: 14,
              background:
                "linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%)",
              border: "1px solid #99f6e4",
              borderRadius: 10,
            }}
          >
            <button
              onClick={() => downloadFile(pdfUrl, pdfFileName)}
              type="button"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "10px 18px",
                background:
                  "linear-gradient(135deg, #dc2626 0%, #ef4444 100%)",
                color: "#fff",
                border: "none",
                borderRadius: 8,
                fontSize: 13,
                fontWeight: 700,
                boxShadow: "0 2px 8px rgba(220,38,38,0.25)",
                cursor: "pointer",
                transition: "transform 0.15s, box-shadow 0.15s",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = "translateY(-1px)";
                e.currentTarget.style.boxShadow =
                  "0 4px 12px rgba(220,38,38,0.4)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = "translateY(0)";
                e.currentTarget.style.boxShadow =
                  "0 2px 8px rgba(220,38,38,0.25)";
              }}
            >
              📄 Download PDF
            </button>

            <button
              onClick={() => downloadFile(docxUrl, docxFileName)}
              type="button"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "10px 18px",
                background:
                  "linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)",
                color: "#fff",
                border: "none",
                borderRadius: 8,
                fontSize: 13,
                fontWeight: 700,
                boxShadow: "0 2px 8px rgba(30,64,175,0.25)",
                cursor: "pointer",
                transition: "transform 0.15s, box-shadow 0.15s",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = "translateY(-1px)";
                e.currentTarget.style.boxShadow =
                  "0 4px 12px rgba(30,64,175,0.4)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = "translateY(0)";
                e.currentTarget.style.boxShadow =
                  "0 2px 8px rgba(30,64,175,0.25)";
              }}
            >
              📝 Download Word
            </button>

            <button
              onClick={() => downloadFile(draftPdfUrl, draftFileName)}
              type="button"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "10px 18px",
                background:
                  "linear-gradient(135deg, #d97706 0%, #f59e0b 100%)",
                color: "#fff",
                border: "none",
                borderRadius: 8,
                fontSize: 13,
                fontWeight: 700,
                boxShadow: "0 2px 8px rgba(217,119,6,0.25)",
                cursor: "pointer",
                transition: "transform 0.15s, box-shadow 0.15s",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = "translateY(-1px)";
                e.currentTarget.style.boxShadow =
                  "0 4px 12px rgba(217,119,6,0.4)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = "translateY(0)";
                e.currentTarget.style.boxShadow =
                  "0 2px 8px rgba(217,119,6,0.25)";
              }}
            >
              📋 Download DRAFT
            </button>
          </div>
          <div
            style={{
              marginTop: 8,
              fontSize: 11,
              color: "#64748b",
              fontStyle: "italic",
              padding: "0 4px",
            }}
          >
            💡 PDF and Word documents include the QR code for verification. Use
            <strong> DRAFT </strong>for review before final issuance.
          </div>

          {/* Certificate Information */}
          <SectionHeader title="Certificate Information" />
          <div className={styles.grid2}>
            <Field label="Certificate No." value={row.certificate_no} mono />
            <Field label="Certificate Type" value={typeCfg.label} />
            <Field label="Status" value={statusCfg.label} />
            <Field
              label="Verification Domain"
              value={
                row.verification_domain === "international"
                  ? "International (qrs-intl.com)"
                  : "Local (qrsyst.com)"
              }
            />
          </div>

          {/* Company & Standard */}
          <SectionHeader title="🏢 Company & Standard" />
          <div className={styles.grid2}>
            <Field label="Company Name" value={row.company_name} fullWidth />
            <Field label="Standard" value={row.standard_name} />
            <Field label="Standard Short" value={row.standard_short} mono />
          </div>

          {/* Validity Dates */}
          <SectionHeader title="📅 Validity Dates" />
          <div className={styles.grid3}>
            <Field
              label="Issue Date"
              value={formatDisplayDate(row.issue_date)}
            />
            <Field
              label="Expire Date"
              value={formatDisplayDate(row.expire_date)}
            />
            <Field
              label="Created"
              value={formatDisplayDate(row.created_at)}
            />
          </div>

          {/* QR Code & Verification */}
          <SectionHeader title="🔗 QR Code & Public Verification" />
          <div
            style={{
              display: "flex",
              gap: 16,
              alignItems: "flex-start",
              padding: "14px",
              borderRadius: 10,
              backgroundColor: "#f9fafb",
              border: "1px solid #e5e7eb",
            }}
          >
            {row.qrCode && (
              <div
                style={{
                  border: "1px solid #e2e8f0",
                  borderRadius: 8,
                  padding: 6,
                  background: "#fff",
                  flexShrink: 0,
                }}
              >
                <img
                  src={row.qrCode}
                  alt="QR Code"
                  style={{ width: 140, height: 140, display: "block" }}
                />
              </div>
            )}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div
                style={{
                  fontSize: 10,
                  color: "#94a3b8",
                  fontWeight: 700,
                  letterSpacing: "0.08em",
                  textTransform: "uppercase",
                  marginBottom: 4,
                }}
              >
                Verification URL
              </div>
              <div
                style={{
                  fontSize: 11,
                  fontFamily: "'IBM Plex Mono', monospace",
                  color: "#0f172a",
                  wordBreak: "break-all",
                  padding: "8px 10px",
                  background: "#fff",
                  borderRadius: 6,
                  border: "1px solid #e2e8f0",
                  lineHeight: 1.6,
                }}
              >
                {row.verification_url || "—"}
              </div>

              <div
                style={{
                  fontSize: 10,
                  color: "#94a3b8",
                  fontWeight: 700,
                  letterSpacing: "0.08em",
                  textTransform: "uppercase",
                  marginTop: 10,
                  marginBottom: 4,
                }}
              >
                Token
              </div>
              <div
                style={{
                  fontSize: 11,
                  fontFamily: "'IBM Plex Mono', monospace",
                  color: "#475569",
                  wordBreak: "break-all",
                }}
              >
                {row.qrcode_token || "—"}
              </div>

              <div
                style={{
                  fontSize: 10,
                  color: "#94a3b8",
                  fontWeight: 700,
                  letterSpacing: "0.08em",
                  textTransform: "uppercase",
                  marginTop: 10,
                  marginBottom: 4,
                }}
              >
                Fingerprint
              </div>
              <div
                style={{
                  fontSize: 11,
                  fontFamily: "'IBM Plex Mono', monospace",
                  color: "#475569",
                }}
              >
                {row.fingerprint || "—"}
              </div>

              {row.verification_url && (
                <a
                  href={row.verification_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 6,
                    marginTop: 12,
                    padding: "6px 12px",
                    background: "#0d7a45",
                    color: "#fff",
                    borderRadius: 6,
                    fontSize: 12,
                    fontWeight: 600,
                    textDecoration: "none",
                  }}
                >
                  🔗 Open Verify Page
                </a>
              )}
            </div>
          </div>

          {/* Signed Scan PDF */}
          <SectionHeader title="📄 Signed Scan PDF" />
          {scanPdfUrl ? (
            <div
              style={{
                padding: "10px 14px",
                borderRadius: 8,
                border: "1px solid #bbf7d0",
                backgroundColor: "#f0fdf4",
                fontSize: 13,
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                gap: 10,
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ fontSize: 20 }}>✅</span>
                <div>
                  <div style={{ fontWeight: 700, color: "#166534" }}>
                    Scan uploaded
                  </div>
                  <div
                    style={{
                      fontSize: 11,
                      color: "#15803d",
                      fontFamily: "'IBM Plex Mono', monospace",
                      marginTop: 2,
                      wordBreak: "break-all",
                    }}
                  >
                    {scanPdfUrl}
                  </div>
                </div>
              </div>
              <a
                href={scanPdfUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  padding: "6px 14px",
                  background: "#0d7a45",
                  color: "#fff",
                  borderRadius: 6,
                  fontSize: 12,
                  fontWeight: 600,
                  textDecoration: "none",
                  flexShrink: 0,
                }}
              >
                📥 View PDF
              </a>
            </div>
          ) : (
            <div
              style={{
                padding: "10px 14px",
                borderRadius: 8,
                border: "1px solid #fde68a",
                backgroundColor: "#fffbeb",
                fontSize: 13,
                color: "#92400e",
                display: "flex",
                alignItems: "center",
                gap: 10,
              }}
            >
              <span style={{ fontSize: 20 }}>⏳</span>
              <div>
                <div style={{ fontWeight: 700 }}>No scan uploaded yet</div>
                <div style={{ fontSize: 11, marginTop: 2 }}>
                  Use <strong>Bulk Upload Scans</strong> to attach the signed
                  scanned PDF. The certificate will become publicly verifiable
                  once uploaded.
                </div>
              </div>
            </div>
          )}

          {/* Audit Trail */}
          <SectionHeader title="🕒 Audit Trail" />
          <div className={styles.grid2}>
            <Field
              label="Created At"
              value={formatDisplayDate(row.created_at)}
            />
            <Field
              label="Last Updated"
              value={formatDisplayDate(row.updated_at)}
            />
          </div>
        </div>

        {/* ── Footer ──────────────────────────────────────────────── */}
        <div className={styles.modalFooter}>
          <button type="button" onClick={onClose} className={styles.cancelBtn}>
            Close
          </button>

          {/* ✅ NEW — Quick download button in footer */}
          <button
            type="button"
            onClick={() => downloadFile(pdfUrl, pdfFileName)}
            className={styles.btnSubmit}
            style={{
              background:
                "linear-gradient(135deg, #dc2626 0%, #ef4444 100%)",
              border: "none",
              color: "#fff",
              cursor: "pointer",
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
            }}
          >
            📄 Download PDF
          </button>

          {row.verification_url && (
            <a
              href={row.verification_url}
              target="_blank"
              rel="noopener noreferrer"
              className={styles.btnSubmit}
              style={{ textDecoration: "none" }}
            >
              🔗 Open Verify Page
            </a>
          )}
        </div>
      </div>
    </div>
  );
}