"use client";

import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import {
  FiChevronRight,
  FiUser,
  FiMail,
  FiPhone,
  FiMapPin,
  FiFileText,
  FiEye,
  FiEdit,
  FiTrash2,
  FiPrinter,
  FiDownload,
   FiUserPlus,
} from "react-icons/fi";
import { BsFillBuildingFill } from "react-icons/bs";
import { StandardsBadge } from "./components/companies/StandardsBadge";
import type { CompanyRow } from "@/lib/api/types/company.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: CompanyRow;
  visibleColumns: ColumnConfig[];
  rowButtons: ButtonConfig[];
  hasActionsColumn: boolean;
  mapColumnKeyToValue: (key: string, row: CompanyRow) => any;
  isExpanded: boolean;
  isSelected: boolean;
  toggleRowExpand: (sno: number) => void;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onAction: (row: CompanyRow, actionKey: string) => void;
  // ✅ NEW — flag indicating this row is freshly added
  isNew?: boolean;
}

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} />,
  invite_client: <FiUserPlus size={14} />,
};

function renderCellValue(col: ColumnConfig, value: any) {
  if (col.key === "standards")
    return <StandardsBadge standards={value ?? []} />;

  // ✅ NEW — Client Group badge with color per group
  if (col.key === "client_group") {
    if (!value || value === "—") return <span style={{ color: "#9ca3af" }}>—</span>;
    const colorMap: Record<string, { bg: string; text: string; border: string }> = {
      QRS:            { bg: "#dbeafe", text: "#1e40af", border: "#93c5fd" },
      TQS:            { bg: "#fef3c7", text: "#92400e", border: "#fcd34d" },
      QRS_B:          { bg: "#ede9fe", text: "#5b21b6", border: "#c4b5fd" },
      "QRS TEAM A":   { bg: "#e0e7ff", text: "#3730a3", border: "#a5b4fc" },
      "QRS TEAM B":   { bg: "#ede9fe", text: "#5b21b6", border: "#c4b5fd" },
      Overseas:       { bg: "#d1fae5", text: "#065f46", border: "#6ee7b7" },
    };
    // friendly labels for the raw audit-request enum values
    const labelMap: Record<string, string> = { QRS_B: "QRS-B" };
    const label = labelMap[value] ?? value;
    const c = colorMap[value] || { bg: "#f3f4f6", text: "#4b5563", border: "#d1d5db" };
    return (
      <span
        style={{
          display: "inline-block",
          padding: "3px 10px",
          borderRadius: "999px",
          fontSize: "11px",
          fontWeight: 700,
          backgroundColor: c.bg,
          color: c.text,
          border: `1px solid ${c.border}`,
          letterSpacing: "0.02em",
          whiteSpace: "nowrap",
        }}
      >
        {label}
      </span>
    );
  }

  if (col.key === "validity")
    return (
      <span
        style={{
          padding: "3px 10px",
          borderRadius: "12px",
          fontSize: "11px",
          fontWeight: 600,
          backgroundColor: value && value !== "—" ? "#d1fae5" : "#f3f4f6",
          color: value && value !== "—" ? "#065f46" : "#6b7280",
        }}
      >
        {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 DynamicCompanyRow({
  row,
  visibleColumns,
  rowButtons,
  hasActionsColumn,
  mapColumnKeyToValue,
  isExpanded,
  isSelected,
  toggleRowExpand,
  handleRowSelect,
  onAction,
  isNew, // ✅ NEW
}: Props) {
  const canView = rowButtons.some((b) => b.key === "view");
  const canEdit = rowButtons.some((b) => b.key === "edit");

  return (
    <>
      <tr
        className={`${styles.tableRow} ${isSelected ? styles.selectedRow : ""} ${
          isNew ? "qrs-new-row" : ""
        }`}
      >
        <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) => {
          if (col.key === "company_code") {
            return (
              <td key={col.key} className={styles.nameCell}>
                <div
                  style={{
                    display: "flex",
                    flexDirection: "column", // ✅ stack vertically
                    gap: 4,
                    minWidth: 180, // ✅ ensure enough room for icons
                  }}
                >
                  {/* ─── Row 1: Code + NEW chip ─── */}
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                      flexWrap: "wrap", // ✅ allow wrap if needed
                    }}
                  >
                    <span
                      style={{
                        fontFamily: "monospace",
                        fontSize: "12px",
                        color: "#6b7280",
                      }}
                    >
                      {row.company_code}
                    </span>

                    {isNew && (
                      <span
                        style={{
                          fontSize: 9,
                          fontWeight: 800,
                          color: "#fff",
                          background: "#16a34a",
                          padding: "2px 6px",
                          borderRadius: 4,
                          letterSpacing: ".05em",
                          whiteSpace: "nowrap",
                        }}
                        title="Recently added"
                      >
                        ✨ NEW
                      </span>
                    )}
                  </div>

                  {/* ─── Row 2: Action icons (always on their own line) ─── */}
                  <div style={{ display: "inline-flex", gap: 4 }}>
                    {canView && (
                      <button
                        onClick={() => onAction(row, "view")}
                        title="View Details"
                        style={{
                          width: 24,
                          height: 24,
                          display: "inline-flex",
                          alignItems: "center",
                          justifyContent: "center",
                          background: "#eff6ff",
                          border: "1px solid #bfdbfe",
                          borderRadius: 6,
                          color: "#1d4ed8",
                          cursor: "pointer",
                          padding: 0,
                        }}
                      >
                        <FiEye size={13} />
                      </button>
                    )}
                    {canEdit && (
                      <button
                        onClick={() => onAction(row, "edit")}
                        title="Edit Company"
                        style={{
                          width: 24,
                          height: 24,
                          display: "inline-flex",
                          alignItems: "center",
                          justifyContent: "center",
                          background: "#fef3c7",
                          border: "1px solid #fcd34d",
                          borderRadius: 6,
                          color: "#b45309",
                          cursor: "pointer",
                          padding: 0,
                        }}
                      >
                        <FiEdit size={13} />
                      </button>
                    )}
                    <button
                      onClick={() => onAction(row, "scope_summary")}
                      title="Generate Scope Summary Report"
                      style={{
                        width: 24,
                        height: 24,
                        display: "inline-flex",
                        alignItems: "center",
                        justifyContent: "center",
                        background: "#ede9fe",
                        border: "1px solid #c4b5fd",
                        borderRadius: 6,
                        color: "#7c3aed",
                        cursor: "pointer",
                        padding: 0,
                      }}
                    >
                      <FiFileText size={13} />
                    </button>
                  </div>
                </div>
              </td>
            );
          }
          return (
            <td key={col.key} className={styles.nameCell}>
              {renderCellValue(col, mapColumnKeyToValue(col.key, 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>
      {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}>Company Details</div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>
                    Company Information
                  </div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <BsFillBuildingFill 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}>Code</span>
                      <span
                        className={styles.value}
                        style={{ fontFamily: "monospace" }}
                      >
                        {row.company_code}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiFileText size={18} />
                      <span className={styles.label}>Cert. Body</span>
                      <span className={styles.value}>
                        {row.certification_body || "—"}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiFileText size={18} />
                      <span className={styles.label}>Validity</span>
                      <span className={styles.value}>
                        {row.validity || "—"}
                      </span>
                    </div>
                  </div>
                </div>
                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Contact</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <FiUser size={18} />
                      <span className={styles.label}>Contact</span>
                      <span className={styles.value}>
                        {row.contact_person}
                        {row.designation ? ` · ${row.designation}` : ""}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiMail size={18} />
                      <span className={styles.label}>Email</span>
                      <span className={styles.value}>{row.email}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiPhone size={18} />
                      <span className={styles.label}>Mobile</span>
                      <span className={styles.value}>{row.mobile}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiMapPin size={18} />
                      <span className={styles.label}>City</span>
                      <span className={styles.value}>
                        {row.city?.trim() || "—"}
                      </span>
                    </div>
                  </div>
                </div>
                {row.scope_of_work && (
                  <div className={styles.panelSection}>
                    <div className={styles.sectionTitleText}>Scope of Work</div>
                    <p
                      style={{
                        fontSize: "13px",
                        color: "#374151",
                        whiteSpace: "pre-line",
                        padding: "0 4px",
                      }}
                    >
                      {row.scope_of_work.trim()}
                    </p>
                  </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}>
                  {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>
      )}
    </>
  );
}