"use client";

import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import {
  FiChevronRight,
  FiEye,
  FiEdit,
  FiTrash2,
  FiDownload,
  FiExternalLink,
  // ✅ NEW
  FiFileText,
  FiFile,
} from "react-icons/fi";
import { MdQrCode2 } from "react-icons/md";
import {
  CertTypeBadge,
  StatusBadge,
} from "./components/certificates/CertificateBadges";
import type { CertificateRow as CertificateRowType } from "@/lib/api/types/certificate.types";

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

// ✅ NEW — IDs allowed to delete certificates
const DELETE_ALLOWED_USER_IDS = [1,8];

// ✅ NEW — Read current user id from localStorage / JWT (best-effort, no throws)
function getCurrentUserId(): number | null {
  if (typeof window === "undefined") return null;
  try {
    // 1. localStorage("user")
    const stored = localStorage.getItem("user");
    if (stored) {
      const parsed = JSON.parse(stored);
      const id = parsed?.id ?? parsed?.userId ?? parsed?.user_id;
      if (id != null) return Number(id);
    }
    // 2. JWT in localStorage
    const token =
      localStorage.getItem("token") ||
      localStorage.getItem("accessToken") ||
      localStorage.getItem("access_token");
    if (token && token.split(".").length === 3) {
      const payload = JSON.parse(atob(token.split(".")[1]));
      const id =
        payload?.id ?? payload?.userId ?? payload?.user_id ?? payload?.sub;
      if (id != null) return Number(id);
    }
    // 3. Plain userId key
    const direct =
      localStorage.getItem("userId") || localStorage.getItem("user_id");
    if (direct) return Number(direct);
  } catch {
    // ignore parse errors
  }
  return null;
}

interface Props {
  row: CertificateRowType;
  isExpanded: boolean;
  isSelected: boolean;
  toggleRowExpand: (sno: number) => void;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onEdit: (row: CertificateRowType) => void;
  onDelete: (row: CertificateRowType) => void;
  onView: (row: CertificateRowType) => void;
  onViewQR?: (row: CertificateRowType) => void;
}

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

// ✅ NEW — Same pattern as InquiryRow.tsx
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");
  }
}

