import { CalendarClock, CheckCircle2, CircleAlert, MapPin, Package, PackageCheck, Tag, Truck, type LucideIcon } from 'lucide-react';

import { RouteIllustration } from '@/components/illustrations/route-illustration';
import type { TrackingEvent } from '@/lib/shipments';
import { cn } from '@/lib/utils';

const kindFor = (status: string): { icon: LucideIcon; tone: string } => {
  const upper = status.toUpperCase();
  if (upper.includes('DELIVER') && !upper.includes('OUT')) return { icon: CheckCircle2, tone: 'bg-success-soft text-success' };
  if (upper.includes('EXCEPT') || upper.includes('FAIL') || upper.includes('RETURN')) return { icon: CircleAlert, tone: 'bg-danger-soft text-danger' };
  if (upper.includes('OUT')) return { icon: PackageCheck, tone: 'bg-warning-soft text-warning' };
  if (upper.includes('TRANSIT')) return { icon: Truck, tone: 'bg-warning-soft text-warning' };
  if (upper.includes('SCAN') || upper.includes('PICK')) return { icon: MapPin, tone: 'bg-info-soft text-info' };
  if (upper.includes('LABEL')) return { icon: Tag, tone: 'bg-primary-soft text-primary' };
  return { icon: Package, tone: 'bg-surface-muted text-muted-foreground' };
};

const dayLabel = (date: Date): string => {
  const today = new Date();
  const yesterday = new Date();
  yesterday.setDate(today.getDate() - 1);
  if (date.toDateString() === today.toDateString()) return 'Today';
  if (date.toDateString() === yesterday.toDateString()) return 'Yesterday';
  return date.toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
};

/** Vertical timeline, newest first, grouped by day with sticky day labels. */
export function TrackingTimeline({
  events,
  estimatedDeliveryAt,
}: {
  events: TrackingEvent[];
  estimatedDeliveryAt?: string;
}) {
  const ordered = [...events].sort((left, right) => Date.parse(right.occurredAt) - Date.parse(left.occurredAt));
  const groups: Array<{ day: string; label: string; events: TrackingEvent[] }> = [];
  for (const event of ordered) {
    const date = new Date(event.occurredAt);
    const day = Number.isNaN(date.getTime()) ? event.occurredAt : date.toDateString();
    const group = groups[groups.length - 1];
    if (group !== undefined && group.day === day) group.events.push(event);
    else groups.push({ day, label: Number.isNaN(date.getTime()) ? 'Unknown date' : dayLabel(date), events: [event] });
  }
  const latest = ordered[0];

  return (
    <div className="grid gap-4">
      {estimatedDeliveryAt === undefined ? null : (
        <p className="inline-flex w-fit items-center gap-1.5 rounded-pill bg-primary-soft px-3 py-1 text-caption font-semibold text-primary">
          <CalendarClock className="h-3.5 w-3.5" aria-hidden="true" />
          Estimated delivery {new Date(estimatedDeliveryAt).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })}
        </p>
      )}
      {ordered.length === 0 ? (
        <div className="grid justify-items-center gap-2 py-8 text-center">
          <RouteIllustration size={96} />
          <p className="max-w-xs text-small text-muted-foreground">Tracking updates will appear here once the courier scans the parcel.</p>
        </div>
      ) : (
        <div className="grid gap-2">
          {groups.map((group) => (
            <section key={group.day} aria-label={group.label}>
              <h3 className="sticky top-16 z-[1] -mx-1 bg-surface/95 px-1 py-1.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-subtle-foreground backdrop-blur">
                {group.label}
              </h3>
              <ol className="relative">
                {group.events.map((event, index) => {
                  const isLatest = event === latest;
                  const kind = kindFor(event.status);
                  const Icon = kind.icon;
                  const last = index === group.events.length - 1 && group === groups[groups.length - 1];
                  return (
                    <li key={`${event.occurredAt}-${index}`} className="relative flex gap-4 pb-5 last:pb-2">
                      {last ? null : <span className="absolute left-[15px] top-8 h-[calc(100%-24px)] w-0.5 bg-border" aria-hidden="true" />}
                      <span className="relative grid h-8 w-8 shrink-0 place-items-center" aria-hidden="true">
                        {isLatest ? <span className="absolute inset-0 rounded-full bg-primary/30 motion-safe:animate-[ring-pulse_1.8s_ease-out_infinite]" /> : null}
                        <span className={cn('relative grid h-8 w-8 place-items-center rounded-full ring-4 ring-surface', isLatest ? 'bg-primary text-primary-foreground' : kind.tone)}>
                          <Icon className="h-4 w-4" />
                        </span>
                      </span>
                      <div className="min-w-0 pt-1">
                        <p className={cn('text-small font-semibold', isLatest ? 'text-foreground' : 'text-foreground/90')}>{event.description ?? event.status}</p>
                        <p className="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-caption text-muted-foreground">
                          {event.location === undefined ? null : (
                            <span className="inline-flex items-center gap-1">
                              <MapPin className="h-3 w-3" aria-hidden="true" />
                              {event.location}
                            </span>
                          )}
                          <time dateTime={event.occurredAt}>
                            {Number.isNaN(Date.parse(event.occurredAt)) ? event.occurredAt : new Date(event.occurredAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}
                          </time>
                        </p>
                      </div>
                    </li>
                  );
                })}
              </ol>
            </section>
          ))}
        </div>
      )}
    </div>
  );
}
