'use client';

import { AlertCircle, MailWarning, MapPin, Package, PackageOpen, Pencil, Plus, Settings2, Truck, type LucideIcon } from 'lucide-react';
import type { ReactNode } from 'react';

import type { SavedAddress } from '@/components/shipments/address-picker';
import { CostPanel } from '@/components/shipments/cost-panel';
import { deliveryWindow } from '@/components/shipments/rate-card';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/input';
import { countryName, flagEmoji } from '@/lib/format';
import { formatMoney, minorFromMajor } from '@/lib/money';
import { cn } from '@/lib/utils';
import type { AddressDraft, SelectedQuote, ShipmentDraft } from '@/lib/wizard';

function ReviewCard({ title, icon: Icon, onEdit, children, className }: { title: string; icon: LucideIcon; onEdit: () => void; children: ReactNode; className?: string }) {
  return (
    <section className={cn('rounded-xl border border-border bg-surface p-5 shadow-xs', className)} aria-label={title}>
      <div className="flex items-center justify-between gap-3">
        <h3 className="flex items-center gap-2 text-small font-bold">
          <span className="grid h-7 w-7 place-items-center rounded-md bg-primary-soft text-primary">
            <Icon className="h-4 w-4" aria-hidden="true" />
          </span>
          {title}
        </h3>
        <Button type="button" variant="ghost" size="sm" className="h-8 min-h-8 px-2 text-primary" onClick={onEdit} aria-label={`Edit ${title.toLowerCase()}`}>
          <Pencil className="h-3.5 w-3.5" aria-hidden="true" />
          Edit
        </Button>
      </div>
      <div className="mt-4">{children}</div>
    </section>
  );
}

function Row({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="grid gap-0.5">
      <dt className="text-[12px] font-semibold uppercase tracking-[0.08em] text-subtle-foreground">{label}</dt>
      <dd className="text-[14px] text-foreground">{children}</dd>
    </div>
  );
}

function AddressDetails({ address, saved }: { address: AddressDraft; saved?: SavedAddress }) {
  const source =
    address.mode === 'saved'
      ? saved
      : {
          contactName: address.contactName,
          companyName: address.companyName,
          line1: address.line1,
          line2: address.line2,
          city: address.city,
          state: address.state,
          postalCode: address.postalCode,
          countryCode: address.countryCode,
          phone: address.phone,
        };
  if (source === undefined) return <p className="text-small text-muted-foreground">Saved address</p>;
  return (
    <dl className="grid gap-3">
      <Row label="Contact">
        <span className="font-semibold">{source.contactName}</span>
        {source.companyName ? <span className="text-muted-foreground"> · {source.companyName}</span> : null}
      </Row>
      <Row label="Address">
        <span className="block">{[source.line1, source.line2].filter(Boolean).join(', ')}</span>
        <span className="block">{[source.city, source.state, source.postalCode].filter(Boolean).join(', ')}</span>
        <span className="block">
          <span aria-hidden="true">{flagEmoji(source.countryCode)} </span>
          {countryName(source.countryCode)}
        </span>
      </Row>
      {source.phone ? <Row label="Phone">{source.phone}</Row> : null}
    </dl>
  );
}

