"use client";

import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import { FiChevronRight, FiEye, FiEdit, FiTrash2, FiPrinter, FiDownload, FiExternalLink, FiCalendar, FiUser, FiFileText } from "react-icons/fi";
import { BsFillBuildingFill } from "react-icons/bs";
import { StageBadge, RiskBadge, ScheduleBadge, StandardsBadge } from "./components/jobs/JobBadge";
import type { JobRow } from "@/lib/api/types/job.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:                 JobRow;
  visibleColumns:      ColumnConfig[];
  rowButtons:          ButtonConfig[];
  hasActionsColumn:    boolean;
  mapColumnKeyToValue: (key: string, row: JobRow) => any;
  isExpanded:          boolean;
  isSelected:          boolean;
  toggleRowExpand:     (sno: number) => void;
  handleRowSelect:     (sno: number, checked: boolean) => void;
  onAction:            (row: JobRow, 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} />,
};

function renderCellValue(col: ColumnConfig, value: any, row: JobRow) {
  if (col.key === "stage")        return <StageBadge stage={value ?? ""} />;
  if (col.key === "mdRisk")       return <RiskBadge risk={value ?? ""} />;
  if (col.key === "scheduleSlot") return <ScheduleBadge slot={value ?? ""} />;
  if (col.key === "standards")    return <StandardsBadge standards={value ?? []} />;
  if (col.key === "jobCodesStr")
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        {(row.jobCodes || []).slice(0, 2).map((c, i) => (
          <span key={i} style={{ fontFamily: "monospace", fontSize: "10px", background: "#f8fafc", border: "1px solid #e2e8f0", padding: "1px 5px", borderRadius: "4px", color: "#475569" }}>{c}</span>
        ))}
        {row.jobCodes?.length > 2 && <span style={{ fontSize: "10px", color: "#94a3b8" }}>+{row.jobCodes.length - 2} more</span>}
      </div>
    );
  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 DynamicJobRow({ 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}>
              {row.pdfUrl && (
                <a href={row.pdfUrl} target="_blank" rel="noreferrer" className={styles.actionBtnView} title="View PDF"><FiEye size={14} /></a>
              )}
              {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>

      {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}>Job Details — #{row.id}</div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Company</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}><BsFillBuildingFill size={18} /><span className={styles.label}>Company</span><span className={styles.value}>{row.companyName}</span></div>
                    <div className={styles.definitionItem}><FiCalendar size={18} /><span className={styles.label}>Stage</span><span className={styles.value}><StageBadge stage={row.stage} size="md" /></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}>Date</span><span className={styles.value}>{row.date}</span></div>
                  </div>
                </div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Job Codes</div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: "6px", marginTop: 6 }}>
                    {row.jobCodes.map((code, i) => (
                      <span key={i} style={{ fontFamily: "monospace", fontSize: "12px", background: "#f1f5f9", border: "1px solid #e2e8f0", padding: "3px 8px", borderRadius: "6px", color: "#334155" }}>{code}</span>
                    ))}
                  </div>
                </div>
                {row.standards?.length > 0 && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>ISO Standards</div>
                    <div style={{ marginTop: 8 }}><StandardsBadge standards={row.standards} size="md" /></div>
                  </div>
                )}
                <div className={styles.panelActions}>
                  {row.pdfUrl && (
                    <a href={row.pdfUrl} target="_blank" rel="noreferrer" className={styles.primaryBtn} style={{ display: "inline-flex", alignItems: "center", gap: 6, textDecoration: "none" }}>
                      <FiExternalLink size={14} /> Open PDF
                    </a>
                  )}
                  {rowButtons.map((btn) => (
                    <button key={btn.key}
                      className={btn.key === "delete" ? styles.dangerBtn : btn.key === "edit" ? styles.secondaryBtn : styles.primaryBtn}
                      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>
      )}
    </>
  );
}
