"use client";

import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import {
  FiChevronRight,
  FiEye,
  FiEdit,
  FiTrash2,
  FiFileText,
  FiUser,
  FiCalendar,
  FiDownload,
  FiPaperclip,
} from "react-icons/fi";
import type { InquiryRow as InquiryRowType } from "@/lib/api/types/inquiry.types";
import {
  STATUS_CONFIG,
  TYPE_CONFIG,
  formatDisplayDate,
} from "@/lib/api/mappers/inquiry.mappers";
import { getDraftPdfUrl, getDraftDocxUrl } from "@/lib/api/inquiry.api";

interface ButtonConfig {
  key: string;
  icon: string;
  color: string;
  label: string;
  order: number;
  position: "row" | "toolbar";
}
interface ColumnConfig {
  key: string;
  type: string;
  label: string;
  order: number;
  sortable: boolean;
  default_visible: boolean;
}

// ✅ NEW — Document attachment shape
interface InquiryDocument {
  type: string;
  path: string;
  filename: string;
  uploaded_at: string;
  uploaded_by?: number;
}

interface Props {
  row: InquiryRowType;
  visibleColumns: ColumnConfig[];
  rowButtons: ButtonConfig[];
  hasActionsColumn: boolean;
  mapColumnKeyToValue: (key: string, row: InquiryRowType) => any;
  isExpanded: boolean;
  isSelected: boolean;
  generating?: boolean;
  toggleRowExpand: (sno: number) => void;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onAction: (row: InquiryRowType, actionKey: string) => void;
}

const iconMap: Record<string, React.ReactNode> = {
  view: <FiEye size={14} />,
  edit: <FiEdit size={14} />,
  delete: <FiTrash2 size={14} />,
  "generate-draft": <FiFileText size={14} />,
  confirm: <span style={{ fontSize: 14 }}>✅</span>,
  "request-changes": <span style={{ fontSize: 14 }}>↩</span>,
  export: <FiDownload size={14} />,
};

// ✅ NEW — Document type label map
const DOC_TYPE_LABELS: Record<string, string> = {
  trade_license: "📄 Trade License",
  previous_certificate: "🎫 Previous Certificate",
  audit_report: "📋 Audit Report",
  scope_letter: "✉️ Scope Letter",
  other: "📎 Other",
};

const docTypeLabel = (t: string) => DOC_TYPE_LABELS[t] ?? t;

// ─────────────────────────────────────────────────────────────────
// ✅ Authenticated draft download helper
// Fetches with JWT Authorization header (window.open can't do this)
// then triggers a browser download via Blob URL
// ─────────────────────────────────────────────────────────────────
async function downloadDraftFile(
  inquiryId: number,
  type: "pdf" | "docx",
  inquiryRef: string,
  draftGeneratedAt?: string | Date | null, // ✅ NEW
) {
  try {
    const token = localStorage.getItem("access_token");
    if (!token) {
      alert("You are not logged in. Please refresh and log in again.");
      return;
    }

    const url =
      type === "pdf"
        ? getDraftPdfUrl(inquiryId, draftGeneratedAt) // ✅ NEW
        : getDraftDocxUrl(inquiryId, draftGeneratedAt); // ✅ NEW
    const res = await fetch(url, {
      headers: { Authorization: `Bearer ${token}` },
    });

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

    const blob = await res.blob();
    const blobUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = blobUrl;
    a.download = `${inquiryRef}_DRAFT.${type}`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(blobUrl);
  } catch (err) {
    console.error("Draft download failed:", err);
    alert("Failed to download. Please try again.");
  }
}

// ✅ NEW — Open uploaded document in new tab
function openDocument(docPath: string) {
  const apiBase =
    process.env.NEXT_PUBLIC_API_URL?.replace(/\/api$/, "") ??
    "http://localhost:3007";
  const url = `${apiBase}/${docPath}`;
  window.open(url, "_blank");
}

