'use client';

import { AlertTriangle, Ban, Download, LoaderCircle, Plus, RotateCw, XCircle, type LucideIcon } from 'lucide-react';
import Link from 'next/link';
import type { ReactNode } from 'react';

import { SuccessBurst } from '@/components/illustrations/success-burst';
import { Button, buttonVariants } from '@/components/ui/button';
import { DateText, MoneyText } from '@/components/ui/money-text';
import type { ShipmentListItem } from '@/lib/shipments';
import { cn } from '@/lib/utils';

const tones = {
  info: { box: 'border-info/25 bg-info-soft', chip: 'bg-surface text-info' },
  danger: { box: 'border-danger/25 bg-danger-soft', chip: 'bg-surface text-danger' },
  warning: { box: 'border-warning/30 bg-warning-soft', chip: 'bg-surface text-warning' },
  neutral: { box: 'border-border bg-surface-muted', chip: 'bg-surface text-muted-foreground' },
} as const;

function Banner({
  tone,
  icon: Icon,
  spin = false,
  title,
  children,
  action,
  alert = false,
}: {
  tone: keyof typeof tones;
  icon: LucideIcon;
  spin?: boolean;
  title: ReactNode;
  children?: ReactNode;
  action?: ReactNode;
  alert?: boolean;
}) {
  return (
    <div className={cn('flex flex-wrap items-start gap-3 rounded-lg border px-4 py-3.5', tones[tone].box)} role={alert ? 'alert' : 'status'}>
      <span className={cn('grid h-9 w-9 shrink-0 place-items-center rounded-md shadow-xs', tones[tone].chip)}>
        <Icon className={cn('h-[18px] w-[18px]', spin && 'animate-spin')} aria-hidden="true" />
      </span>
      <div className="min-w-0 flex-1 pt-0.5">
        <p className="text-small font-semibold text-foreground">{title}</p>
        {children === undefined ? null : <div className="mt-0.5 text-small text-muted-foreground">{children}</div>}
      </div>
      {action === undefined ? null : <div className="flex shrink-0 flex-wrap gap-2 self-center">{action}</div>}
    </div>
  );
}

export function StatusBanner({ shipment }: { shipment: ShipmentListItem }) {
  if (shipment.status === 'PENDING') {
    return (
      <Banner tone="info" icon={LoaderCircle} spin title="We are creating your shipment.">
        This page updates automatically.
      </Banner>
    );
  }
  if (shipment.status === 'FAILED') {
    return (
      <Banner
        tone="danger"
        icon={XCircle}
        alert
        title={shipment.failureReason ?? 'The shipment failed.'}
        action={
          <Link href={`/shipments/new?duplicate=${shipment.id}`} className={buttonVariants({ size: 'sm' })}>
            <RotateCw className="h-3.5 w-3.5" aria-hidden="true" />
            Try again
          </Link>
        }
      >
        The full amount was returned to your wallet.
      </Banner>
    );
  }
  if (shipment.status === 'CANCELLED') {
    return (
      <Banner tone="neutral" icon={Ban} title="This shipment was cancelled.">
        {shipment.cancelledAt === undefined ? null : (
          <>
            Cancelled <DateText value={shipment.cancelledAt} />
          </>
        )}
        {shipment.chargedMinor === undefined ? null : (
          <>
            {shipment.cancelledAt === undefined ? 'R' : '. R'}efunded <MoneyText minor={shipment.chargedMinor} currency={shipment.currency} /> to your wallet.
          </>
        )}
      </Banner>
    );
  }
  if (shipment.status === 'EXCEPTION') {
    const latest = shipment.events?.[shipment.events.length - 1];
    return (
      <Banner tone="warning" icon={AlertTriangle} alert title={latest?.description ?? 'The courier reported an exception.'}>
        Contact the courier or support with the tracking number.
      </Banner>
    );
  }
  return null;
}

export function CreatedBanner({ shipmentId }: { shipmentId: string }) {
  return (
    <div className="flex flex-wrap items-center gap-4 rounded-xl border border-success/25 bg-success-soft px-4 py-3" role="status">
      <SuccessBurst size={56} className="-my-2 shrink-0" />
      <div className="min-w-0 flex-1">
        <p className="font-display text-h3 font-bold text-foreground">Your label is ready</p>
        <p className="text-small text-muted-foreground">Download it, print it and attach it to the parcel.</p>
      </div>
      <div className="flex flex-wrap gap-2">
        <Button type="button" size="sm" onClick={() => document.getElementById('download-label')?.click()}>
          <Download className="h-3.5 w-3.5" aria-hidden="true" />
          Download label
        </Button>
        <Link href="/shipments/new" className={buttonVariants({ variant: 'secondary', size: 'sm' })}>
          <Plus className="h-3.5 w-3.5" aria-hidden="true" />
          Create another shipment
        </Link>
        <span className="sr-only">{shipmentId}</span>
      </div>
    </div>
  );
}
