"use client";

import React from "react";
import styles from "../commonstyle/dattabale.module.css";
import {
  FiChevronRight, FiEye, FiEdit, FiTrash2,
  FiPrinter, FiDownload, FiUser, FiCalendar, FiFileText,
} from "react-icons/fi";
import { getStatusBadge } from "./CompanyAuditFilters";
import type { CompanyAuditRow } from "@/lib/api/types/companyAudit.types";

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

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

const iconMap: Record<string, React.ReactNode> = {
  view:   <FiEye      size={14} />,
  edit:   <FiEdit     size={14} />,
  delete: <FiTrash2   size={14} />,
  export: <FiDownload size={14} />,
  print:  <FiPrinter  size={14} />,
};

// ✅ NEW — Stage color map (Stage 1 / Stage 2 / Surveillance / Recertification)
function getStageBadgeStyle(stage: string): { bg: string; text: string } {
  const s = String(stage || "").toLowerCase();
  if (s.includes("recertification"))             return { bg: "#fef3c7", text: "#92400e" };
  if (s.includes("surveillance"))                return { bg: "#dbeafe", text: "#1e40af" };
  if (s.includes("stage 2") || s.includes("stage2")) return { bg: "#dcfce7", text: "#166534" };
  if (s.includes("stage 1") || s.includes("stage1")) return { bg: "#f5f3ff", text: "#6d28d9" };
  return { bg: "#f3f4f6", text: "#6b7280" };
}

function renderCellValue(col: ColumnConfig, value: any, row?: CompanyAuditRow) {
  if (col.key === "status") return getStatusBadge(value);

  if (col.key === "auditStage") {
    // ✅ UPDATED — colored badge per stage type
    const v =
      (value && value !== "—" ? value : null) ||
      ((row as any)?.auditStage && (row as any).auditStage !== "—" ? (row as any).auditStage : null);
    const c = getStageBadgeStyle(v);
    return (
      <span style={{
        padding: "3px 10px", borderRadius: 12, fontSize: 11, fontWeight: 600,
        background: c.bg, color: c.text,
      }}>
        {v || "—"}
      </span>
    );
  }

  // ✅ Audit By — read what the mapper produced (which now reads stages[].auditBy)
  if (col.key === "auditBy") {
    const v =
      (value && value !== "—" ? value : null) ||
      (row?.auditBy && row.auditBy !== "—" ? row.auditBy : null) ||
      (row?.leadAuditor && row.leadAuditor !== "—" ? row.leadAuditor : null);
    return v || "—";
  }

  // Audit Type
  if (col.key === "auditType") {
    const v =
      (value && value !== "—" ? value : null) ||
      ((row as any)?.auditType && (row as any).auditType !== "—" ? (row as any).auditType : null);
    return v ? (
      <span style={{ padding: "3px 10px", borderRadius: 12, fontSize: 11, fontWeight: 600, background: "#f5f3ff", color: "#6d28d9" }}>
        {v}
      </span>
    ) : "—";
  }

  // Audit Mode
  if (col.key === "auditMode") {
    const v =
      (value && value !== "—" ? value : null) ||
      ((row as any)?.auditMode && (row as any).auditMode !== "—" ? (row as any).auditMode : null);
    return v ? (
      <span style={{ padding: "3px 10px", borderRadius: 12, fontSize: 11, fontWeight: 600, background: "#eff6ff", color: "#1d4ed8" }}>
        {v}
      </span>
    ) : "—";
  }

  // Audit Year
  if (col.key === "auditYear") {
    const v =
      (value && value !== "—" ? value : null) ||
      ((row as any)?.auditYear && (row as any).auditYear !== "—" ? (row as any).auditYear : null);
    return v ? <span style={{ color: "#6b7280", fontSize: 13 }}>{v}</span> : "—";
  }

  if (col.type === "date" && value && value !== "—") {
    try {
      return new Date(value)
        .toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })
        .replace(/ /g, "-");
    } catch { return value; }
  }
  return value ?? "—";
}

export default function DynamicCompanyAuditRow({
  row, visibleColumns, rowButtons, hasActionsColumn,
  mapColumnKeyToValue, isExpanded, isSelected,
  toggleRowExpand, handleRowSelect, onAction,
}: Props) {
  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)}
          </td>
        ))}

        {hasActionsColumn && (
          <td className={styles.actionsCell}>
            <div className={styles.actionGroup}>
              {rowButtons.map((btn) => (
                <button
                  key={btn.key}
                  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}
                >
                  {iconMap[btn.key] || <span style={{ fontSize: 14 }}>{btn.icon}</span>}
                </button>
              ))}
            </div>
          </td>
        )}
      </tr>

      {/* ── Expanded detail 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}>Audit Details</div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Audit Information</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}><FiFileText size={18} /><span className={styles.label}>Company</span><span className={styles.value}>{row.companyName}</span></div>
                    <div className={styles.definitionItem}><FiFileText size={18} /><span className={styles.label}>Audit Stage</span><span className={styles.value}>{row.auditStage}</span></div>
                    <div className={styles.definitionItem}><FiUser     size={18} /><span className={styles.label}>Lead Auditor</span><span className={styles.value}>{row.leadAuditor}</span></div>
                    <div className={styles.definitionItem}><FiCalendar size={18} /><span className={styles.label}>Audit Date</span><span className={styles.value}>{row.auditDate}</span></div>
                    <div className={styles.definitionItem}><FiFileText size={18} /><span className={styles.label}>Status</span><span className={styles.value}>{getStatusBadge(row.status)}</span></div>

                    <div className={styles.definitionItem}>
                      <FiUser size={18} />
                      <span className={styles.label}>Audit By</span>
                      <span className={styles.value}>
                        {row.auditBy ?? row.leadAuditor ?? "—"}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiFileText size={18} />
                      <span className={styles.label}>Audit Type</span>
                      <span className={styles.value}>
                        {(row as any)?.auditType ?? row.auditStage ?? "—"}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiFileText size={18} />
                      <span className={styles.label}>Audit Mode</span>
                      <span className={styles.value}>
                        {(row as any)?.auditMode ?? "—"}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiCalendar size={18} />
                      <span className={styles.label}>Audit Year</span>
                      <span className={styles.value}>
                        {(row as any)?.auditYear ?? "—"}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiCalendar size={18} />
                      <span className={styles.label}>Created At</span>
                      <span className={styles.value}>
                        {(row as any)?.createdAt ?? (row as any)?.created_at ?? "—"}
                      </span>
                    </div>
                  </div>
                </div>
                {row.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>
                )}
                {row.findings && row.findings !== "—" && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>Findings</div>
                    <p style={{ fontSize: 13, color: "#374151", whiteSpace: "pre-line", padding: "0 4px" }}>{row.findings}</p>
                  </div>
                )}
                <div className={styles.panelActions}>
                  {rowButtons.map((btn) => (
                    <button
                      key={btn.key}
                      className={btn.key === "delete" ? styles.dangerBtn : styles.secondaryBtn}
                      onClick={() => onAction(row, btn.key)}
                    >
                      {iconMap[btn.key] || <span style={{ fontSize: 16 }}>{btn.icon}</span>}
                      {" "}{btn.label || btn.key}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </td>
        </tr>
      )}
    </>
  );
}