// ─────────────────────────────────────────────────────────────────
// Status & Type badges
// ─────────────────────────────────────────────────────────────────
function StatusBadge({ status }: { status: string }) {
  const cfg = STATUS_CONFIG[status] ?? {
    label: status,
    bg: "#f3f4f6",
    color: "#6b7280",
    dot: "#9ca3af",
  };
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 5,
        padding: "3px 10px",
        borderRadius: 12,
        fontSize: 11,
        fontWeight: 600,
        backgroundColor: cfg.bg,
        color: cfg.color,
      }}
    >
      <span
        style={{
          width: 6,
          height: 6,
          borderRadius: "50%",
          backgroundColor: cfg.dot,
          flexShrink: 0,
        }}
      />
      {cfg.label}
    </span>
  );
}

function TypeBadge({ type }: { type: string }) {
  const cfg = TYPE_CONFIG[type] ?? {
    label: type,
    bg: "#f3f4f6",
    color: "#6b7280",
  };
  return (
    <span
      style={{
        padding: "2px 8px",
        borderRadius: 8,
        fontSize: 10,
        fontWeight: 700,
        textTransform: "uppercase",
        letterSpacing: "0.05em",
        backgroundColor: cfg.bg,
        color: cfg.color,
      }}
    >
      {cfg.label}
    </span>
  );
}

// Render cell value based on column key/type
// ─────────────────────────────────────────────────────────────────
function renderCellValue(
  col: ColumnConfig,
  value: any,
  row?: InquiryRowType,
  onAction?: (row: InquiryRowType, key: string) => void,
  permittedKeys?: Set<string>,
) {
  if (col.key === "status") return <StatusBadge status={String(value ?? "")} />;
  if (col.key === "inquiry_type")
    return <TypeBadge type={String(value ?? "")} />;
  // ✅ NEW — Certification Body badge
  if (col.key === "cert_body") {
    const v = String(value ?? "").trim();
    if (!v || v === "—") return <span style={{ color: "#9ca3af" }}>—</span>;
    return (
      <span
        style={{
          padding: "3px 10px",
          borderRadius: 8,
          fontSize: 11,
          fontWeight: 700,
          letterSpacing: "0.05em",
          background:
            v === "QRS"
              ? "linear-gradient(135deg, #ede9fe 0%, #ddd6fe 100%)"
              : "linear-gradient(135deg, #cffafe 0%, #a5f3fc 100%)",
          color: v === "QRS" ? "#6d28d9" : "#0e7490",
          border: `1px solid ${v === "QRS" ? "#c4b5fd" : "#67e8f9"}`,
        }}
      >
        {v === "QRS" ? "🏢 QRS" : "🏛 TQS"}
      </span>
    );
  }

  // ✅ NEW — Audit Stage badge
  if (col.key === "audit_stage") {
    const v = String(value ?? "").trim();
    if (!v || v === "—") return <span style={{ color: "#9ca3af" }}>—</span>;
    const stageColors: Record<
      string,
      { bg: string; color: string; border: string }
    > = {
      "Stage 1": { bg: "#dbeafe", color: "#1e40af", border: "#bfdbfe" },
      "Stage 2": { bg: "#dbeafe", color: "#1e40af", border: "#bfdbfe" },
      Surveillance: { bg: "#fef3c7", color: "#92400e", border: "#fde68a" },
      Recertification: { bg: "#dcfce7", color: "#166534", border: "#bbf7d0" },
    };
    const cfg = stageColors[v] ?? {
      bg: "#f3f4f6",
      color: "#374151",
      border: "#e5e7eb",
    };
    return (
      <span
        style={{
          padding: "3px 10px",
          borderRadius: 8,
          fontSize: 11,
          fontWeight: 600,
          backgroundColor: cfg.bg,
          color: cfg.color,
          border: `1px solid ${cfg.border}`,
          whiteSpace: "nowrap",
        }}
      >
        {v}
      </span>
    );
  }
  // ✅ inquiry_ref — show ref + inline view/edit icons
  if (col.key === "inquiry_ref" && row && onAction) {
    const showView = !permittedKeys || permittedKeys.has("view");
    const showEdit = !permittedKeys || permittedKeys.has("edit");
    return (
      <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
        <span
          style={{
            fontFamily: "monospace",
            fontSize: 12,
            fontWeight: 600,
            color: "#374151",
          }}
        >
          {String(value ?? "—")}
        </span>
        {showView && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              onAction(row, "view");
            }}
            title="View"
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              width: 24,
              height: 24,
              borderRadius: 6,
              border: "1px solid #bfdbfe",
              backgroundColor: "#eff6ff",
              color: "#2563eb",
              cursor: "pointer",
              padding: 0,
              transition: "all 0.15s",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = "#dbeafe";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = "#eff6ff";
            }}
          >
            <FiEye size={12} />
          </button>
        )}
        {showEdit && (
          <button
            onClick={(e) => {
              e.stopPropagation();
              onAction(row, "edit");
            }}
            title="Edit"
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              width: 24,
              height: 24,
              borderRadius: 6,
              border: "1px solid #d1fae5",
              backgroundColor: "#ecfdf5",
              color: "#10b981",
              cursor: "pointer",
              padding: 0,
              transition: "all 0.15s",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = "#d1fae5";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = "#ecfdf5";
            }}
          >
            <FiEdit size={12} />
          </button>
        )}
      </div>
    );
  }

  // ✅ SAFETY: never render objects directly
  if (value === null || value === undefined) return "—";
  if (typeof value === "object") {
    if (Array.isArray(value)) {
      return value.length === 0 ? "—" : `${value.length} item(s)`;
    }
    return value.name ?? value.title ?? value.label ?? "—";
  }
  return String(value);
}

