import { Clock, MapPin, Package, ShieldCheck, Tag } from 'lucide-react';
import type { ReactNode } from 'react';

import { Avatar } from '@/components/ui/avatar';
import { countryName, flagEmoji } from '@/lib/format';
import { formatMoney } from '@/lib/money';
import { cn } from '@/lib/utils';
import type { AddressDraft, SelectedQuote, ShipmentDraft } from '@/lib/wizard';

export interface Place {
  city: string;
  countryCode: string;
}

/** Resolves the city/country shown for a draft address: the saved lookup, or the typed values. */
const placeOf = (address: AddressDraft, saved?: Place | null): Place | null => {
  if (address.mode === 'saved') return saved ?? null;
  if (address.city.trim().length === 0 && address.countryCode.length === 0) return null;
  return { city: address.city.trim(), countryCode: address.countryCode };
};

const deliveryWindow = (quote: SelectedQuote): string | null => {
  if (quote.deliveryMinDays === undefined) return null;
  if (quote.deliveryMaxDays === undefined || quote.deliveryMaxDays === quote.deliveryMinDays) return `${quote.deliveryMinDays} business days`;
  return `${quote.deliveryMinDays} to ${quote.deliveryMaxDays} business days`;
};

function Section({ title, icon, children }: { title: string; icon: ReactNode; children: ReactNode }) {
  return (
    <div className="border-t border-border px-5 py-4 first:border-t-0">
      <p className="mb-2.5 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-subtle-foreground [&>svg]:h-3.5 [&>svg]:w-3.5">
        {icon}
        {title}
      </p>
      {children}
    </div>
  );
}

function Placeholder({ className }: { className?: string }) {
  return <span className={cn('block h-3.5 rounded bg-surface-muted', className)} aria-hidden="true" />;
}

function Stop({ label, place, last }: { label: string; place: Place | null; last?: boolean }) {
  return (
    <li className="relative flex gap-3 pb-4 last:pb-0">
      {last ? null : <span className="absolute left-[5px] top-4 h-[calc(100%-10px)] border-l-2 border-dashed border-border-strong" aria-hidden="true" />}
      <span className={cn('relative mt-1 h-3 w-3 shrink-0 rounded-full ring-4', place === null ? 'bg-border-strong ring-surface' : 'bg-primary ring-primary-soft')} aria-hidden="true" />
      <div className="min-w-0 flex-1">
        <p className="text-caption text-muted-foreground">{label}</p>
        {place === null ? (
          <>
            <Placeholder className="mt-1.5 w-28" />
            <span className="sr-only">Not set</span>
          </>
        ) : (
          <p className="truncate text-small font-semibold text-foreground">
            <span aria-hidden="true">{flagEmoji(place.countryCode)} </span>
            {[place.city, countryName(place.countryCode)].filter((part) => part.length > 0).join(', ')}
          </p>
        )}
      </div>
    </li>
  );
}

function Chip({ children }: { children: ReactNode }) {
  return <span className="inline-flex items-center rounded-pill bg-surface-muted px-2.5 py-1 text-caption font-medium text-foreground tabular-nums">{children}</span>;
}

