'use client';

import { useQuery } from '@tanstack/react-query';
import { Ban, CalendarClock, CheckCircle2, CircleAlert, Clock, Package, PackageCheck, RotateCcw, Truck, XCircle, type LucideIcon } from 'lucide-react';

import { Container } from '@/components/layout/container';
import { ErrorIllustration } from '@/components/illustrations';
import { JourneyTrack } from '@/components/shipments/journey-track';
import { TrackSearchForm } from '@/components/shipments/track-search-form';
import { TrackingTimeline } from '@/components/shipments/tracking-timeline';
import { FormAlert } from '@/components/forms/form-field';
import { Avatar } from '@/components/ui/avatar';
import { ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, api } from '@/lib/api-client';
import { countryName, flagEmoji } from '@/lib/format';
import { site } from '@/lib/marketing';
import { queryKeys } from '@/lib/query-keys';
import { statusLabel, type PublicTracking } from '@/lib/shipments';
import { cn } from '@/lib/utils';

/** Big status icon and tint for the result header. */
const statusLook = (rawStatus: string): { icon: LucideIcon; tint: string } => {
  const status = rawStatus.toUpperCase();
  if (status === 'DELIVERED') return { icon: CheckCircle2, tint: 'bg-success-soft text-success' };
  if (status === 'OUT_FOR_DELIVERY') return { icon: PackageCheck, tint: 'bg-warning-soft text-warning' };
  if (status === 'IN_TRANSIT') return { icon: Truck, tint: 'bg-warning-soft text-warning' };
  if (status === 'EXCEPTION') return { icon: CircleAlert, tint: 'bg-danger-soft text-danger' };
  if (status === 'FAILED') return { icon: XCircle, tint: 'bg-danger-soft text-danger' };
  if (status === 'CANCELLED') return { icon: Ban, tint: 'bg-surface-muted text-muted-foreground' };
  if (status === 'RETURNED') return { icon: RotateCcw, tint: 'bg-primary-soft text-accent' };
  if (status === 'PENDING') return { icon: Clock, tint: 'bg-info-soft text-info' };
  return { icon: Package, tint: 'bg-primary-soft text-primary' };
};

/** City and country only. The public page never shows names, streets, phones, emails or references. */
function Place({ place, align = 'left' }: { place: { city?: string; countryCode?: string }; align?: 'left' | 'right' }) {
  return (
    <div className={cn('min-w-0', align === 'right' && 'text-right')}>
      <p className="truncate text-small font-semibold text-foreground">{place.city ?? '—'}</p>
      <p className="truncate text-caption text-muted-foreground">
        {place.countryCode === undefined ? null : <span aria-hidden="true">{flagEmoji(place.countryCode)} </span>}
        {place.countryCode === undefined ? '' : countryName(place.countryCode)}
      </p>
    </div>
  );
}

function TrustFooter() {
  return (
    <p className="mt-10 flex items-center justify-center gap-2 text-caption text-subtle-foreground">
      Tracking powered by
      <span className="inline-flex items-center gap-1.5 font-semibold text-muted-foreground">
        <span className="grid h-5 w-5 place-items-center rounded-md bg-brand-gradient text-primary-foreground" aria-hidden="true">
          <svg viewBox="0 0 24 24" className="h-3 w-3" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 8.5 12 4l8 4.5v7L12 20l-8-4.5v-7Z" />
            <path d="M12 12v8M12 12 4 8.5M12 12l8-3.5" />
          </svg>
        </span>
        {site.name}
      </span>
    </p>
  );
}