export function CertificateRow({
  row,
  isExpanded,
  isSelected,
  toggleRowExpand,
  handleRowSelect,
  onEdit,
  onDelete,
  onView,
  onViewQR,
}: Props) {
  // ✅ NEW — URLs for downloads
  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`;

  // ✅ NEW — Build download filenames using cert_no
  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`;

  // ✅ NEW — Permission check: only allowed user ids see the delete button
  const currentUserId = getCurrentUserId();
  const canDelete =
    currentUserId !== null && DELETE_ALLOWED_USER_IDS.includes(currentUserId);

  return (
    <>
      <tr
        className={`${styles.tableRow} ${isSelected ? styles.selectedRow : ""}`}
      >
        <td className={styles.expandCell}>
          <button
            className={styles.expandBtn}
            onClick={() => toggleRowExpand(row.sno)}
          >
            <FiChevronRight
              size={16}
              className={`${styles.expandIcon} ${
                isExpanded ? styles.expanded : ""
              }`}
            />
          </button>
        </td>
        <td style={{ textAlign: "center", padding: "10px 8px" }}>
          <input
            type="checkbox"
            className={styles.checkbox}
            checked={isSelected}
            onChange={(e) => handleRowSelect(row.sno, e.target.checked)}
          />
        </td>

        <td className={styles.nameCell}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              flexWrap: "nowrap",
            }}
          >
            <span
              style={{
                fontFamily: "'IBM Plex Mono', monospace",
                fontSize: 12,
                fontWeight: 600,
                color: "#0f172a",
              }}
            >
              {row.certificate_no}
            </span>

            {/* Inline action icons next to Cert No */}
            <div style={{ display: "inline-flex", gap: 4, marginLeft: 4 }}>
              <button
                onClick={() => onView(row)}
                title="View Details"
                style={{
                  width: 24,
                  height: 24,
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  background: "#eff6ff",
                  border: "1px solid #bfdbfe",
                  borderRadius: 6,
                  color: "#1d4ed8",
                  cursor: "pointer",
                  padding: 0,
                }}
              >
                <FiEye size={13} />
              </button>

              {onViewQR && row.qrCode && (
                <button
                  onClick={() => onViewQR(row)}
                  title="View / Download QR Code"
                  style={{
                    width: 24,
                    height: 24,
                    display: "inline-flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: "#f0fdfa",
                    border: "1px solid #14b8a6",
                    borderRadius: 6,
                    color: "#0f766e",
                    cursor: "pointer",
                    padding: 0,
                  }}
                >
                  <MdQrCode2 size={14} />
                </button>
              )}
              {/* 👇 ADD THIS NEW BUTTON RIGHT HERE — after the QR button, still inside this same div */}
              <button
                onClick={() => onEdit(row)}
                title="Edit Certificate"
                style={{
                  width: 24,
                  height: 24,
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  background: "#fef3c7",
                  border: "1px solid #fcd34d",
                  borderRadius: 6,
                  color: "#b45309",
                  cursor: "pointer",
                  padding: 0,
                }}
              >
                <FiEdit size={13} />
              </button>
            </div>
          </div>
        </td>

        <td className={styles.nameCell}>
          <div style={{ fontWeight: 600, fontSize: 13 }}>
            {row.company_name}
          </div>
        </td>

        <td className={styles.nameCell}>
          <div style={{ fontWeight: 500, fontSize: 13 }}>
            {row.standard_name}
          </div>
          <div
            style={{
              fontSize: 11,
              color: "#9ca3af",
              fontFamily: "'IBM Plex Mono', monospace",
            }}
          >
            {row.standard_short}
          </div>
        </td>

        <td className={styles.nameCell}>
          <CertTypeBadge type={row.cert_type} />
        </td>

        <td className={styles.nameCell}>
          <StatusBadge status={row.status} />
        </td>

        <td className={styles.nameCell}>
          <span style={{ fontSize: 12, color: "#64748b" }}>
            {formatDate(row.issue_date)}
          </span>
        </td>

        <td className={styles.nameCell}>
          <span style={{ fontSize: 12, color: "#64748b" }}>
            {formatDate(row.expire_date)}
          </span>
        </td>

        <td className={styles.actionsCell}>
          <div className={styles.actionGroup}>
            {row.scan_pdf_url && (
              <a
                href={row.scan_pdf_url}
                target="_blank"
                rel="noopener noreferrer"
                className={styles.actionBtnView}
                title="View Signed Scan PDF"
              >
                <FiDownload size={14} />
              </a>
            )}
            {row.verification_url && (
              <a
                href={row.verification_url}
                target="_blank"
                rel="noopener noreferrer"
                className={styles.actionBtnView}
                title="Open Verify Page"
              >
                <FiExternalLink size={14} />
              </a>
            )}

            {/* QR Code button */}
            {onViewQR && row.qrCode && (
              <button
                className={styles.actionBtnView}
                onClick={() => onViewQR(row)}
                title="View / Download QR Code"
                style={{
                  background: "#f0fdfa",
                  borderColor: "#14b8a6",
                  color: "#0f766e",
                }}
              >
                <MdQrCode2 size={16} />
              </button>
            )}

            {/* ✅ Download Final PDF — uses downloadFile() */}
            <button
              className={styles.actionBtnView}
              onClick={() => downloadFile(pdfUrl, pdfFileName)}
              title="Download Certificate PDF (with QR)"
              style={{
                background: "#fef2f2",
                borderColor: "#fca5a5",
                color: "#b91c1c",
              }}
            >
              <FiFile size={14} />
            </button>

            {/* ✅ Download Word — uses downloadFile() */}
            <button
              className={styles.actionBtnView}
              onClick={() => downloadFile(docxUrl, docxFileName)}
              title="Download Certificate Word (with QR)"
              style={{
                background: "#eff6ff",
                borderColor: "#93c5fd",
                color: "#1e40af",
              }}
            >
              <FiFileText size={14} />
            </button>

            {/* ✅ Download DRAFT PDF — uses downloadFile() */}
            <button
              className={styles.actionBtnView}
              onClick={() => downloadFile(draftPdfUrl, draftFileName)}
              title="Download as DRAFT (with watermark)"
              style={{
                background: "#fef9c3",
                borderColor: "#fcd34d",
                color: "#854d0e",
                fontSize: 13,
                fontWeight: 700,
              }}
            >
              📋
            </button>

            <button
              className={styles.actionBtnView}
              onClick={() => onView(row)}
              title="View Details"
            >
              <FiEye size={14} />
            </button>
            <button
              className={styles.actionBtnEdit}
              onClick={() => onEdit(row)}
              title="Edit"
            >
              <FiEdit size={14} />
            </button>
            {/* ✅ NEW — Delete button gated to allowed user IDs only (currently: id=4) */}
            {canDelete && (
              <button
                className={styles.actionBtnDelete}
                onClick={() => onDelete(row)}
                title="Delete"
              >
                <FiTrash2 size={14} />
              </button>
            )}
          </div>
        </td>
      </tr>

      {isExpanded && (
        <tr className={styles.expandedRow}>
          <td colSpan={11}>
            <div className={styles.expandedContent}>
              <div className={styles.detailPanel}>
                <div className={styles.panelHeader}>Certificate Details</div>

                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Identification</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Certificate No</span>
                      <span
                        className={styles.value}
                        style={{ fontFamily: "'IBM Plex Mono', monospace" }}
                      >
                        {row.certificate_no}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Company</span>
                      <span className={styles.value}>{row.company_name}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Standard</span>
                      <span className={styles.value}>
                        {row.standard_name} ({row.standard_short})
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Type</span>
                      <span className={styles.value}>
                        <CertTypeBadge type={row.cert_type} />
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Status</span>
                      <span className={styles.value}>
                        <StatusBadge status={row.status} />
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Domain</span>
                      <span className={styles.value}>
                        {row.verification_domain}
                      </span>
                    </div>
                  </div>
                </div>

                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Dates</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Issue Date</span>
                      <span className={styles.value}>
                        {formatDate(row.issue_date)}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Expire Date</span>
                      <span className={styles.value}>
                        {formatDate(row.expire_date)}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Created</span>
                      <span className={styles.value}>
                        {formatDate(row.created_at)}
                      </span>
                    </div>
                    {/* ✅ NEW */}
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>
                        Surv. Audit On/Before
                      </span>
                      <span className={styles.value}>
                        {formatDate(row.surveillance_audit_due)}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Re-certification Due</span>
                      <span className={styles.value}>
                        {formatDate(row.recertification_due)}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <span className={styles.label}>Updated</span>
                      <span className={styles.value}>
                        {formatDate(row.updated_at)}
                      </span>
                    </div>
                  </div>
                </div>

                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>QR & Verify</div>
                  <div
                    style={{
                      display: "flex",
                      gap: 16,
                      alignItems: "flex-start",
                    }}
                  >
                    {row.qrCode && (
                      <div
                        style={{
                          border: "1px solid #e2e8f0",
                          borderRadius: 8,
                          padding: 8,
                          background: "#fff",
                        }}
                      >
                        <img
                          src={row.qrCode}
                          alt="QR"
                          style={{
                            width: 140,
                            height: 140,
                            display: "block",
                          }}
                        />
                      </div>
                    )}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div
                        style={{
                          fontSize: 11,
                          color: "#94a3b8",
                          fontWeight: 700,
                          marginBottom: 4,
                        }}
                      >
                        VERIFICATION URL
                      </div>
                      <div
                        style={{
                          fontSize: 12,
                          fontFamily: "'IBM Plex Mono', monospace",
                          color: "#0f172a",
                          wordBreak: "break-all",
                          padding: "8px 12px",
                          background: "#f8fafc",
                          borderRadius: 6,
                          border: "1px solid #e2e8f0",
                        }}
                      >
                        {row.verification_url || "—"}
                      </div>
                      <div
                        style={{
                          fontSize: 11,
                          color: "#94a3b8",
                          fontWeight: 700,
                          marginTop: 12,
                          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: 11,
                          color: "#94a3b8",
                          fontWeight: 700,
                          marginTop: 8,
                          marginBottom: 4,
                        }}
                      >
                        FINGERPRINT
                      </div>
                      <div
                        style={{
                          fontSize: 11,
                          fontFamily: "'IBM Plex Mono', monospace",
                          color: "#475569",
                        }}
                      >
                        {row.fingerprint}
                      </div>
                    </div>
                  </div>
                </div>

                {/* ✅ Document Downloads Section */}
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>
                    📄 Certificate Documents
                  </div>
                  <div
                    style={{
                      display: "flex",
                      gap: 10,
                      flexWrap: "wrap",
                      padding: 12,
                      background:
                        "linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%)",
                      border: "1px solid #99f6e4",
                      borderRadius: 10,
                    }}
                  >
                    <button
                      onClick={() => downloadFile(pdfUrl, pdfFileName)}
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 6,
                        padding: "10px 16px",
                        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",
                      }}
                    >
                      <FiFile size={14} /> Download PDF
                    </button>

                    <button
                      onClick={() => downloadFile(docxUrl, docxFileName)}
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 6,
                        padding: "10px 16px",
                        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",
                      }}
                    >
                      <FiFileText size={14} /> Download Word
                    </button>

                    <button
                      onClick={() => downloadFile(draftPdfUrl, draftFileName)}
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 6,
                        padding: "10px 16px",
                        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",
                      }}
                    >
                      📋 Download DRAFT (with watermark)
                    </button>
                  </div>
                  <div
                    style={{
                      marginTop: 8,
                      fontSize: 11,
                      color: "#64748b",
                      fontStyle: "italic",
                    }}
                  >
                    💡 PDF and Word documents include the QR code for
                    verification. Use DRAFT for review before final issuance.
                  </div>
                </div>

                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Signed Scan PDF</div>
                  {row.scan_pdf_url ? (
                    <div>
                      <a
                        href={row.scan_pdf_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{
                          color: "#2563eb",
                          fontSize: 13,
                          textDecoration: "underline",
                        }}
                      >
                        {row.scan_pdf_url}
                      </a>
                    </div>
                  ) : (
                    <div
                      style={{
                        padding: 12,
                        background: "#fef3c7",
                        color: "#92400e",
                        borderRadius: 6,
                        fontSize: 12,
                      }}
                    >
                      ⏳ No scan uploaded yet. Use Bulk Upload Scans to attach
                      the signed PDF.
                    </div>
                  )}
                </div>

                <div className={styles.panelActions}>
                  {onViewQR && row.qrCode && (
                    <button
                      className={styles.secondaryBtn}
                      onClick={() => onViewQR(row)}
                      style={{
                        background: "#f0fdfa",
                        borderColor: "#14b8a6",
                        color: "#0f766e",
                      }}
                    >
                      <MdQrCode2 size={14} /> View / Download QR
                    </button>
                  )}
                  <button
                    className={styles.secondaryBtn}
                    onClick={() => onEdit(row)}
                  >
                    <FiEdit size={14} /> Edit
                  </button>
                  {/* ✅ NEW — Delete button gated to allowed user IDs only (currently: id=4) */}
                  {canDelete && (
                    <button
                      className={styles.dangerBtn}
                      onClick={() => onDelete(row)}
                    >
                      <FiTrash2 size={14} /> Delete
                    </button>
                  )}
                </div>
              </div>
            </div>
          </td>
        </tr>
      )}
    </>
  );
}