"use client";
import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import { FiChevronRight, FiUser, FiMail, FiPhone, FiMapPin, FiFileText, FiEye, FiEdit, FiTrash2 } from "react-icons/fi";
import { BsFillBuildingFill } from "react-icons/bs";
import { StandardsBadge } from "./components/companies/StandardsBadge";
import type { CompanyRow as CompanyRowType } from "@/lib/api/types/company.types";

interface Props {
  row: CompanyRowType;
  isExpanded: boolean;
  isSelected: boolean;
  toggleRowExpand: (sno: number) => void;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onEdit: (row: CompanyRowType) => void;
  onDelete: (row: CompanyRowType) => void;
  onView: (row: CompanyRowType) => void;
  // ✅ NEW — flag indicating this row is freshly added
  isNew?: boolean;
}

// ✅ NEW — Client Group badge (mirrors the badge used in DynamicCompanyRow)
function ClientGroupBadge({ value }: { value?: string }) {
  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" },
  };
  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>
  );
}

export function CompanyRow({ row, isExpanded, isSelected, toggleRowExpand, handleRowSelect, onEdit, onDelete, onView, isNew }: Props) {
  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>

        <td className={styles.nameCell}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "nowrap" }}>
            <span style={{ fontFamily: "monospace", fontSize: "12px", color: "#6b7280" }}>
              {row.company_code}
            </span>

            {/* ✅ NEW — green NEW chip for freshly added companies */}
            {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 style={{ display: "inline-flex", gap: 4, marginLeft: 4 }}>
              <button onClick={() => onView(row)} 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>
              <button onClick={() => onEdit(row)} 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>
            </div>
          </div>
        </td>

        {/* ✅ NEW — Client Group column, directly after Code */}
        <td className={styles.nameCell}><ClientGroupBadge value={row.client_group} /></td>

        <td className={styles.nameCell}><div style={{ fontWeight: 600, fontSize: "13px" }}>{row.name}</div></td>
        <td className={styles.nameCell}><span style={{ color: "#6b7280", fontSize: "13px" }}>{row.city?.trim() || "—"}</span></td>
        <td className={styles.nameCell}><div style={{ fontWeight: 500, fontSize: "13px" }}>{row.contact_person}</div><div style={{ fontSize: "11px", color: "#9ca3af" }}>{row.designation}</div></td>
        <td className={styles.nameCell}><StandardsBadge standards={row.standards} /></td>
        <td className={styles.nameCell}><span style={{ padding: "3px 10px", borderRadius: "12px", fontSize: "11px", fontWeight: 600, backgroundColor: row.validity ? "#d1fae5" : "#f3f4f6", color: row.validity ? "#065f46" : "#6b7280" }}>{row.validity || "—"}</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}>
                <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}>Company 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}>Certification 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 Details</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}>
                  <button className={styles.secondaryBtn} onClick={() => onEdit(row)}><FiEdit size={14} /> Edit Company</button>
                  <button className={styles.dangerBtn} onClick={() => onDelete(row)}><FiTrash2 size={14} /> Delete</button>
                </div>
              </div>
            </div>
          </td>
        </tr>
      )}
    </>
  );
}