export function TrackResult({ trackingNumber }: { trackingNumber: string }) {
  const result = useQuery({
    queryKey: queryKeys.publicTrack(trackingNumber),
    queryFn: () => api<PublicTracking>(`/track/${encodeURIComponent(trackingNumber)}`),
    retry: false,
  });
  const error = result.error instanceof ApiError ? result.error : null;
  const data = result.data;
  const look = data === undefined ? null : statusLook(data.status);
  const StatusIcon = look?.icon ?? Package;

  return (
    <>
      <section className="relative overflow-hidden pb-24 pt-28 md:pb-28 md:pt-36">
        <div className="pointer-events-none absolute inset-0 bg-mesh" aria-hidden="true" />
        <Container className="relative grid justify-items-center text-center">
          <p className="inline-flex rounded-pill bg-primary-soft px-3 py-1 text-caption font-semibold uppercase tracking-[0.14em] text-primary">Parcel tracking</p>
          <h1 className="mt-4 max-w-full break-all font-mono text-[1.75rem] font-bold leading-tight tracking-wide text-foreground md:text-[2.5rem]">{trackingNumber}</h1>
          <TrackSearchForm key={trackingNumber} initialValue={trackingNumber} className="mt-8" />
        </Container>
      </section>

      <section className="relative pb-16 md:pb-24">
        <Container>
          <div className="relative z-[1] mx-auto -mt-12 max-w-[880px]">
            {result.isLoading ? (
              <div className="rounded-2xl border border-border bg-surface p-6 shadow-lg md:p-8" aria-label="Loading tracking" role="status">
                <div className="flex items-center gap-4">
                  <Skeleton className="h-16 w-16 rounded-full" />
                  <div className="grid flex-1 gap-2">
                    <Skeleton className="h-9 w-48" />
                    <Skeleton className="h-4 w-32" />
                  </div>
                </div>
                <Skeleton className="mt-8 h-12 w-full" />
                <Skeleton className="mt-6 h-40 w-full" />
              </div>
            ) : null}

            {error !== null && error.status === 404 ? (
              <div className="grid justify-items-center rounded-2xl border border-border bg-surface px-6 py-12 text-center shadow-lg">
                <ErrorIllustration size={120} />
                <h2 className="mt-4 font-display text-h2 font-bold">Tracking number not found</h2>
                <ul className="mt-3 grid list-disc gap-1 pl-5 text-left text-small text-muted-foreground">
                  <li>Check the number on your label for typos.</li>
                  <li>Allow a few hours after the label is created before the first update.</li>
                </ul>
                <TrackSearchForm key={trackingNumber} initialValue={trackingNumber} className="mt-6" />
              </div>
            ) : null}

            {error !== null && error.status === 429 ? (
              <div className="rounded-2xl border border-border bg-surface p-6 shadow-lg">
                <FormAlert tone="warning" title="Too many tracking lookups.">
                  {error.retryAfterSeconds === undefined ? 'Wait a minute and try again.' : `Try again in ${Math.ceil(error.retryAfterSeconds / 60)} minute${Math.ceil(error.retryAfterSeconds / 60) === 1 ? '' : 's'}.`}
                </FormAlert>
              </div>
            ) : null}

            {error !== null && error.status !== 404 && error.status !== 429 ? (
              <div className="rounded-2xl border border-border bg-surface shadow-lg">
                <ErrorState message={error.message} requestId={error.requestId} onRetry={() => void result.refetch()} />
              </div>
            ) : null}

            {data === undefined ? null : (
              <article className="overflow-hidden rounded-2xl border border-border bg-surface shadow-lg" aria-labelledby="tracking-status">
                <header className="border-b border-border bg-surface-muted/50 p-6 md:p-8">
                  <div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex items-center gap-4">
                      <span className={cn('grid h-16 w-16 shrink-0 place-items-center rounded-full', look?.tint)}>
                        <StatusIcon className="h-8 w-8" aria-hidden="true" />
                      </span>
                      <div className="min-w-0">
                        <p className="text-caption font-semibold uppercase tracking-[0.12em] text-subtle-foreground">Status</p>
                        <h2 id="tracking-status" className="font-display text-[2rem] font-extrabold leading-tight tracking-[-0.03em] md:text-display-lg">
                          {statusLabel(data.status)}
                        </h2>
                      </div>
                    </div>
                    <div className="flex flex-col items-start gap-2 sm:items-end">
                      {data.estimatedDeliveryAt === undefined ? null : (
                        <span className="inline-flex 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 {new Date(data.estimatedDeliveryAt).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })}
                        </span>
                      )}
                      {data.courierName === undefined ? null : (
                        <span className="inline-flex items-center gap-2 text-small font-medium text-foreground">
                          <Avatar name={data.courierName} size="sm" shape="square" className="rounded-md" />
                          {data.courierName}
                        </span>
                      )}
                    </div>
                  </div>

                  <div className="mt-6 grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-4">
                    <Place place={data.origin} />
                    <div className="relative h-6 w-24 sm:w-48" aria-hidden="true">
                      <span className="absolute inset-x-0 top-1/2 -translate-y-1/2 border-t-2 border-dashed border-border-strong" />
                      <span className="absolute top-1/2 h-3 w-3 -translate-y-1/2 rounded-full bg-primary shadow-glow motion-safe:animate-[route-travel_3.2s_cubic-bezier(0.2,0.8,0.2,1)_infinite]" />
                    </div>
                    <Place place={data.destination} align="right" />
                  </div>
                  {data.brandName === undefined ? null : <p className="mt-4 text-caption text-muted-foreground">Shipped by {data.brandName}</p>}
                </header>

                <div className="border-b border-border px-6 py-6 md:px-8">
                  <JourneyTrack status={data.status} />
                </div>

                <div className="p-6 md:p-8">
                  <h3 className="mb-4 font-display text-h3 font-bold">Tracking history</h3>
                  <TrackingTimeline events={data.events} />
                </div>
              </article>
            )}
          </div>
          <TrustFooter />
        </Container>
      </section>
    </>
  );
}
