
"use client";

import Link from "next/link";
import type { WorkAssignmentQueueItem, WorkAssignmentQueueSummary } from "@/types";

function fullName(user?: { firstName?: string | null; lastName?: string | null; email?: string | null } | null) {
  if (!user) return "-";
  const name = [user.firstName, user.lastName].filter(Boolean).join(" ").trim();
  return name || user.email || "-";
}

function formatDueAt(value?: string | null) {
  if (!value) return "No due date";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleString();
}

function reminderBadge(state: WorkAssignmentQueueItem["reminderState"]) {
  const tones = {
    overdue: "border-red-200 bg-red-50 text-red-700",
    today: "border-amber-200 bg-amber-50 text-amber-700",
    soon: "border-blue-200 bg-blue-50 text-blue-700",
    upcoming: "border-slate-200 bg-slate-50 text-slate-700",
    none: "border-slate-200 bg-slate-50 text-slate-700",
  } as const;

  const labels = {
    overdue: "Overdue",
    today: "Due today",
    soon: "Due soon",
    upcoming: "Upcoming",
    none: "No due date",
  } as const;

  return <span className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold ${tones[state]}`}>{labels[state]}</span>;
}

function escalationBadge(state: WorkAssignmentQueueItem["escalationState"]) {
  const tones = {
    normal: "border-slate-200 bg-slate-50 text-slate-700",
    watch: "border-blue-200 bg-blue-50 text-blue-700",
    action_today: "border-amber-200 bg-amber-50 text-amber-700",
    escalated: "border-red-200 bg-red-50 text-red-700",
  } as const;

  const labels = {
    normal: "Normal lane",
    watch: "Watch lane",
    action_today: "Action today",
    escalated: "Escalated",
  } as const;

  return <span className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold ${tones[state]}`}>{labels[state]}</span>;
}

function hookBadge(hook: WorkAssignmentQueueItem["notificationHooks"][number], index: number) {
  const tones = {
    ready: "border-slate-200 bg-white text-slate-700",
    armed: "border-blue-200 bg-blue-50 text-blue-700",
    active: "border-emerald-200 bg-emerald-50 text-emerald-700",
  } as const;

  return (
    <span key={`${hook.channel}-${index}`} className={`inline-flex rounded-full border px-2 py-1 text-[11px] font-semibold ${tones[hook.state]}`}>
      {hook.channel.replaceAll("_", " ")}
    </span>
  );
}

function summaryCard(label: string, value: number) {
  return (
    <div className="rounded-xl border bg-gray-50 px-3 py-3">
      <div className="text-xs font-semibold uppercase tracking-wide text-gray-500">{label}</div>
      <div className="mt-1 text-lg font-semibold text-gray-900">{value}</div>
    </div>
  );
}

export function AssignmentQueueCard({
  title,
  description,
  items,
  summary,
  emptyMessage,
}: {
  title: string;
  description: string;
  items: WorkAssignmentQueueItem[];
  summary: WorkAssignmentQueueSummary;
  emptyMessage: string;
}) {
  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="mb-4 flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <h3 className="text-base font-semibold">{title}</h3>
          <p className="mt-1 text-sm text-gray-500">{description}</p>
        </div>
        <div className="grid grid-cols-2 gap-2 lg:min-w-[420px] lg:grid-cols-5">
          {summaryCard("Open", summary.total)}
          {summaryCard("Overdue", summary.overdue)}
          {summaryCard("Today", summary.dueToday)}
          {summaryCard("Urgent", summary.urgent)}
          {summaryCard("Escalated", summary.escalated)}
        </div>
      </div>

      {items.length ? (
        <div className="space-y-3">
          {items.map((item) => (
            <div key={item.id} className="rounded-2xl border p-4">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                <div className="space-y-2">
                  <div className="flex flex-wrap items-center gap-2">
                    <Link href={item.href} className="text-sm font-semibold text-gray-900 hover:underline">
                      {item.targetLabel}
                    </Link>
                    {reminderBadge(item.reminderState)}
                    {escalationBadge(item.escalationState)}
                    <span className="inline-flex rounded-full border bg-white px-2.5 py-1 text-xs font-semibold text-gray-700">{item.priority.replaceAll("_", " ")}</span>
                    <span className="inline-flex rounded-full border bg-white px-2.5 py-1 text-xs font-semibold text-gray-700">{item.status.replaceAll("_", " ")}</span>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {(item.notificationHooks ?? []).map(hookBadge)}
                  </div>
                  <div className="text-sm text-gray-600">{item.targetContext || item.targetType.replaceAll("_", " ")}</div>
                  <div className="text-sm text-gray-900">{item.instructions || "No assignment instructions recorded."}</div>
                  {item.expectedOutcome ? <div className="text-sm text-gray-600">Expected outcome: {item.expectedOutcome}</div> : null}
                </div>
                <div className="space-y-2 text-sm text-gray-600 lg:min-w-[260px] lg:text-right">
                  <div>Primary: <span className="font-medium text-gray-900">{fullName(item.primaryAssigneeUser)}</span></div>
                  <div>Due: <span className="font-medium text-gray-900">{formatDueAt(item.dueAt)}</span></div>
                  <div>Assigned by: <span className="font-medium text-gray-900">{fullName(item.assignedByUser)}</span></div>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="rounded-xl border border-dashed px-4 py-8 text-sm text-gray-500">{emptyMessage}</div>
      )}
    </section>
  );
}
