// Rendu du corps d'un step (XLSX ou BDD) — calque ligne pour ligne de
//   coolcare-app/public/js/admin/report_templates_review.js (renderStepBody)
// Padding / font-sizes / couleurs en hex pour fidélité visuelle. L'ordre
// item-line → parent → action → calcul auto → autoComment → options
// reproduit exactement l'ordre coolcare ; aucun champ n'est réorganisé.

import type { ReactNode } from "react";

type StepRecord = Record<string, unknown> | null;
type Source = "xlsx" | "db";

function asString(v: unknown): string {
  return typeof v === "string" ? v : "";
}

function asNumber(v: unknown): number {
  if (typeof v === "number") return v;
  if (typeof v === "string") {
    const n = Number(v);
    return Number.isFinite(n) ? n : 0;
  }
  return 0;
}

function extractOptions(step: Record<string, unknown>): string[] {
  const raw = step.options;
  if (!Array.isArray(raw)) return [];
  return raw
    .map((o) => {
      if (typeof o === "string") return o;
      if (o && typeof o === "object") {
        const obj = o as Record<string, unknown>;
        return asString(obj.label) || asString(obj.value);
      }
      return "";
    })
    .filter(Boolean);
}

export function StepCell({
  step,
  source,
  className = "",
  isChild = false,
}: {
  step: StepRecord;
  source: Source;
  className?: string;
  isChild?: boolean;
}) {
  // Padding-left renforcé pour les enfants (coolcare : padding-left:1.5rem).
  const padX = isChild ? "pl-6 pr-[0.8rem]" : "px-[0.8rem]";

  if (!step) {
    return (
      <div
        className={`flex items-center justify-center py-2 text-[0.78rem] italic text-[#9ca3af] border-r border-dashed border-[#e5e7eb] last:border-r-0 min-h-[42px] ${padX} ${className}`}
      >
        —
      </div>
    );
  }

  const kind = asString(step.input_kind).toLowerCase();
  const item = asString(step.item);
  const action = asString(step.action_label) || asString(step.action);
  const actionUpper = action.toUpperCase();
  // Filtre coolcare : on n'affiche pas l'action quand c'est juste le marqueur
  // d'extension (déjà rendu par la présence d'enfants).
  const skipAction =
    actionUpper === "AVEC POSSIBILITE EXTENSION" ||
    actionUpper.startsWith("EXTENSION SI");
  const calcAuto = asString(step.calcul_auto);
  const parentItem = asString(step.parent_item);
  const migrationId = source === "db" ? asString(step.migration_id) : "";
  const isRequired = asNumber(step.is_required) === 1;
  const showRequiredTag = kind && kind !== "section";

  const options = extractOptions(step);

  // textarea auto : quand un step "choice" est enfant d'un parent, l'app
  // mobile génère un commentaire conditionnel sur PROBLEME/PANNE.
  const showAutoComment = kind === "choice" && parentItem !== "";

  return (
    <div
      className={`py-2 text-[0.85rem] border-r border-dashed border-[#e5e7eb] last:border-r-0 min-h-[42px] ${padX} ${className}`}
    >
      <div className="flex items-center gap-[0.4rem] flex-wrap">
        {kind && (
          <span className="inline-flex items-center rounded bg-[#1f2937] px-[0.35rem] py-[0.1rem] text-[0.6rem] font-semibold uppercase tracking-wide text-white">
            {kind}
          </span>
        )}
        <strong className="font-semibold text-[#111827] break-words">
          {item || "(sans libellé)"}
        </strong>
        {showRequiredTag && <RequiredTag required={isRequired} />}
        {migrationId && (
          <span
            className="text-[0.6rem] font-bold text-[#7c3aed]"
            title={`Verrouillé par migration_id=${migrationId}`}
          >
            🔒 migration_id={migrationId}
          </span>
        )}
      </div>

      {parentItem && (
        <div className="mt-[0.15rem] text-[0.7rem] italic text-[#6366f1]">
          ↳ enfant de <strong>{parentItem}</strong>
        </div>
      )}

      {action && !skipAction && (
        <div className="mt-[0.15rem] text-[0.7rem] text-[#6b7280]">
          ↳ {action}
        </div>
      )}

      {calcAuto && (
        <div className="mt-[0.15rem] text-[0.7rem] text-[#6b7280]">
          ⚙️ calcul auto :{" "}
          <code className="font-mono text-[#111827]">{calcAuto}</code>
        </div>
      )}

      {showAutoComment && (
        <div className="mt-[0.15rem] text-[0.7rem] italic text-[#0ea5e9]">
          💬 textarea auto (code app, si PROBLEME/PANNE)
        </div>
      )}

      {options.length > 0 && (
        <div className="mt-[0.2rem] flex flex-wrap gap-[0.15rem] text-[0.72rem] text-[#374151]">
          {options.map((o, i) => (
            <span
              key={`${i}-${o}`}
              className="inline-block rounded border border-[#d1d5db] bg-white px-[0.35rem] py-[0.05rem]"
            >
              {o}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

function RequiredTag({ required }: { required: boolean }): ReactNode {
  if (required) {
    return (
      <span
        className="inline-flex items-center rounded border border-[#fca5a5] bg-[#fee2e2] px-[0.3rem] py-[0.05rem] text-[0.58rem] font-bold uppercase tracking-wide text-[#991b1b]"
        title="Saisie obligatoire"
      >
        OBLIGATOIRE
      </span>
    );
  }
  return (
    <span
      className="inline-flex items-center rounded border border-[#d1d5db] bg-[#f3f4f6] px-[0.3rem] py-[0.05rem] text-[0.58rem] font-medium uppercase tracking-wide text-[#6b7280]"
      title="Saisie facultative"
    >
      facultatif
    </span>
  );
}