export function ReviewStep({
  draft,
  quote,
  addresses,
  international,
  balanceMinor,
  emailUnverified,
  confirmed,
  disabled,
  onConfirmedChange,
  onEditStep,
  onTopUp,
}: {
  draft: ShipmentDraft;
  quote: SelectedQuote;
  addresses: SavedAddress[];
  international: boolean;
  balanceMinor: number;
  emailUnverified: boolean;
  confirmed: boolean;
  disabled: boolean;
  onConfirmedChange: (confirmed: boolean) => void;
  onEditStep: (step: number) => void;
  onTopUp: () => void;
}) {
  const weightUnit = draft.unit === 'metric' ? 'kg' : 'lb';
  const sizeUnit = draft.unit === 'metric' ? 'cm' : 'in';
  const shortfall = Math.max(0, quote.totalMinor - balanceMinor);
  const savedSender = addresses.find((address) => address.id === draft.sender.addressId);
  const savedRecipient = addresses.find((address) => address.id === draft.recipient.addressId);
  const insured = draft.isInsured ? minorFromMajor(draft.insuredAmount) ?? undefined : undefined;

  return (
    <div className="grid gap-5">
      <div className="grid gap-4 md:grid-cols-2">
        <ReviewCard title="Sender" icon={PackageOpen} onEdit={() => onEditStep(0)}>
          <AddressDetails address={draft.sender} saved={savedSender} />
        </ReviewCard>
        <ReviewCard title="Recipient" icon={MapPin} onEdit={() => onEditStep(0)}>
          <AddressDetails address={draft.recipient} saved={draft.recipient.mode === 'saved' ? savedRecipient : undefined} />
        </ReviewCard>
        <ReviewCard title="Package and items" icon={Package} onEdit={() => onEditStep(1)}>
          <dl className="grid gap-3">
            <Row label={draft.parcels.length === 1 ? 'Parcel' : `${draft.parcels.length} parcels`}>
              <span className="flex flex-wrap gap-1.5">
                {draft.parcels.map((parcel, index) => (
                  <span key={index} className="rounded-pill bg-surface-muted px-2.5 py-0.5 text-caption font-medium tabular-nums">
                    {parcel.weight} {weightUnit} · {parcel.length} × {parcel.width} × {parcel.height} {sizeUnit}
                  </span>
                ))}
              </span>
            </Row>
            <Row label="Items">
              {draft.items.length === 0 ? <span className="text-muted-foreground">None declared</span> : draft.items.map((item) => `${item.quantity} × ${item.description || 'Item'}`).join(', ')}
            </Row>
          </dl>
        </ReviewCard>
        <ReviewCard title="Options" icon={Settings2} onEdit={() => onEditStep(2)}>
          <dl className="grid gap-3">
            {international ? <Row label="Duties and taxes">{draft.taxesDutiesPaidBy === 'Sender' ? 'Paid by sender' : 'Paid by recipient'}</Row> : null}
            <Row label="Insurance">{insured === undefined ? 'Not insured' : `Insured for ${formatMoney(insured, quote.currency)}`}</Row>
            {draft.reference.length > 0 ? <Row label="Reference">{draft.reference}</Row> : null}
          </dl>
        </ReviewCard>
        <ReviewCard title="Courier and service" icon={Truck} onEdit={() => onEditStep(3)} className="md:col-span-2">
          <div className="flex items-center gap-4">
            <Avatar name={quote.courierName} size="lg" shape="square" className="h-12 w-12 rounded-xl" />
            <div className="min-w-0 flex-1">
              <p className="truncate text-[16px] font-semibold">{quote.courierName}</p>
              <p className="truncate text-small text-muted-foreground">
                {quote.serviceName} · {deliveryWindow(quote)}
              </p>
            </div>
            <p className="font-display text-[22px] font-extrabold tabular-nums">{formatMoney(quote.totalMinor, quote.currency)}</p>
          </div>
        </ReviewCard>
      </div>

      <CostPanel totalMinor={quote.totalMinor} currency={quote.currency} balanceMinor={balanceMinor} insuredMinor={insured} />

      {emailUnverified ? (
        <div className="flex items-start gap-3 rounded-lg border border-info/25 bg-info-soft px-4 py-3 text-small" role="alert">
          <MailWarning className="mt-0.5 h-[18px] w-[18px] shrink-0 text-info" aria-hidden="true" />
          <p>
            <span className="font-semibold">Verify your email before buying a label.</span>{' '}
            <span className="text-muted-foreground">Check your inbox for the verification link.</span>
          </p>
        </div>
      ) : null}

      {shortfall > 0 ? (
        <div className="flex flex-wrap items-center gap-3 rounded-lg border border-danger/25 bg-danger-soft px-4 py-3" role="alert">
          <AlertCircle className="h-[18px] w-[18px] shrink-0 text-danger" aria-hidden="true" />
          <p className="min-w-0 flex-1 text-small">
            <span className="font-semibold">Insufficient funds.</span>{' '}
            <span className="text-muted-foreground">
              Your wallet is short by <span className="font-bold text-foreground">{formatMoney(shortfall, quote.currency)}</span>.
            </span>
          </p>
          <Button type="button" size="sm" onClick={onTopUp}>
            <Plus className="h-4 w-4" aria-hidden="true" />
            Top up
          </Button>
        </div>
      ) : null}

      <label
        className={cn(
          'flex cursor-pointer items-start gap-3 rounded-lg border p-4 transition-colors',
          confirmed ? 'border-primary bg-primary-soft' : 'border-border bg-surface hover:border-border-strong',
          disabled && 'cursor-not-allowed opacity-60',
        )}
      >
        <Checkbox checked={confirmed} disabled={disabled} onChange={(event) => onConfirmedChange(event.target.checked)} />
        <span className="text-small text-foreground">I confirm the details are correct and understand labels may not be cancellable after pickup.</span>
      </label>
    </div>
  );
}
