import { Ban, Check, CircleAlert, RotateCcw, XCircle, type LucideIcon } from 'lucide-react';

import { cn } from '@/lib/utils';

const STAGES = ['Created', 'Label ready', 'In transit', 'Out for delivery', 'Delivered'] as const;

type Tone = 'primary' | 'danger' | 'neutral' | 'accent';

interface Journey {
  /** Index of the current stage. */
  stage: number;
  tone: Tone;
  /** Icon shown on the current node for problem states. */
  icon?: LucideIcon;
  /** Replaces the label of the current stage (e.g. "Exception"). */
  label?: string;
}

/** Maps a shipment status (internal or public tracking) onto the five journey stages. */
export const journeyFor = (rawStatus: string): Journey => {
  const status = rawStatus.toUpperCase().replace(/[\s-]+/g, '_');
  switch (status) {
    case 'PENDING':
    case 'CREATED':
      return { stage: 0, tone: 'primary' };
    case 'LABEL_READY':
      return { stage: 1, tone: 'primary' };
    case 'IN_TRANSIT':
      return { stage: 2, tone: 'primary' };
    case 'OUT_FOR_DELIVERY':
      return { stage: 3, tone: 'primary' };
    case 'DELIVERED':
      return { stage: 4, tone: 'primary' };
    case 'EXCEPTION':
      return { stage: 2, tone: 'danger', icon: CircleAlert, label: 'Exception' };
    case 'FAILED':
      return { stage: 0, tone: 'danger', icon: XCircle, label: 'Failed' };
    case 'CANCELLED':
      return { stage: 1, tone: 'neutral', icon: Ban, label: 'Cancelled' };
    case 'RETURNED':
      return { stage: 2, tone: 'accent', icon: RotateCcw, label: 'Returned' };
    default:
      if (status.includes('DELIVER') && status.includes('OUT')) return { stage: 3, tone: 'primary' };
      if (status.includes('DELIVER')) return { stage: 4, tone: 'primary' };
      if (status.includes('TRANSIT')) return { stage: 2, tone: 'primary' };
      return { stage: 0, tone: 'primary' };
  }
};

const toneClasses: Record<Tone, { fill: string; ring: string; text: string }> = {
  primary: { fill: 'bg-primary', ring: 'ring-primary/20', text: 'text-primary' },
  danger: { fill: 'bg-danger', ring: 'ring-danger/20', text: 'text-danger' },
  neutral: { fill: 'bg-subtle-foreground', ring: 'ring-border', text: 'text-muted-foreground' },
  accent: { fill: 'bg-accent', ring: 'ring-accent/20', text: 'text-accent' },
};

/** Five labelled nodes joined by a line that fills to the current stage. */
export function JourneyTrack({ status, className }: { status: string; className?: string }) {
  const journey = journeyFor(status);
  const tone = toneClasses[journey.tone];
  const progress = (journey.stage / (STAGES.length - 1)) * 100;
  const CurrentIcon = journey.icon;
  return (
    <div className={cn('relative', className)}>
      <p className="sr-only">
        Shipment progress: {journey.label ?? STAGES[journey.stage]}, stage {journey.stage + 1} of {STAGES.length}.
      </p>
      <div className="relative mx-3 sm:mx-6" aria-hidden="true">
        <div className="absolute left-0 right-0 top-[11px] h-0.5 rounded-pill bg-border" />
        <div className={cn('absolute left-0 top-[11px] h-0.5 rounded-pill transition-[width] duration-700 ease-brand', tone.fill)} style={{ width: `${progress}%` }} />
        <ol className="relative flex justify-between">
          {STAGES.map((stage, index) => {
            const done = index < journey.stage;
            const current = index === journey.stage;
            return (
              <li key={stage} className="flex w-6 flex-col items-center">
                <span
                  className={cn(
                    'grid h-6 w-6 place-items-center rounded-full border-2 transition-colors duration-280',
                    done && cn(tone.fill, 'border-transparent text-primary-foreground'),
                    current && cn(tone.fill, 'border-transparent text-primary-foreground ring-4', tone.ring),
                    !done && !current && 'border-border bg-surface',
                  )}
                >
                  {done ? <Check className="h-3 w-3" strokeWidth={3} /> : null}
                  {current && CurrentIcon !== undefined ? <CurrentIcon className="h-3.5 w-3.5" /> : null}
                  {current && CurrentIcon === undefined ? (
                    journey.stage === STAGES.length - 1 ? <Check className="h-3 w-3" strokeWidth={3} /> : <span className="h-2 w-2 rounded-full bg-primary-foreground motion-safe:animate-pulse-dot" />
                  ) : null}
                </span>
                <span
                  className={cn(
                    'mt-2 hidden w-24 text-center text-caption sm:block',
                    current ? cn('font-semibold', tone.text) : done ? 'font-medium text-foreground' : 'text-subtle-foreground',
                  )}
                >
                  {current && journey.label !== undefined ? journey.label : stage}
                </span>
              </li>
            );
          })}
        </ol>
      </div>
      <p className={cn('mt-3 text-center text-caption font-semibold sm:hidden', tone.text)} aria-hidden="true">
        {journey.label ?? STAGES[journey.stage]}
      </p>
    </div>
  );
}
