'use client';

import { ArrowRight, Package, Plus } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

import { Can } from '@/components/can';
import { DashCard } from '@/components/dashboard/dash-card';
import { EmptyBoxIllustration } from '@/components/illustrations';
import { StatusBadge } from '@/components/shipments/status-badge';
import { buttonVariants } from '@/components/ui/button';
import { CopyButton } from '@/components/ui/copy-button';
import { EmptyState, ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import type { RecentShipment } from '@/lib/dashboard';
import { countryName, flagEmoji, relativeTime } from '@/lib/format';
import { formatMoney } from '@/lib/money';
import { cn } from '@/lib/utils';

function Place({ shipment }: { shipment: RecentShipment }) {
  const destination = shipment.destinationAddress;
  const country = destination?.countryCode;
  const parts = [destination?.city, country === undefined ? undefined : countryName(country)].filter(Boolean);
  if (parts.length === 0) return null;
  return (
    <span className="block truncate text-caption text-muted-foreground">
      {country === undefined ? null : <span aria-hidden="true">{flagEmoji(country)} </span>}
      {parts.join(', ')}
    </span>
  );
}

function Cost({ shipment, currency }: { shipment: RecentShipment; currency: string }) {
  return shipment.chargedMinor === undefined ? <span className="text-subtle-foreground">—</span> : <>{formatMoney(shipment.chargedMinor, shipment.currency ?? currency)}</>;
}

export function RecentShipments({
  rows,
  currency,
  loading,
  error,
  onRetry,
}: {
  rows: RecentShipment[];
  currency: string;
  loading?: boolean;
  error?: string;
  onRetry?: () => void;
}) {
  const router = useRouter();
  return (
    <DashCard
      title="Recent shipments"
      action={
        <Link href="/shipments" className={cn(buttonVariants({ variant: 'ghost', size: 'sm' }), 'group -mr-2 text-primary')}>
          View all
          <ArrowRight className="h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
        </Link>
      }
    >
      {loading ? (
        <div className="grid gap-3">
          {[0, 1, 2, 3, 4].map((index) => (
            <Skeleton key={index} className="h-12 w-full" />
          ))}
        </div>
      ) : null}
      {!loading && error !== undefined ? <ErrorState message={error} onRetry={onRetry} /> : null}
      {!loading && error === undefined && rows.length === 0 ? (
        <EmptyState
          illustration={<EmptyBoxIllustration size={96} />}
          title="No shipments yet"
          description="Create your first shipment to compare courier rates and buy a label."
          action={
            <Can permission="shipments:create">
              <Link href="/shipments/new" className={buttonVariants({ size: 'sm' })}>
                <Plus className="h-4 w-4" aria-hidden="true" />
                Create a shipment
              </Link>
            </Can>
          }
        />
      ) : null}
      {!loading && error === undefined && rows.length > 0 ? (
        <>
          {/* Desktop table */}
          <div className="-mx-5 hidden overflow-x-auto md:-mx-6 md:block">
            <table className="w-full min-w-[760px] text-left text-small">
              <thead>
                <tr className="h-11 border-y border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  <th scope="col" className="px-6 font-semibold">Tracking</th>
                  <th scope="col" className="px-3 font-semibold">Recipient</th>
                  <th scope="col" className="px-3 font-semibold">Courier</th>
                  <th scope="col" className="px-3 font-semibold">Status</th>
                  <th scope="col" className="px-3 text-right font-semibold">Cost</th>
                  <th scope="col" className="px-6 text-right font-semibold">Created</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((shipment) => {
                  const href = `/shipments/${shipment.id}`;
                  return (
                    <tr
                      key={shipment.id}
                      className="group h-14 cursor-pointer border-b border-border transition-colors last:border-b-0 hover:bg-surface-muted/60"
                      onClick={() => router.push(href)}
                    >
                      <td className="px-6">
                        <span className="flex items-center gap-1">
                          <Link href={href} className="rounded-sm font-mono text-small font-semibold text-foreground underline-offset-4 hover:underline" onClick={(event) => event.stopPropagation()}>
                            {shipment.trackingNumber ?? 'Pending'}
                          </Link>
                          {shipment.trackingNumber === undefined ? null : (
                            <CopyButton value={shipment.trackingNumber} label="Copy tracking number" className="opacity-0 focus-visible:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100" />
                          )}
                        </span>
                      </td>
                      <td className="max-w-[220px] px-3">
                        <span className="block truncate font-medium text-foreground">{shipment.destinationAddress?.contactName ?? 'Recipient'}</span>
                        <Place shipment={shipment} />
                      </td>
                      <td className="px-3 text-muted-foreground">{shipment.courierName ?? '—'}</td>
                      <td className="px-3">{shipment.status === undefined ? null : <StatusBadge status={shipment.status} />}</td>
                      <td className="px-3 text-right font-semibold tabular-nums text-foreground">
                        <Cost shipment={shipment} currency={currency} />
                      </td>
                      <td className="whitespace-nowrap px-6 text-right text-muted-foreground">
                        {shipment.createdAt === undefined ? '—' : <time dateTime={shipment.createdAt}>{relativeTime(shipment.createdAt)}</time>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Mobile cards */}
          <ul className="grid gap-2 md:hidden">
            {rows.map((shipment) => (
              <li key={shipment.id}>
                <Link href={`/shipments/${shipment.id}`} className="block rounded-lg border border-border p-3 transition-colors hover:bg-surface-muted">
                  <span className="flex items-center justify-between gap-2">
                    <span className="inline-flex min-w-0 items-center gap-2 font-mono text-small font-semibold">
                      <Package className="h-4 w-4 shrink-0 text-subtle-foreground" aria-hidden="true" />
                      <span className="truncate">{shipment.trackingNumber ?? 'Pending'}</span>
                    </span>
                    {shipment.status === undefined ? null : <StatusBadge status={shipment.status} />}
                  </span>
                  <span className="mt-2 flex items-end justify-between gap-3">
                    <span className="min-w-0">
                      <span className="block truncate text-small font-medium">{shipment.destinationAddress?.contactName ?? 'Recipient'}</span>
                      <Place shipment={shipment} />
                    </span>
                    <span className="shrink-0 text-small font-semibold tabular-nums">
                      <Cost shipment={shipment} currency={currency} />
                    </span>
                  </span>
                </Link>
              </li>
            ))}
          </ul>
        </>
      ) : null}
    </DashCard>
  );
}
