'use client';

import { AlertTriangle, ArrowLeft, ChevronDown, RotateCw, Timer } from 'lucide-react';
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';

import { NoResultsIllustration } from '@/components/illustrations';
import { RateCard } from '@/components/shipments/rate-card';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Segmented } from '@/components/ui/segmented';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
import { QUOTE_STALE_MS, type SelectedQuote } from '@/lib/wizard';

/** Re-renders once a second while mounted, for the quote expiry timer. */
function useNow(): number {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const timer = window.setInterval(() => setNow(Date.now()), 1000);
    return () => window.clearInterval(timer);
  }, []);
  return now;
}

function ComparingText() {
  return (
    <p className="flex items-center gap-1 text-small font-medium text-muted-foreground" aria-live="polite">
      Comparing couriers
      <span className="inline-flex gap-0.5" aria-hidden="true">
        {[0, 1, 2].map((dot) => (
          <span key={dot} className="h-1 w-1 rounded-full bg-current motion-safe:animate-pulse-dot" style={{ animationDelay: `${dot * 0.2}s` }} />
        ))}
      </span>
    </p>
  );
}

function ExpiryTimer({ quotedAt }: { quotedAt: string }) {
  const now = useNow();
  const remaining = Math.max(0, Date.parse(quotedAt) + QUOTE_STALE_MS - now);
  if (Number.isNaN(remaining) || remaining === 0) return null;
  const minutes = Math.floor(remaining / 60000);
  const seconds = Math.floor((remaining % 60000) / 1000);
  return (
    <span className="inline-flex items-center gap-1 text-caption tabular-nums text-subtle-foreground">
      <Timer className="h-3.5 w-3.5" aria-hidden="true" />
      Prices held for {minutes}:{String(seconds).padStart(2, '0')}
    </span>
  );
}

