"use client";

import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import {
  FiChevronRight,
  FiEye,
  FiEdit,
  FiTrash2,
  FiFileText,
  FiUser,
  FiCalendar,
  FiDownload,
} 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 Props {
  row: InquiryRowType;
  isExpanded: boolean;
  isSelected: boolean;
  generating?: boolean;
  toggleRowExpand: (sno: number) => void;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onEdit: (row: InquiryRowType) => void;
  onDelete: (row: InquiryRowType) => void;
  onView: (row: InquiryRowType) => void;
  onGenerate?: (row: InquiryRowType) => void;
  onConfirm?: (row: InquiryRowType) => void;
  onRequestChanges?: (row: InquiryRowType) => void;
}

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>
  );
}

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 InquiryRow({
  row,
  isExpanded,
  isSelected,
  generating,
  toggleRowExpand,
  handleRowSelect,
  onEdit,
  onDelete,
  onView,
  onGenerate,
  onConfirm,
  onRequestChanges,
}: Props) {
  const hasDraft = !!(row.draft_pdf_path || row.draft_docx_path);

  // ✅ NEW — statuses where Scheme should be allowed to (re)generate the draft
  // Includes DRAFT_READY so after editing certificate details, Scheme can refresh the draft
  const canGenerate =
    row.status === "IN_REVIEW" ||
    row.status === "CHANGES_REQUESTED" ||
    row.status === "DRAFT_READY";

  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}>
          <span
            style={{ fontFamily: "monospace", fontSize: 12, color: "#6b7280" }}
          >
            {row.inquiry_ref}
          </span>
        </td>
        <td className={styles.nameCell}>
          <TypeBadge type={row.inquiry_type} />
        </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.auditor_name}
          </div>
          <div style={{ fontSize: 11, color: "#9ca3af" }}>
            {formatDisplayDate(row.audit_date)}
          </div>
        </td>
        {/* <td className={styles.nameCell}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
            {row.standards?.map(s => (
              <span key={s.id} style={{ padding: '2px 7px', borderRadius: 6, fontSize: 10, fontWeight: 600, backgroundColor: '#dbeafe', color: '#1e40af' }}>{s.name}</span>
            ))}
            {!row.standards?.length && <span style={{ color: '#9ca3af', fontSize: 12 }}>—</span>}
          </div>
        </td> */}
        <td className={styles.nameCell}>
          <StatusBadge status={row.status} />
        </td>
        <td className={styles.nameCell}>
          <span style={{ fontSize: 12, color: "#6b7280" }}>
            {row.submitted_by
              ? `${row.submitted_by.firstName} ${row.submitted_by.lastName}`.trim()
              : "—"}
          </span>
        </td>
        <td className={styles.actionsCell}>
          <div className={styles.actionGroup}>
            <button
              className={styles.actionBtnView}
              onClick={() => onView(row)}
              title="View"
            >
              {" "}
              <FiEye size={14} />
            </button>
            <button
              className={styles.actionBtnEdit}
              onClick={() => onEdit(row)}
              title="Edit"
            >
              {" "}
              <FiEdit size={14} />
            </button>
            <button
              className={styles.actionBtnDelete}
              onClick={() => onDelete(row)}
              title="Delete"
            >
              {" "}
              <FiTrash2 size={14} />
            </button>
          </div>
        </td>
      </tr>

      {isExpanded && (
        <tr className={styles.expandedRow}>
          <td colSpan={10}>
            <div className={styles.expandedContent}>
              <div className={styles.detailPanel}>
                {/* ✅ ACTION BAR — top of expanded panel, left aligned ──── */}
                <div
                  style={{
                    display: "flex",
                    flexWrap: "wrap",
                    alignItems: "center",
                    gap: 8,
                    padding: "12px 20px",
                    backgroundColor: "#f8fafc",
                    borderBottom: "2px solid #e5e7eb",
                    marginBottom: 0,
                  }}
                >
                  {/* Edit */}
                  <button
                    onClick={() => onEdit(row)}
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 5,
                      padding: "7px 14px",
                      borderRadius: 8,
                      border: "1px solid #d1d5db",
                      backgroundColor: "#fff",
                      color: "#374151",
                      cursor: "pointer",
                      fontSize: 12,
                      fontWeight: 600,
                    }}
                  >
                    <FiEdit size={13} /> Edit Inquiry
                  </button>

                  {/* ✅ UPDATED — Generate / Re-generate Draft (also shows when DRAFT_READY) */}
                  {canGenerate && onGenerate && (
                    <button
                      onClick={() => onGenerate(row)}
                      disabled={generating}
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 5,
                        padding: "7px 14px",
                        borderRadius: 8,
                        border: "1px solid #fcd34d",
                        backgroundColor: generating ? "#fef9c3" : "#fef3c7",
                        color: "#92400e",
                        cursor: generating ? "not-allowed" : "pointer",
                        fontSize: 12,
                        fontWeight: 700,
                      }}
                    >
                      {generating
                        ? "⏳ Generating..."
                        : row.status === "DRAFT_READY"
                          ? "🔄 Re-generate Draft"
                          : "📄 Generate Draft"}
                    </button>
                  )}

                  {/* ✅ UPDATED — Cert No warning (also shows when DRAFT_READY missing cert no.) */}
                  {canGenerate && !row.certificate_number && (
                    <span
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 5,
                        padding: "6px 12px",
                        borderRadius: 8,
                        backgroundColor: "#fef2f2",
                        border: "1px solid #fecaca",
                        color: "#ef4444",
                        fontSize: 11,
                        fontWeight: 600,
                      }}
                    >
                      ⚠️ Edit first — fill Certificate No., dates &amp; scope
                    </span>
                  )}

                  {/* Download PDF */}
                  {hasDraft && (
                    <button
                      onClick={() =>
                        downloadFile(
                          getDraftPdfUrl(
                            row.id,
                            (row as any).draft_generated_at,
                          ),
                          `${row.inquiry_ref}_DRAFT.pdf`,
                        )
                      }
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 5,
                        padding: "7px 14px",
                        borderRadius: 8,
                        border: "1px solid #a7f3d0",
                        backgroundColor: "#f0fdf4",
                        color: "#065f46",
                        cursor: "pointer",
                        fontSize: 12,
                        fontWeight: 600,
                      }}
                    >
                      <FiDownload size={13} /> Download PDF
                    </button>
                  )}

                  {/* Download Word */}
                  {hasDraft && (
                    <button
                      onClick={() =>
                        downloadFile(
                          getDraftDocxUrl(
                            row.id,
                            (row as any).draft_generated_at,
                          ),
                          `${row.inquiry_ref}_DRAFT.docx`,
                        )
                      }
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 5,
                        padding: "7px 14px",
                        borderRadius: 8,
                        border: "1px solid #bfdbfe",
                        backgroundColor: "#eff6ff",
                        color: "#1e40af",
                        cursor: "pointer",
                        fontSize: 12,
                        fontWeight: 600,
                      }}
                    >
                      <FiDownload size={13} /> Download Word
                    </button>
                  )}

                  {/* Client Confirmed */}
                  {row.status === "DRAFT_READY" && onConfirm && (
                    <button
                      onClick={() => onConfirm(row)}
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 5,
                        padding: "7px 14px",
                        borderRadius: 8,
                        border: "none",
                        backgroundColor: "#10b981",
                        color: "#fff",
                        cursor: "pointer",
                        fontSize: 12,
                        fontWeight: 700,
                      }}
                    >
                      ✅ Client Confirmed
                    </button>
                  )}

                  {/* Request Changes */}
                  {row.status === "DRAFT_READY" && onRequestChanges && (
                    <button
                      onClick={() => onRequestChanges(row)}
                      style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 5,
                        padding: "7px 14px",
                        borderRadius: 8,
                        border: "1px solid #fca5a5",
                        backgroundColor: "#fef2f2",
                        color: "#991b1b",
                        cursor: "pointer",
                        fontSize: 12,
                        fontWeight: 600,
                      }}
                    >
                      ↩ Request Changes
                    </button>
                  )}

                  {/* Delete — pushed far right */}
                  <button
                    onClick={() => onDelete(row)}
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 5,
                      padding: "7px 14px",
                      borderRadius: 8,
                      border: "1px solid #fecaca",
                      backgroundColor: "#fff5f5",
                      color: "#dc2626",
                      cursor: "pointer",
                      fontSize: 12,
                      fontWeight: 600,
                      marginLeft: "auto",
                    }}
                  >
                    <FiTrash2 size={13} /> Delete
                  </button>
                </div>

                {/* ── Panel header ────────────────────────────────────────── */}
                <div className={styles.panelHeader}>
                  Inquiry Details — {row.inquiry_ref}
                </div>

                {/* ── Inquiry info ─────────────────────────────────────────── */}
                <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>
                    <div className={styles.definitionItem}>
                      <FiCalendar size={16} />
                      <span className={styles.label}>Audit Date</span>
                      <span className={styles.value}>
                        {formatDisplayDate(row.audit_date)}
                      </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}>
                      <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 ||
                  (row as any).surveillance_audit_due ||
                  (row as any).recertification_due) && (
                  <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 — Surveillance Audit Due */}
                      <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>
                      {/* ✅ NEW — Re-certification Due */}
                      <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 notes ───────────────────────────────── */}
                {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?.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>
                )}

                {/* ── 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>
              </div>
            </div>
          </td>
        </tr>
      )}
    </>
  );
}