// ─────────────────────────────────────────────────────────────────
// Decide if a workflow button should appear based on row status
// ─────────────────────────────────────────────────────────────────
function shouldShowButton(btnKey: string, status: string): boolean {
  // ✅ Allow generate-draft also when DRAFT_READY (for re-generating after edits)
  if (btnKey === "generate-draft")
    return (
      status === "IN_REVIEW" ||
      status === "CHANGES_REQUESTED" ||
      status === "DRAFT_READY"
    );
  if (btnKey === "confirm") return status === "DRAFT_READY";
  if (btnKey === "request-changes") return status === "DRAFT_READY";
  return true; // view, edit, delete always show
}

// ═════════════════════════════════════════════════════════════════
// Component
// ═════════════════════════════════════════════════════════════════
export default function DynamicInquiryRow({
  row,
  visibleColumns,
  rowButtons,
  hasActionsColumn,
  mapColumnKeyToValue,
  isExpanded,
  isSelected,
  generating,
  toggleRowExpand,
  handleRowSelect,
  onAction,
}: Props) {
  const hasDraft = !!(row.draft_pdf_path || row.draft_docx_path);

  // ✅ NEW — Read documents off the row safely (may not be in type yet)
  const documents: InquiryDocument[] = ((row as any).documents ??
    []) as InquiryDocument[];

  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>
        {visibleColumns.map((col) => (
          <td key={col.key} className={styles.nameCell}>
            {renderCellValue(
              col,
              mapColumnKeyToValue(col.key, row),
              row,
              onAction,
              new Set(rowButtons.map((b) => b.key)),
            )}
          </td>
        ))}
        {hasActionsColumn && (
          <td className={styles.actionsCell}>
            <div className={styles.actionGroup}>
              {rowButtons.map((btn) => {
                if (!shouldShowButton(btn.key, row.status)) return null;
                const isGenerating = btn.key === "generate-draft" && generating;
                return (
                  <button
                    key={btn.key}
                    disabled={isGenerating}
                    className={
                      btn.key === "delete"
                        ? styles.actionBtnDelete
                        : btn.key === "edit"
                          ? styles.actionBtnEdit
                          : styles.actionBtnView
                    }
                    onClick={() => onAction(row, btn.key)}
                    title={btn.label || btn.key}
                    style={
                      !["view", "edit", "delete"].includes(btn.key)
                        ? { color: btn.color, borderColor: `${btn.color}33` }
                        : undefined
                    }
                  >
                    {isGenerating
                      ? "⏳"
                      : iconMap[btn.key] || (
                          <span style={{ fontSize: 14 }}>{btn.icon}</span>
                        )}
                  </button>
                );
              })}
            </div>
          </td>
        )}
      </tr>

      {/* ── Expanded panel ──────────────────────────────────────── */}
      {isExpanded && (
        <tr className={styles.expandedRow}>
          <td colSpan={visibleColumns.length + 3 + (hasActionsColumn ? 1 : 0)}>
            <div className={styles.expandedContent}>
              <div className={styles.detailPanel}>
                <div className={styles.panelHeader}>
                  Inquiry Details — {row.inquiry_ref}
                </div>

                {/* ✅ MOVED TO TOP — Action buttons (Generate Draft, Download, etc) */}
                <div
                  style={{
                    display: "flex",
                    flexWrap: "wrap",
                    alignItems: "center",
                    gap: 8,
                    padding: "12px 16px",
                    backgroundColor: "#f8fafc",
                    border: "1px solid #e2e8f0",
                    borderRadius: 10,
                    marginBottom: 16,
                  }}
                >
                  <span
                    style={{
                      fontSize: 11,
                      fontWeight: 700,
                      color: "#64748b",
                      textTransform: "uppercase",
                      letterSpacing: "0.05em",
                      marginRight: 4,
                    }}
                  >
                    ⚡ Quick Actions:
                  </span>

                  {/* Workflow buttons (edit, generate-draft, confirm, request-changes, delete) */}
                  {rowButtons.map((btn) => {
                    if (!shouldShowButton(btn.key, row.status)) return null;
                    const isGenerating =
                      btn.key === "generate-draft" && generating;
                    return (
                      <button
                        key={btn.key}
                        disabled={isGenerating}
                        className={
                          btn.key === "delete"
                            ? styles.dangerBtn
                            : btn.key === "edit"
                              ? styles.secondaryBtn
                              : styles.primaryBtn
                        }
                        onClick={() => onAction(row, btn.key)}
                        style={
                          !["view", "edit", "delete"].includes(btn.key)
                            ? { backgroundColor: btn.color }
                            : undefined
                        }
                      >
                        {isGenerating
                          ? "⏳"
                          : iconMap[btn.key] || (
                              <span style={{ fontSize: 16 }}>{btn.icon}</span>
                            )}{" "}
                        {btn.label || btn.key}
                      </button>
                    );
                  })}

                  {/* Download PDF / Word if draft exists */}
                  {/* Download PDF / Word if draft exists */}
                  {hasDraft && (
                    <>
                      <button
                        className={styles.primaryBtn}
                        onClick={() =>
                          downloadDraftFile(
                            row.id,
                            "pdf",
                            row.inquiry_ref,
                            (row as any).draft_generated_at, // ✅ NEW — cache-bust
                          )
                        }
                        style={{ backgroundColor: "#10b981" }}
                      >
                        <FiDownload size={14} /> Download PDF
                      </button>
                      <button
                        className={styles.primaryBtn}
                        onClick={() =>
                          downloadDraftFile(
                            row.id,
                            "docx",
                            row.inquiry_ref,
                            (row as any).draft_generated_at, // ✅ NEW — cache-bust
                          )
                        }
                        style={{ backgroundColor: "#3b82f6" }}
                      >
                        <FiDownload size={14} /> Download Word
                      </button>
                    </>
                  )}
                </div>

                {/* Inquiry Information */}
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>
                    Inquiry Information
                  </div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <FiFileText size={16} />
                      <span className={styles.label}>Reference</span>
                      <span
                        className={styles.value}
                        style={{ fontFamily: "monospace" }}
                      >
                        {row.inquiry_ref}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiFileText size={16} />
                      <span className={styles.label}>Type</span>
                      <span className={styles.value}>
                        <TypeBadge type={row.inquiry_type} />
                      </span>
                    </div>
                    {/* ✅ NEW — Certification Body */}
                    <div className={styles.definitionItem}>
                      <FiFileText size={16} />
                      <span className={styles.label}>Cert Body</span>
                      <span className={styles.value}>
                        {(row as any).cert_body ? (
                          <span
                            style={{
                              padding: "2px 10px",
                              borderRadius: 8,
                              fontSize: 11,
                              fontWeight: 700,
                              background:
                                (row as any).cert_body === "QRS"
                                  ? "#ede9fe"
                                  : "#cffafe",
                              color:
                                (row as any).cert_body === "QRS"
                                  ? "#6d28d9"
                                  : "#0e7490",
                            }}
                          >
                            {(row as any).cert_body === "QRS"
                              ? "🏢 QRS"
                              : "🏛 TQS"}
                          </span>
                        ) : (
                          "—"
                        )}
                      </span>
                    </div>

                    {/* ✅ NEW — Audit Stage */}
                    <div className={styles.definitionItem}>
                      <FiFileText size={16} />
                      <span className={styles.label}>Audit Stage</span>
                      <span className={styles.value}>
                        {(row as any).audit_stage ? (
                          <span
                            style={{
                              padding: "2px 10px",
                              borderRadius: 8,
                              fontSize: 11,
                              fontWeight: 600,
                              background: "#f5f3ff",
                              color: "#6d28d9",
                              border: "1px solid #ddd6fe",
                            }}
                          >
                            {(row as any).audit_stage}
                          </span>
                        ) : (
                          "—"
                        )}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiCalendar size={16} />
                      <span className={styles.label}>Audit Date</span>
                      <span className={styles.value}>
                        {formatDisplayDate(row.audit_date)}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiUser size={16} />
                      <span className={styles.label}>Auditor</span>
                      <span className={styles.value}>{row.auditor_name}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiFileText size={16} />
                      <span className={styles.label}>Prev. Cert No.</span>
                      <span className={styles.value}>
                        {row.previous_cert_no || "—"}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiFileText size={16} />
                      <span className={styles.label}>Status</span>
                      <span className={styles.value}>
                        <StatusBadge status={row.status} />
                      </span>
                    </div>
                  </div>
                </div>

                {/* Certificate Details */}
                {(row.certificate_number ||
                  row.issue_date ||
                  row.expiry_date) && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>
                      Certificate Details
                    </div>
                    <div className={styles.definitionGrid}>
                      <div className={styles.definitionItem}>
                        <FiFileText size={16} />
                        <span className={styles.label}>Certificate No.</span>
                        <span
                          className={styles.value}
                          style={{ fontFamily: "monospace" }}
                        >
                          {row.certificate_number || "—"}
                        </span>
                      </div>
                      <div className={styles.definitionItem}>
                        <FiCalendar size={16} />
                        <span className={styles.label}>Issue Date</span>
                        <span className={styles.value}>
                          {formatDisplayDate(row.issue_date)}
                        </span>
                      </div>
                      <div className={styles.definitionItem}>
                        <FiCalendar size={16} />
                        <span className={styles.label}>Expiry Date</span>
                        <span className={styles.value}>
                          {formatDisplayDate(row.expiry_date)}
                        </span>
                      </div>
                      <div className={styles.definitionItem}>
                        <FiFileText size={16} />
                        <span className={styles.label}>Accreditation</span>
                        <span className={styles.value}>
                          {row.accreditation_body || "—"}
                        </span>
                      </div>
                      {/* ✅ NEW */}
                      <div className={styles.definitionItem}>
                        <FiCalendar size={16} />
                        <span className={styles.label}>
                          Surv. Audit On/Before
                        </span>
                        <span className={styles.value}>
                          {formatDisplayDate(
                            (row as any).surveillance_audit_due,
                          )}
                        </span>
                      </div>
                      <div className={styles.definitionItem}>
                        <FiCalendar size={16} />
                        <span className={styles.label}>
                          Re-certification Due
                        </span>
                        <span className={styles.value}>
                          {formatDisplayDate((row as any).recertification_due)}
                        </span>
                      </div>
                    </div>
                  </div>
                )}

                {/* Scope */}
                {row.scope_of_work && row.scope_of_work !== "—" && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>Scope of Work</div>
                    <p
                      style={{
                        fontSize: 13,
                        color: "#374151",
                        whiteSpace: "pre-line",
                        padding: "0 4px",
                      }}
                    >
                      {row.scope_of_work}
                    </p>
                  </div>
                )}

                {/* Notes */}
                {row.notes && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>Notes</div>
                    <p
                      style={{
                        fontSize: 13,
                        color: "#374151",
                        whiteSpace: "pre-line",
                        padding: "0 4px",
                      }}
                    >
                      {row.notes}
                    </p>
                  </div>
                )}

                {/* Change request */}
                {row.change_request_notes && (
                  <div className={styles.panelSection}>
                    <div
                      className={styles.sectionTitleText}
                      style={{ color: "#991b1b" }}
                    >
                      ⚠️ Change Request Notes
                    </div>
                    <p
                      style={{
                        fontSize: 13,
                        color: "#991b1b",
                        whiteSpace: "pre-line",
                        padding: "8px 12px",
                        backgroundColor: "#fef2f2",
                        borderRadius: 6,
                      }}
                    >
                      {row.change_request_notes}
                    </p>
                  </div>
                )}

                {/* Standards */}
                {row.standards && row.standards.length > 0 && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>ISO Standards</div>
                    <div
                      style={{
                        display: "flex",
                        flexWrap: "wrap",
                        gap: 6,
                        marginTop: 6,
                      }}
                    >
                      {row.standards.map((s) => (
                        <span
                          key={s.id}
                          style={{
                            padding: "4px 12px",
                            borderRadius: 8,
                            fontSize: 12,
                            fontWeight: 600,
                            backgroundColor: "#dbeafe",
                            color: "#1e40af",
                          }}
                        >
                          {s.name}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {/* ✅ Supporting Documents */}
                {documents.length > 0 && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>
                      📎 Supporting Documents ({documents.length})
                    </div>
                    <div
                      style={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 6,
                        marginTop: 6,
                      }}
                    >
                      {documents.map((doc, idx) => (
                        <div
                          key={idx}
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 12,
                            padding: "8px 12px",
                            backgroundColor: "#f0fdfa",
                            border: "1px solid #99f6e4",
                            borderRadius: 8,
                            fontSize: 13,
                          }}
                        >
                          <FiPaperclip size={14} color="#0f766e" />
                          <span
                            style={{
                              fontSize: 11,
                              fontWeight: 700,
                              padding: "3px 8px",
                              borderRadius: 6,
                              backgroundColor: "#0f766e",
                              color: "#fff",
                              whiteSpace: "nowrap",
                            }}
                          >
                            {docTypeLabel(doc.type)}
                          </span>
                          <span
                            style={{
                              flex: 1,
                              color: "#0f766e",
                              fontWeight: 600,
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                              whiteSpace: "nowrap",
                            }}
                            title={doc.filename}
                          >
                            {doc.filename}
                          </span>
                          <span style={{ fontSize: 11, color: "#6b7280" }}>
                            {formatDisplayDate(doc.uploaded_at)}
                          </span>
                          <button
                            onClick={() => openDocument(doc.path)}
                            style={{
                              padding: "4px 12px",
                              borderRadius: 6,
                              border: "1px solid #99f6e4",
                              backgroundColor: "#fff",
                              color: "#0f766e",
                              cursor: "pointer",
                              fontSize: 12,
                              fontWeight: 600,
                              display: "inline-flex",
                              alignItems: "center",
                              gap: 4,
                            }}
                          >
                            <FiDownload size={12} /> Open
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Team */}
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Team</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <FiUser size={16} />
                      <span className={styles.label}>Submitted by</span>
                      <span className={styles.value}>
                        {row.submitted_by
                          ? `${row.submitted_by.firstName ?? ""} ${row.submitted_by.lastName ?? ""}`.trim()
                          : "—"}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiUser size={16} />
                      <span className={styles.label}>Assigned to</span>
                      <span className={styles.value}>
                        {row.assigned_to
                          ? `${row.assigned_to.firstName ?? ""} ${row.assigned_to.lastName ?? ""}`.trim()
                          : "Unassigned"}
                      </span>
                    </div>
                  </div>
                </div>

                {/* ✅ NOTE: Bottom action buttons removed — moved to TOP of panel */}
              </div>
            </div>
          </td>
        </tr>
      )}
    </>
  );
}