export function RateList({
  options,
  reasons,
  loading,
  selectedToken,
  stale,
  quotedAt,
  onSelect,
  onRefresh,
  onBack,
}: {
  options: SelectedQuote[];
  reasons: string[];
  loading: boolean;
  selectedToken: string | null;
  stale: boolean;
  quotedAt?: string | null;
  onSelect: (quote: SelectedQuote) => void;
  onRefresh: () => void;
  onBack: () => void;
}) {
  const [sort, setSort] = useState<'cheapest' | 'fastest'>('cheapest');
  const [couriers, setCouriers] = useState<string[]>([]);
  const [showAll, setShowAll] = useState(false);
  const cardRefs = useRef<Array<HTMLDivElement | null>>([]);
  const courierNames = useMemo(() => [...new Set(options.map((option) => option.courierName))], [options]);
  const filtered = useMemo(() => {
    const list = options.filter((option) => couriers.length === 0 || couriers.includes(option.courierName));
    return [...list].sort((left, right) =>
      sort === 'cheapest' ? left.totalMinor - right.totalMinor : (left.deliveryMinDays ?? 999) - (right.deliveryMinDays ?? 999),
    );
  }, [options, couriers, sort]);
  const visible = showAll ? filtered : filtered.slice(0, 5);
  // Flips to expired when the quote passes the stale threshold while this step is open; resets on a new quote.
  const [expiry, setExpiry] = useState({ quotedAt, expired: false });
  if (expiry.quotedAt !== quotedAt) setExpiry({ quotedAt, expired: false });
  useEffect(() => {
    if (quotedAt === null || quotedAt === undefined) return undefined;
    const remaining = Date.parse(quotedAt) + QUOTE_STALE_MS - Date.now();
    if (Number.isNaN(remaining)) return undefined;
    const timer = window.setTimeout(() => setExpiry({ quotedAt, expired: true }), Math.max(0, remaining));
    return () => window.clearTimeout(timer);
  }, [quotedAt]);
  const isStale = stale || (expiry.expired && expiry.quotedAt === quotedAt);

  const selectedIndex = visible.findIndex((quote) => quote.quoteToken === selectedToken);
  const focusIndex = selectedIndex === -1 ? 0 : selectedIndex;

  const onCardKey = (event: KeyboardEvent<HTMLDivElement>, index: number) => {
    if (event.key === ' ' || event.key === 'Enter') {
      event.preventDefault();
      const quote = visible[index];
      if (quote !== undefined) onSelect(quote);
      return;
    }
    const delta = event.key === 'ArrowDown' || event.key === 'ArrowRight' ? 1 : event.key === 'ArrowUp' || event.key === 'ArrowLeft' ? -1 : 0;
    if (delta === 0) return;
    event.preventDefault();
    const next = (index + delta + visible.length) % visible.length;
    const quote = visible[next];
    if (quote !== undefined) onSelect(quote);
    cardRefs.current[next]?.focus();
  };

  const toggleCourier = (name: string) => setCouriers((current) => (current.includes(name) ? current.filter((item) => item !== name) : [...current, name]));

  const controls = (
    <div className="flex flex-wrap items-center gap-3">
      <p className="text-small font-semibold text-foreground">
        {loading ? 'Searching' : `${filtered.length} ${filtered.length === 1 ? 'option' : 'options'} found`}
      </p>
      <div className="ml-auto flex flex-wrap items-center gap-2">
        <Segmented<'cheapest' | 'fastest'>
          size="sm"
          label="Sort rates"
          value={sort}
          onChange={setSort}
          options={[
            { value: 'cheapest', label: 'Cheapest' },
            { value: 'fastest', label: 'Fastest' },
          ]}
        />
        <Button type="button" variant="ghost" size="sm" onClick={onRefresh} disabled={loading}>
          <RotateCw className={cn('h-3.5 w-3.5', loading && 'animate-spin')} aria-hidden="true" />
          Refresh rates
        </Button>
      </div>
    </div>
  );

  if (loading) {
    return (
      <div className="grid gap-4">
        {controls}
        <div className="h-0.5 overflow-hidden rounded-pill bg-primary-soft" aria-hidden="true">
          <div className="h-full w-full origin-left bg-brand-gradient motion-safe:animate-[progress-indeterminate_1.2s_cubic-bezier(0.2,0.8,0.2,1)_infinite]" />
        </div>
        <ComparingText />
        <div className="grid gap-3" aria-hidden="true">
          {[0, 1, 2, 3, 4].map((index) => (
            <div key={index} className="flex h-[88px] items-center gap-4 rounded-xl border border-border bg-surface px-5">
              <Skeleton className="h-12 w-12 rounded-xl" />
              <div className="grid flex-1 gap-2">
                <Skeleton className="h-4 w-40" />
                <Skeleton className="h-3 w-56" />
              </div>
              <Skeleton className="h-7 w-20" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (options.length === 0) {
    return (
      <div className="grid justify-items-center rounded-xl border border-border bg-surface px-6 py-12 text-center">
        <NoResultsIllustration size={120} />
        <h3 className="mt-4 font-display text-h2 font-bold">No couriers available for this shipment</h3>
        {reasons.length === 0 ? (
          <p className="mt-2 max-w-md text-small text-muted-foreground">Try adjusting the package size, weight or addresses.</p>
        ) : (
          <ul className="mt-3 grid max-w-md list-disc gap-1 pl-5 text-left text-small text-muted-foreground">
            {reasons.map((reason) => (
              <li key={reason}>{reason}</li>
            ))}
          </ul>
        )}
        <Button type="button" variant="secondary" className="mt-6" onClick={onBack}>
          <ArrowLeft className="h-4 w-4" aria-hidden="true" />
          Back
        </Button>
      </div>
    );
  }

  return (
    <div className="grid gap-4">
      {isStale ? (
        <div className="flex flex-wrap items-center gap-3 rounded-lg border border-warning/30 bg-warning-soft px-4 py-3" role="status">
          <AlertTriangle className="h-[18px] w-[18px] shrink-0 text-warning" aria-hidden="true" />
          <p className="min-w-0 flex-1 text-small">
            <span className="font-semibold">Prices may have changed.</span> <span className="text-muted-foreground">These rates were quoted a while ago. Refresh to see current prices.</span>
          </p>
          <Button type="button" size="sm" onClick={onRefresh}>
            <RotateCw className="h-3.5 w-3.5" aria-hidden="true" />
            Refresh rates
          </Button>
        </div>
      ) : null}

      {controls}

      {courierNames.length > 1 ? (
        <div className="flex flex-wrap gap-2" role="group" aria-label="Filter by courier">
          {courierNames.map((name) => {
            const active = couriers.includes(name);
            return (
              <button
                key={name}
                type="button"
                aria-pressed={active}
                onClick={() => toggleCourier(name)}
                className={cn(
                  'inline-flex h-8 items-center gap-1.5 rounded-pill border pl-1 pr-3 text-caption font-semibold transition-colors',
                  active ? 'border-primary bg-primary-soft text-primary' : 'border-border bg-surface text-muted-foreground hover:border-border-strong hover:text-foreground',
                )}
              >
                <Avatar name={name} size="xs" />
                {name}
              </button>
            );
          })}
          {couriers.length > 0 ? (
            <button type="button" onClick={() => setCouriers([])} className="h-8 rounded-pill px-2 text-caption font-semibold text-primary hover:underline">
              Clear
            </button>
          ) : null}
        </div>
      ) : null}

      <div role="radiogroup" aria-label="Courier rates" className="grid gap-3">
        {visible.map((quote, index) => (
          <RateCard
            key={quote.quoteToken}
            ref={(node) => {
              cardRefs.current[index] = node;
            }}
            quote={quote}
            selected={quote.quoteToken === selectedToken}
            best={index === 0 ? (sort === 'cheapest' ? 'Best price' : 'Fastest') : undefined}
            tabIndex={index === focusIndex ? 0 : -1}
            onSelect={() => onSelect(quote)}
            onKeyDown={(event) => onCardKey(event, index)}
          />
        ))}
        {visible.length === 0 ? <p className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-small text-muted-foreground">No rates match the selected couriers.</p> : null}
      </div>

      <div className="flex flex-wrap items-center justify-between gap-3">
        {quotedAt === null || quotedAt === undefined || isStale ? <span /> : <ExpiryTimer quotedAt={quotedAt} />}
        {filtered.length > 5 ? (
          <Button type="button" variant="ghost" size="sm" onClick={() => setShowAll((value) => !value)} aria-expanded={showAll}>
            {showAll ? 'Show top 5' : `Show all ${filtered.length}`}
            <ChevronDown className={cn('h-4 w-4 transition-transform', showAll && 'rotate-180')} aria-hidden="true" />
          </Button>
        ) : null}
      </div>
    </div>
  );
}
