"use client";

import { format, parseISO } from "date-fns";
import { ArrowRight, Clock } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

import { groupChangesBySection } from "./history-utils";
import type { HistoryAction, OrderBlotterHistory } from "./history-types";

function formatHistoryDateTime(changedAt: string) {
  try {
    const normalized = changedAt.includes("T") ? changedAt : changedAt.replace(" ", "T");
    const date = parseISO(normalized);
    return {
      date: format(date, "MMM d, yyyy"),
      time: format(date, "h:mm a"),
      full: format(date, "MMM d, yyyy h:mm a"),
    };
  } catch {
    return { date: changedAt, time: "", full: changedAt };
  }
}

function actionLabel(action: HistoryAction) {
  switch (action) {
    case "create":
      return "Created";
    case "update":
      return "Updated";
    case "delete":
      return "Deleted";
    default:
      return action;
  }
}

function ActionBadge({ action }: { action: HistoryAction }) {
  const variant =
    action === "delete" ? "destructive" : action === "create" ? "default" : "secondary";

  return (
    <Badge variant={variant} className="h-5 px-2 text-[10px] font-semibold uppercase tracking-wide">
      {actionLabel(action)}
    </Badge>
  );
}

function dotClass(action: HistoryAction) {
  if (action === "create") return "border-primary bg-primary";
  if (action === "delete") return "border-destructive bg-destructive";
  return "border-primary/60 bg-primary/60";
}

export function OrderBlotterHistoryTimeline({ history }: { history: OrderBlotterHistory }) {
  const lastChange = history.events[0]?.changedAt ?? "";
  const lastFormatted = lastChange ? formatHistoryDateTime(lastChange).full : "—";

  if (history.events.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border/70 py-10 text-center text-muted-foreground">
        <Clock className="mb-2 size-6 opacity-40" />
        <p className="text-sm">No changes recorded yet.</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <div className="grid overflow-hidden rounded-xl border border-border/60 sm:grid-cols-3">
        <div className="bg-muted/50 px-3 py-2.5 sm:border-r sm:border-border/60">
          <div className="font-semibold text-lg tabular-nums leading-none text-foreground">
            {history.events.length}
          </div>
          <div className="mt-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
            Events in timeline
          </div>
        </div>
        <div className="border-t border-border/60 bg-muted/50 px-3 py-2.5 sm:border-t-0 sm:border-r">
          <div className="font-semibold text-sm leading-snug text-foreground">{lastFormatted}</div>
          <div className="mt-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
            Last change
          </div>
        </div>
        <div className="border-t border-border/60 bg-muted/50 px-3 py-2.5 sm:border-t-0">
          <div className="font-semibold text-sm leading-snug tabular-nums text-foreground">
            {history.orderNumber}
          </div>
          <div className="mt-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
            Order #
          </div>
        </div>
      </div>

      <ol className="relative m-0 flex list-none flex-col gap-2.5">
        <div
          aria-hidden
          className="pointer-events-none absolute top-2.5 bottom-2.5 left-[7px] w-px rounded-full bg-border"
        />
        {history.events.map((event, index) => {
          const when = formatHistoryDateTime(event.changedAt);
          const sections = groupChangesBySection(event.changes);
          const fieldCount = event.changes.length;
          const fieldLabel = fieldCount === 1 ? "1 field changed" : `${fieldCount} fields changed`;

          return (
            <li key={event.id} className="relative flex items-start gap-2.5">
              <div className="flex w-3.5 shrink-0 justify-center pt-3.5">
                <span
                  aria-hidden
                  className={cn(
                    "relative z-10 size-3 shrink-0 rounded-full border-2 border-background ring-1 ring-border",
                    dotClass(event.action),
                  )}
                />
              </div>
              <details
                className="group min-w-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-card shadow-sm"
                open={index === 0}
              >
                <summary className="flex cursor-pointer list-none flex-wrap items-center gap-x-2.5 gap-y-1 bg-muted/40 px-3 py-2 marker:content-none hover:bg-muted/60 [&::-webkit-details-marker]:hidden">
                  <span className="whitespace-nowrap font-semibold text-sm text-foreground">
                    {when.full}
                  </span>
                  <ActionBadge action={event.action} />
                  <span className="text-muted-foreground text-xs sm:text-sm">
                    <strong className="font-medium text-foreground">{event.userLabel}</strong>
                    {" · "}
                    {fieldLabel}
                  </span>
                  <span className="ml-auto text-muted-foreground text-xs transition-transform group-open:rotate-180">
                    ▾
                  </span>
                </summary>

                <div className="space-y-2.5 border-t border-border/60 px-3 py-2.5">
                  {sections.length === 0 ? (
                    <p className="m-0 text-muted-foreground text-sm">No field-level details recorded.</p>
                  ) : (
                    sections.map((section) => (
                      <div key={section.sectionId}>
                        <h4 className="mb-1 text-[10px] font-bold uppercase tracking-wide text-primary">
                          {section.title}
                        </h4>
                        <ul className="m-0 list-none divide-y divide-border/50 overflow-hidden rounded-lg border border-border/60">
                          {section.rows.map((row) => (
                            <li
                              key={row.key}
                              className="grid gap-1.5 bg-card px-2.5 py-1.5 text-sm sm:grid-cols-[minmax(110px,0.9fr)_minmax(70px,1fr)_auto_minmax(70px,1fr)] sm:items-center"
                            >
                              <span className="font-medium text-foreground text-xs sm:text-sm">
                                {row.label}
                              </span>
                              <span
                                className={cn(
                                  "text-muted-foreground text-xs sm:text-sm",
                                  !row.old.trim() && "italic",
                                )}
                              >
                                {row.old.trim() || "empty"}
                              </span>
                              <ArrowRight
                                className="hidden size-3.5 text-muted-foreground sm:block"
                                aria-hidden
                              />
                              <span
                                className={cn(
                                  "font-medium text-primary text-xs sm:text-sm",
                                  !row.newValue.trim() && "italic text-muted-foreground",
                                )}
                              >
                                {row.newValue.trim() || "empty"}
                              </span>
                            </li>
                          ))}
                        </ul>
                      </div>
                    ))
                  )}
                </div>
              </details>
            </li>
          );
        })}
      </ol>
    </div>
  );
}
