'use client';

import { AlertTriangle, CalendarDays, Check, Clock } from 'lucide-react';
import { forwardRef, type KeyboardEvent } from 'react';

import { Avatar } from '@/components/ui/avatar';
import { formatMoney } from '@/lib/money';
import { cn } from '@/lib/utils';
import type { SelectedQuote } from '@/lib/wizard';

export const deliveryWindow = (quote: SelectedQuote): string => {
  if (quote.deliveryMinDays === undefined) return 'Delivery time unavailable';
  if (quote.deliveryMaxDays === undefined || quote.deliveryMaxDays === quote.deliveryMinDays) return `${quote.deliveryMinDays} business days`;
  return `${quote.deliveryMinDays} to ${quote.deliveryMaxDays} business days`;
};

/** Splits a formatted price into symbol-ish parts and the number so the currency can be styled muted and small. */
const priceParts = (minor: number, currency: string): { before: string; number: string; after: string } => {
  const formatted = formatMoney(minor, currency);
  const match = /^(\D*)([\d.,\s ]*\d)(\D*)$/.exec(formatted);
  if (match === null) return { before: '', number: formatted, after: '' };
  return { before: match[1] ?? '', number: match[2] ?? formatted, after: match[3] ?? '' };
};

export const RateCard = forwardRef<
  HTMLDivElement,
  {
    quote: SelectedQuote;
    selected: boolean;
    best?: string;
    tabIndex: number;
    onSelect: () => void;
    onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;
  }
>(function RateCard({ quote, selected, best, tabIndex, onSelect, onKeyDown }, ref) {
  const price = priceParts(quote.totalMinor, quote.currency);
  const cheapest = quote.tags.includes('cheapest');
  const fastest = quote.tags.includes('fastest');
  const estimate = quote.estimatedDeliveryDate === undefined ? null : new Date(quote.estimatedDeliveryDate);
  return (
    <div
      ref={ref}
      role="radio"
      aria-checked={selected}
      aria-label={`${quote.courierName}, ${quote.serviceName}, ${formatMoney(quote.totalMinor, quote.currency)}, ${deliveryWindow(quote)}${cheapest ? ', cheapest' : ''}${fastest ? ', fastest' : ''}`}
      tabIndex={tabIndex}
      onClick={onSelect}
      onKeyDown={onKeyDown}
      className={cn(
        'group relative cursor-pointer overflow-hidden rounded-xl border bg-surface outline-none transition-[transform,box-shadow,border-color,background-color] duration-180 ease-brand',
        'hover:-translate-y-0.5 hover:shadow-md focus-visible:shadow-glow',
        selected ? 'border-2 border-primary bg-primary-soft' : 'border-border hover:border-border-strong',
      )}
    >
      {best === undefined ? null : (
        <span className="absolute left-0 top-0 rounded-br-lg bg-brand-gradient px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-[0.1em] text-primary-foreground" aria-hidden="true">
          {best}
        </span>
      )}
      <div className={cn('flex min-h-[88px] items-center gap-4 py-4 pl-4 pr-11 sm:pl-5', selected && 'pl-[15px] pr-[43px] sm:pl-[19px]', best !== undefined && 'pt-6')}>
        {quote.logoUrl === undefined ? (
          <Avatar name={quote.courierName} size="lg" shape="square" className="h-12 w-12 rounded-xl text-small" />
        ) : (
          // Courier logos come from the rate response.
          // eslint-disable-next-line @next/next/no-img-element
          <img src={quote.logoUrl} alt="" className="h-12 w-12 shrink-0 rounded-xl border border-border bg-surface object-contain p-1" />
        )}
        <div className="min-w-0 flex-1">
          <p className="truncate text-[16px] font-semibold text-foreground">{quote.courierName}</p>
          <p className="truncate text-[13px] text-muted-foreground">{quote.serviceName}</p>
          <p className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-muted-foreground">
            <span className="inline-flex items-center gap-1">
              <Clock className="h-3.5 w-3.5" aria-hidden="true" />
              {deliveryWindow(quote)}
            </span>
            {estimate === null || Number.isNaN(estimate.getTime()) ? null : (
              <span className="inline-flex items-center gap-1">
                <CalendarDays className="h-3.5 w-3.5" aria-hidden="true" />
                Est. {estimate.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })}
              </span>
            )}
          </p>
        </div>
        <div className="flex shrink-0 flex-col items-end gap-1.5">
          {cheapest || fastest ? (
            <span className="flex gap-1">
              {cheapest ? <span className="rounded-pill bg-success-soft px-2 py-0.5 text-[11px] font-semibold text-success">Cheapest</span> : null}
              {fastest ? <span className="rounded-pill bg-primary-soft px-2 py-0.5 text-[11px] font-semibold text-primary ring-1 ring-inset ring-primary/20">Fastest</span> : null}
            </span>
          ) : null}
          <p className="whitespace-nowrap font-display text-[26px] font-extrabold leading-none tracking-[-0.02em] tabular-nums text-foreground">
            {price.before.trim().length === 0 ? null : <span className="mr-0.5 align-top text-small font-semibold text-muted-foreground">{price.before.trim()}</span>}
            {price.number}
            {price.after.trim().length === 0 ? null : <span className="ml-1 text-small font-semibold text-muted-foreground">{price.after.trim()}</span>}
          </p>
        </div>
      </div>
      {quote.warnings.length === 0 ? null : (
        <ul className="grid gap-1 border-t border-warning/25 bg-warning-soft px-4 py-2 sm:px-5">
          {quote.warnings.map((warning) => (
            <li key={warning} className="flex items-start gap-2 text-caption text-foreground">
              <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-warning" aria-hidden="true" />
              {warning}
            </li>
          ))}
        </ul>
      )}
      <span
        className={cn(
          'absolute right-3 top-1/2 grid h-6 w-6 -translate-y-1/2 place-items-center rounded-full bg-primary text-primary-foreground shadow-sm transition duration-180 ease-brand',
          selected ? 'scale-100 opacity-100' : 'scale-50 opacity-0',
        )}
        aria-hidden="true"
      >
        <Check className="h-3.5 w-3.5" strokeWidth={3} />
      </span>
    </div>
  );
});