export function SummarySidebar({
  draft,
  sender,
  recipient,
  international = false,
  balanceMinor,
  currency = 'USD',
  className,
}: {
  draft: ShipmentDraft;
  sender?: Place | null;
  recipient?: Place | null;
  international?: boolean;
  balanceMinor?: number;
  currency?: string;
  className?: string;
}) {
  const quote: SelectedQuote | null = draft.selectedQuote;
  const from = placeOf(draft.sender, sender);
  const to = placeOf(draft.recipient, recipient);
  const weightUnit = draft.unit === 'metric' ? 'kg' : 'lb';
  const sizeUnit = draft.unit === 'metric' ? 'cm' : 'in';
  const parcels = draft.parcels.filter((parcel) => parcel.weight.length > 0 || parcel.length.length > 0);
  const itemCount = draft.items.reduce((sum, item) => sum + (Number.parseInt(item.quantity, 10) || 0), 0);
  const after = quote === null || balanceMinor === undefined ? null : balanceMinor - quote.totalMinor;
  const eta = quote === null ? null : deliveryWindow(quote);

  return (
    <aside className={cn('overflow-hidden rounded-xl border border-border bg-surface shadow-sm', className)} aria-label="Shipment summary">
      <div className="flex items-center justify-between border-b border-border bg-surface-muted/60 px-5 py-3">
        <h2 className="font-display text-small font-bold">Summary</h2>
        <span className="text-caption text-muted-foreground">Step {draft.step + 1} of 5</span>
      </div>

      <Section title="Route" icon={<MapPin />}>
        <ol>
          <Stop label="From" place={from} />
          <Stop label="To" place={to} last />
        </ol>
      </Section>

      <Section title="Package" icon={<Package />}>
        {parcels.length === 0 ? (
          <Placeholder className="w-36" />
        ) : (
          <div className="flex flex-wrap gap-1.5">
            {parcels.map((parcel, index) => (
              <Chip key={index}>
                {parcel.weight.length > 0 ? `${parcel.weight} ${weightUnit}` : '—'}
                {parcel.length.length > 0 ? ` · ${parcel.length} × ${parcel.width || '—'} × ${parcel.height || '—'} ${sizeUnit}` : ''}
              </Chip>
            ))}
            {itemCount > 0 ? <Chip>{itemCount} {itemCount === 1 ? 'item' : 'items'}</Chip> : null}
          </div>
        )}
      </Section>

      <Section title="Options" icon={<ShieldCheck />}>
        <div className="flex flex-wrap gap-1.5">
          {international ? <Chip>Duties paid by {draft.taxesDutiesPaidBy === 'Sender' ? 'sender' : 'recipient'}</Chip> : null}
          {draft.isInsured ? <Chip>Insured</Chip> : null}
          {draft.reference.trim().length > 0 ? (
            <Chip>
              <Tag className="mr-1 h-3 w-3" aria-hidden="true" />
              {draft.reference.trim()}
            </Chip>
          ) : null}
          {!international && !draft.isInsured && draft.reference.trim().length === 0 ? <span className="text-caption text-subtle-foreground">No extra options</span> : null}
        </div>
      </Section>

      <Section title="Selected rate" icon={<Clock />}>
        {quote === null ? (
          <div className="flex items-center gap-3">
            <span className="h-9 w-9 rounded-lg bg-surface-muted" aria-hidden="true" />
            <div className="grid flex-1 gap-1.5">
              <Placeholder className="w-2/3" />
              <Placeholder className="w-1/2" />
            </div>
            <span className="sr-only">No rate selected yet</span>
          </div>
        ) : (
          <div className="flex items-center gap-3">
            <Avatar name={quote.courierName} size="md" shape="square" className="rounded-lg" />
            <div className="min-w-0">
              <p className="truncate text-small font-semibold">{quote.courierName}</p>
              <p className="truncate text-caption text-muted-foreground">
                {quote.serviceName}
                {eta === null ? '' : ` · ${eta}`}
              </p>
            </div>
          </div>
        )}
      </Section>

      <div className="border-t border-border bg-surface-muted/50 px-5 py-4">
        <div className="flex items-end justify-between gap-3">
          <span className="text-small font-semibold text-foreground">Total</span>
          <span className="font-display text-[28px] font-extrabold leading-none tracking-[-0.02em] tabular-nums">
            {quote === null ? <span className="text-subtle-foreground">—</span> : formatMoney(quote.totalMinor, quote.currency)}
          </span>
        </div>
        {balanceMinor === undefined ? null : (
          <dl className="mt-3 grid gap-1 text-caption">
            <div className="flex justify-between text-muted-foreground">
              <dt>Wallet balance</dt>
              <dd className="tabular-nums">{formatMoney(balanceMinor, quote?.currency ?? currency)}</dd>
            </div>
            {after === null || quote === null ? null : (
              <div className={cn('flex justify-between font-semibold', after < 0 ? 'text-danger' : 'text-success')}>
                <dt>Balance after purchase</dt>
                <dd className="tabular-nums">{formatMoney(after, quote.currency)}</dd>
              </div>
            )}
          </dl>
        )}
      </div>
    </aside>
  );
}

export { placeOf };
