import type { Employee, Initiative, MarketingLocation, MarketingRole } from "@/lib/marketing";
import {
  formatDate,
  getStatusPillClass,
  INITIATIVE_STATUS_LABELS,
  INITIATIVE_TYPE_LABELS,
  MARKETING_ROLE_LABELS,
} from "@/lib/marketing/labels";

type InitiativeTableProps = {
  initiatives: Initiative[];
  scoresById: Record<string, number>;
  employeesById: Record<string, Employee>;
  locationsById: Record<string, MarketingLocation>;
  selectedInitiativeId: string | null;
  role: MarketingRole;
  isCreatingInitiative?: boolean;
  onSelectInitiative: (initiativeId: string) => void;
  onCreateInitiative?: () => void;
};

function locationScopeLabel(initiative: Initiative, locationsById: Record<string, MarketingLocation>): string {
  if (initiative.isGlobal) {
    return "Global (marca/negocio)";
  }

  const { locationIds } = initiative;
  const names = locationIds.map((locationId) => locationsById[locationId]?.name ?? locationId);
  if (names.length === 0) {
    return "Sin ubicación";
  }

  if (names.length <= 2) {
    return names.join(" + ");
  }

  return `${names.slice(0, 2).join(" + ")} +${names.length - 2}`;
}

function peopleLabel(initiative: Initiative, employeesById: Record<string, Employee>): string {
  const ownerName = employeesById[initiative.ownerId]?.name ?? "Sin dueño";
  const contributors = initiative.contributorIds
    .map((contributorId) => employeesById[contributorId]?.name)
    .filter((value): value is string => Boolean(value));

  if (contributors.length === 0) {
    return ownerName;
  }

  return `${ownerName} + ${contributors.length}`;
}

function targetActualLabel(initiative: Initiative): string {
  const chunks: string[] = [];
  if (initiative.metricSelection.score) {
    chunks.push(`${initiative.metrics.target} / ${initiative.metrics.actual} score`);
  }
  if (initiative.metricSelection.tickets) {
    chunks.push(`${initiative.metrics.ticketsTarget} / ${initiative.metrics.ticketsActual} tickets`);
  }
  if (initiative.metricSelection.revenue) {
    chunks.push(`${initiative.metrics.revenueTarget} / ${initiative.metrics.revenueActual} revenue`);
  }

  return chunks.join(" · ") || "Sin KPI seleccionado";
}

export default function InitiativeTable({
  initiatives,
  scoresById,
  employeesById,
  locationsById,
  selectedInitiativeId,
  role,
  isCreatingInitiative = false,
  onSelectInitiative,
  onCreateInitiative,
}: InitiativeTableProps) {
  const canCreate = (role === "lead" || role === "owner") && onCreateInitiative;

  return (
    <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
      <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
        <div>
          <h2 className="text-h2 font-semibold">Iniciativas</h2>
          <p className="text-label mt-1 text-benell-text-soft">
            Vista actual: {MARKETING_ROLE_LABELS[role]}. {role === "lead" || role === "owner" ? "Puedes editar en el detalle." : "Modo lectura."}
          </p>
        </div>
        {canCreate ? (
          <button
            type="button"
            onClick={onCreateInitiative}
            disabled={isCreatingInitiative}
            className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60"
          >
            {isCreatingInitiative ? "Creando..." : "Nueva iniciativa"}
          </button>
        ) : null}
      </div>

      <div className="overflow-x-auto">
        <table className="min-w-[1100px] w-full border-separate border-spacing-y-2">
          <thead>
            <tr className="text-left text-label text-benell-text-soft">
              <th className="px-3 py-1">Iniciativa</th>
              <th className="px-3 py-1">Tipo</th>
              <th className="px-3 py-1">Scope</th>
              <th className="px-3 py-1">Target vs Actual</th>
              <th className="px-3 py-1">Score</th>
              <th className="px-3 py-1">Status</th>
              <th className="px-3 py-1">Owner + Contributors</th>
              <th className="px-3 py-1">Due date</th>
            </tr>
          </thead>
          <tbody>
            {initiatives.map((initiative) => {
              const isSelected = selectedInitiativeId === initiative.id;
              return (
                <tr
                  key={initiative.id}
                  className={`cursor-pointer rounded-xl bg-white transition hover:bg-benell-surface-muted ${
                    isSelected ? "ring-2 ring-benell-brown" : ""
                  }`}
                  onClick={() => onSelectInitiative(initiative.id)}
                >
                  <td className="rounded-l-xl px-3 py-3 text-body font-semibold">{initiative.name}</td>
                  <td className="px-3 py-3 text-body">{INITIATIVE_TYPE_LABELS[initiative.type]}</td>
                  <td className="px-3 py-3 text-body">{locationScopeLabel(initiative, locationsById)}</td>
                  <td className="px-3 py-3 text-body text-tabular">{targetActualLabel(initiative)}</td>
                  <td className="px-3 py-3 text-body font-semibold text-tabular">{scoresById[initiative.id]?.toFixed(1) ?? "0.0"}</td>
                  <td className="px-3 py-3 text-body">
                    <span className={`rounded-pill px-2 py-1 text-label font-semibold ${getStatusPillClass(initiative.status)}`}>
                      {INITIATIVE_STATUS_LABELS[initiative.status]}
                    </span>
                  </td>
                  <td className="px-3 py-3 text-body">{peopleLabel(initiative, employeesById)}</td>
                  <td className="rounded-r-xl px-3 py-3 text-body text-tabular">{formatDate(initiative.dueDate)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {initiatives.length === 0 ? (
        <p className="text-body mt-3 text-benell-text-soft">No hay iniciativas para los filtros seleccionados.</p>
      ) : null}
    </section>
  );
}
