import Link from "next/link";

type SelectedWorkflowAction = {
  label: string;
  value: string;
  detail: string;
  tone: "urgent" | "watch" | "calm";
  buttonLabel: string;
  disabled?: boolean;
  href?: string;
  onClick?: () => void;
};

type SelectedWorkflowStatus = {
  label: string;
  count: number;
  tone?: "urgent" | "watch" | "calm";
};

type SelectedWorkflowQueueHandoff = {
  label: string;
  count: number;
  detail: string;
  href: string;
  cta: string;
  tone: "urgent" | "watch" | "calm";
};

const toneClasses: Record<SelectedWorkflowAction["tone"], string> = {
  urgent: "border-red-200 bg-red-50 text-red-700",
  watch: "border-amber-200 bg-amber-50 text-amber-700",
  calm: "border-emerald-200 bg-emerald-50 text-emerald-700",
};

export function DispatchSelectedWorkflowAcceleration({
  actions,
  statusMix,
  summary,
  harmonizationSummary,
  queueHandoffs,
}: {
  actions: SelectedWorkflowAction[];
  statusMix: SelectedWorkflowStatus[];
  summary: string[];
  harmonizationSummary: string[];
  queueHandoffs: SelectedWorkflowQueueHandoff[];
}) {
  const quickAssignAction = actions.find((action) => action.label === "Quick assign first");
  const openFirstAction = actions.find((action) => action.label === "Open first selected");
  const advanceAction = actions.find((action) => action.label === "Advance actionable");
  const resetAction = actions.find((action) => action.label === "Reset selection");

  const assignReadyCount = statusMix
    .filter((item) => item.label === "Assignment ready")
    .reduce((sum, item) => sum + item.count, 0);
  const inMotionCount = statusMix
    .filter((item) => item.label === "Staging / assigned" || item.label === "In transit")
    .reduce((sum, item) => sum + item.count, 0);
  const reviewCount = Math.max(statusMix.reduce((sum, item) => sum + item.count, 0) - assignReadyCount - inMotionCount, 0);

  const readinessCards = [
    {
      label: "Ready to quick assign",
      count: assignReadyCount,
      tone: assignReadyCount ? "urgent" : "calm",
      detail: assignReadyCount ? "Selected work is sitting in draft or available states and is ready for immediate truck/driver coverage." : "No selected loads are clearly ready for immediate quick assign.",
    },
    {
      label: "Needs review before assign",
      count: reviewCount,
      tone: reviewCount ? "watch" : "calm",
      detail: reviewCount ? "The current selection mixes statuses that likely need record review before pushing the same assignment action." : "No mixed-status issues are visible in the current selection.",
    },
    {
      label: "Already assigned / in motion",
      count: inMotionCount,
      tone: inMotionCount ? "watch" : "calm",
      detail: inMotionCount ? "Some selected loads are already assigned or moving, so they should not lead the next assignment step." : "No selected loads are already assigned or in motion.",
    },
  ] as const;

  const guidance = assignReadyCount
    ? "Assign now. The selected set includes draft or available loads that are ready for immediate coverage."
    : reviewCount
      ? "Review the mixed selection first. Open the first selected load or reset the selection before assigning."
      : inMotionCount
        ? "This selected set is already covered or moving. Reopen first selected or advance the actionable record instead of reassigning."
        : "Select visible work to unlock the next assignment-ready path.";

  return (
    <section className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-gray-900">Selected load actions</div>
          <div className="text-xs text-gray-500">Keep the selected set moving through the next likely action without making dispatchers rebuild the same selection, first-open, or follow-through pattern.</div>
        </div>
        <div className="flex flex-wrap gap-2">
          {summary.length ? summary.map((item) => (
            <span key={item} className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">{item}</span>
          )) : <span className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">Selection ready</span>}
        </div>
      </div>


      <div className="mt-4 grid gap-3 xl:grid-cols-3">
        {readinessCards.map((card) => (
          <div key={card.label} className="rounded-xl border bg-gray-50 p-4">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-gray-900">{card.label}</div>
                <div className="mt-2 text-xs text-gray-600">{card.detail}</div>
              </div>
              <span className={`rounded-full border px-2.5 py-1 text-xs font-semibold ${toneClasses[card.tone]}`}>{card.count}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-4 rounded-xl border bg-gray-50 p-4">
        <div className="text-sm font-semibold text-gray-900">Selected quick-assign guidance</div>
        <div className="mt-2 text-xs text-gray-600">{guidance}</div>
        <div className="mt-3 flex flex-wrap gap-2">
          {quickAssignAction ? (quickAssignAction.href ? (
            <Link href={quickAssignAction.href} className={`inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 ${quickAssignAction.disabled ? "pointer-events-none opacity-50" : ""}`}>
              {quickAssignAction.buttonLabel}
            </Link>
          ) : (
            <button type="button" onClick={quickAssignAction.onClick} disabled={quickAssignAction.disabled} className="inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50">
              {quickAssignAction.buttonLabel}
            </button>
          )) : null}
          {openFirstAction ? (openFirstAction.href ? (
            <Link href={openFirstAction.href} className={`inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 ${openFirstAction.disabled ? "pointer-events-none opacity-50" : ""}`}>
              {openFirstAction.buttonLabel}
            </Link>
          ) : null) : null}
          {advanceAction ? (
            <button type="button" onClick={advanceAction.onClick} disabled={advanceAction.disabled} className="inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50">
              {advanceAction.buttonLabel}
            </button>
          ) : null}
          {resetAction ? (
            <button type="button" onClick={resetAction.onClick} disabled={resetAction.disabled} className="inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50">
              {resetAction.buttonLabel}
            </button>
          ) : null}
        </div>
      </div>

      <div className="mt-4 grid gap-3 xl:grid-cols-4">
        {actions.map((action) => (
          <div key={action.label} className="rounded-xl border p-4">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-gray-900">{action.label}</div>
                <div className="mt-2 text-xs text-gray-600">{action.detail}</div>
              </div>
              <span className={`rounded-full border px-2.5 py-1 text-xs font-semibold ${toneClasses[action.tone]}`}>{action.value}</span>
            </div>
            <div className="mt-4">
              {action.href ? (
                <Link href={action.href} className={`inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 ${action.disabled ? "pointer-events-none opacity-50" : ""}`}>
                  {action.buttonLabel}
                </Link>
              ) : (
                <button type="button" onClick={action.onClick} disabled={action.disabled} className="inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50">
                  {action.buttonLabel}
                </button>
              )}
            </div>
          </div>
        ))}
      </div>


      <div className="mt-4 rounded-xl border bg-gray-50 p-4">
        <div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-gray-900">Selected-work next step</div>
            <div className="mt-1 text-xs text-gray-600">Send the current selection to the right next step without rebuilding the board by hand.</div>
          </div>
          <div className="flex flex-wrap gap-2">
            {queueHandoffs.length ? queueHandoffs.map((item) => (
              <span key={item.label} className={`rounded-full border px-2.5 py-1 text-xs font-semibold ${toneClasses[item.tone]}`}>{item.label} {item.count}</span>
            )) : <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700">Ready</span>}
          </div>
        </div>
        <div className="mt-4 grid gap-3 xl:grid-cols-4">
          {queueHandoffs.map((item) => (
            <div key={item.label} className="rounded-xl border bg-white p-4">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-gray-900">{item.label}</div>
                  <div className="mt-2 text-xs text-gray-600">{item.detail}</div>
                </div>
                <span className={`rounded-full border px-2.5 py-1 text-xs font-semibold ${toneClasses[item.tone]}`}>{item.count}</span>
              </div>
              <div className="mt-4">
                <Link href={item.href} className="inline-flex items-center rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">
                  {item.cta}
                </Link>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="mt-4 rounded-xl border bg-gray-50 p-4">
        <div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-gray-900">Selected-work status harmonization</div>
            <div className="mt-1 text-xs text-gray-600">Keep the selected set aligned to one operational status family before reusing quick assign, advance, or reopen actions.</div>
          </div>
          <div className="flex flex-wrap gap-2">
            {harmonizationSummary.length ? harmonizationSummary.map((item) => (
              <span key={item} className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700">{item}</span>
            )) : <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700">Status harmony ready</span>}
          </div>
        </div>
        <div className="mt-4 grid gap-2 sm:grid-cols-2 xl:grid-cols-5">
          {statusMix.map((item) => (
            <div key={item.label} className="rounded-xl border bg-white px-3 py-3">
              <div className="flex items-start justify-between gap-2">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">{item.label}</div>
                <span className={`rounded-full border px-2 py-0.5 text-[10px] font-semibold ${toneClasses[item.tone ?? "calm"]}`}>{item.count}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
