"use client";

import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import { FiChevronRight, FiFileText, FiEye, FiEdit, FiTrash2, FiPrinter, FiDownload, FiExternalLink } from "react-icons/fi";
import { FaAward, FaFileAlt } from "react-icons/fa";
import { TemplateTypeBadge, StageBadge } from "./components/templates/TemplateTypeBadge";
import type { TemplateRow } from "@/lib/api/types/template.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:                 TemplateRow;
  visibleColumns:      ColumnConfig[];
  rowButtons:          ButtonConfig[];
  hasActionsColumn:    boolean;
  mapColumnKeyToValue: (key: string, row: TemplateRow) => any;
  isExpanded:          boolean;
  isSelected:          boolean;
  toggleRowExpand:     (sno: number) => void;
  handleRowSelect:     (sno: number, checked: boolean) => void;
  onAction:            (row: TemplateRow, 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: TemplateRow) {
  if (col.key === "stageName")    return <StageBadge stageName={value ?? ""} />;
  if (col.key === "templateType") return <TemplateTypeBadge templateType={value ?? ""} />;
  if (col.key === "isActive")
    return (
      <span style={{ padding: "3px 10px", borderRadius: "12px", fontSize: "11px", fontWeight: 600, backgroundColor: value ? "#d1fae5" : "#f3f4f6", color: value ? "#065f46" : "#6b7280" }}>
        {value ? "Active" : "Inactive"}
      </span>
    );
  if (col.key === "version")
    return <span style={{ fontFamily: "monospace", fontSize: "11px", background: "#f8fafc", border: "1px solid #e2e8f0", padding: "2px 7px", borderRadius: "4px", color: "#475569" }}>{value}</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 DynamicTemplateRow({
  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}>
              {/* Always show PDF preview */}
              <a href={row.url} target="_blank" rel="noreferrer" className={styles.actionBtnView} title="Preview 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}>Template Details</div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Template Information</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}><FiFileText size={18} /><span className={styles.label}>Name</span><span className={styles.value}>{row.name}</span></div>
                    <div className={styles.definitionItem}><FiFileText size={18} /><span className={styles.label}>Stage</span><span className={styles.value}><StageBadge stageName={row.stageName} size="md" /></span></div>
                    <div className={styles.definitionItem}><FiFileText size={18} /><span className={styles.label}>Type</span><span className={styles.value}><TemplateTypeBadge templateType={row.templateType} size="md" /></span></div>
                    <div className={styles.definitionItem}><FiFileText size={18} /><span className={styles.label}>Version</span><span className={styles.value} style={{ fontFamily: "monospace" }}>{row.version}</span></div>
                  </div>
                </div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>File Path</div>
                  <p style={{ fontSize: "12px", color: "#374151", fontFamily: "monospace", padding: "0 4px", wordBreak: "break-all" }}>{row.filePath}</p>
                </div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>PDF URL</div>
                  <p style={{ fontSize: "12px", color: "#374151", fontFamily: "monospace", padding: "0 4px", wordBreak: "break-all" }}>{row.url}</p>
                </div>
                <div className={styles.panelActions}>
                  <a href={row.url} 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>
      )}
    </>
  );
}
