'use client';

import Link from 'next/link';
import { useParams, useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useRef, useState, type ReactNode } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, Ban, ChevronRight, Copy, Download, ExternalLink, Printer, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

import { NoResultsIllustration } from '@/components/illustrations';
import { PageTitle } from '@/components/layout/page-header';
import { ActivityList } from '@/components/shipments/activity-list';
import { CancelShipmentDialog } from '@/components/shipments/cancel-shipment-dialog';
import { CostSummaryCard } from '@/components/shipments/cost-summary-card';
import { JourneyTrack } from '@/components/shipments/journey-track';
import { PackageItemsTable } from '@/components/shipments/package-items-table';
import { RouteCard } from '@/components/shipments/route-card';
import { CreatedBanner, StatusBanner } from '@/components/shipments/status-banner';
import { StatusBadge } from '@/components/shipments/status-badge';
import { TrackingTimeline } from '@/components/shipments/tracking-timeline';
import { Avatar } from '@/components/ui/avatar';
import { Button, buttonVariants } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { CopyButton } from '@/components/ui/copy-button';
import { Menu, type MenuItem } from '@/components/ui/menu';
import { DateText } from '@/components/ui/money-text';
import { EmptyState, ErrorState, ForbiddenState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, api, apiBlob, downloadBlob, openBlob } from '@/lib/api-client';
import { usePermission } from '@/hooks/use-permission';
import { queryKeys } from '@/lib/query-keys';
import {
  canCancelShipment,
  isLabelReady,
  type ActivityEntry,
  type ShipmentListItem,
} from '@/lib/shipments';

export default function ShipmentDetailPage() {
  return (
    <Suspense fallback={<DetailSkeleton />}>
      <ShipmentDetail />
    </Suspense>
  );
}

function ShipmentDetail() {
  const allowed = usePermission('shipments:read');
  const canCancel = usePermission('shipments:cancel');
  const params = useParams<{ id: string }>();
  const search = useSearchParams();
  const created = search.get('created') === '1';
  const queryClient = useQueryClient();
  const [cancelOpen, setCancelOpen] = useState(false);
  const [refreshError, setRefreshError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const mountedAt = useRef(0);

  useEffect(() => {
    mountedAt.current = Date.now();
  }, [params.id]);

  const shipment = useQuery({
    queryKey: queryKeys.shipment(params.id),
    enabled: allowed,
    queryFn: () => api<ShipmentListItem>(`/shipments/${params.id}`),
    refetchInterval: (query) => {
      if (query.state.data?.status !== 'PENDING') return false;
      if (mountedAt.current === 0) return 3000;
      return Date.now() - mountedAt.current < 120_000 ? 3000 : 30_000;
    },
  });
  const activity = useQuery({
    queryKey: queryKeys.shipmentActivity(params.id),
    enabled: allowed && shipment.isSuccess,
    queryFn: () => api<ActivityEntry[]>(`/shipments/${params.id}/activity`),
  });

  if (!allowed) return <ForbiddenState />;
  if (shipment.error instanceof ApiError && shipment.error.status === 404) {
    return (
      <Card>
        <EmptyState
          illustration={<NoResultsIllustration size={120} />}
          title="Shipment not found"
          description="It may have been removed, or the link is incorrect."
          action={
            <Link href="/shipments" className={buttonVariants({ variant: 'secondary' })}>
              <ArrowLeft className="h-4 w-4" aria-hidden="true" />
              Back to shipments
            </Link>
          }
        />
      </Card>
    );
  }
  if (shipment.error instanceof ApiError) {
    return (
      <Card>
        <ErrorState message={shipment.error.message} requestId={shipment.error.requestId} onRetry={() => void shipment.refetch()} />
      </Card>
    );
  }
  if (shipment.isLoading || shipment.data === undefined) return <DetailSkeleton />;

  const data = shipment.data;
  const title = data.reference ?? data.id.slice(-8);
  const breadcrumb = `Shipments / ${data.trackingNumber ?? data.id}`;
  const labelReady = isLabelReady(data);

  const downloadLabel = () => {
    void apiBlob(`/shipments/${data.id}/label`)
      .then((blob) => downloadBlob(blob, `${data.id}.pdf`))
      .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'The label could not be downloaded.'));
  };
  const printLabel = () => {
    void apiBlob(`/shipments/${data.id}/label`)
      .then((blob) => openBlob(blob))
      .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'The label could not be opened.'));
  };
  const refreshStatus = () => {
    setRefreshing(true);
    setRefreshError(null);
    void api<ShipmentListItem>(`/shipments/${data.id}/refresh`, { method: 'POST' })
      .then((updated) => {
        queryClient.setQueryData(queryKeys.shipment(data.id), updated);
        toast.success('Status refreshed.');
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : 'Refresh failed.';
        setRefreshError(message);
        toast.error(message);
      })
      .finally(() => setRefreshing(false));
  };

  const menuItems: MenuItem[] = [
    { label: 'Duplicate', icon: Copy, href: `/shipments/new?duplicate=${data.id}` },
    { label: refreshing ? 'Refreshing status' : 'Refresh status', icon: RefreshCw, disabled: refreshing, onSelect: refreshStatus },
    ...(canCancel
      ? ([
          { type: 'divider' },
          {
            label: 'Cancel shipment',
            icon: Ban,
            danger: true,
            disabled: !canCancelShipment(data.status),
            disabledReason: 'Only shipments that are created or have a label ready can be cancelled',
            onSelect: () => setCancelOpen(true),
          },
        ] satisfies MenuItem[])
      : []),
  ];

  return (
    <div className="grid gap-6">
      <PageTitle title={title} breadcrumb={breadcrumb} />

      <Card className="p-5 md:p-6">
        <nav aria-label="Breadcrumb" className="flex items-center gap-1 text-caption text-muted-foreground">
          <Link href="/shipments" className="rounded-sm hover:text-foreground hover:underline">
            Shipments
          </Link>
          <ChevronRight className="h-3 w-3" aria-hidden="true" />
          <span className="truncate font-mono">{data.trackingNumber ?? data.id}</span>
        </nav>
        <div className="mt-3 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div className="min-w-0">
            <div className="flex flex-wrap items-center gap-3">
              <h1 className="truncate font-display text-[28px] font-bold leading-9 tracking-[-0.02em]">{title}</h1>
              <StatusBadge status={data.status} className="text-small" />
            </div>
            {data.trackingNumber === undefined ? (
              <p className="mt-1 text-small text-muted-foreground">Tracking number pending</p>
            ) : (
              <p className="mt-1 flex items-center gap-1 font-mono text-small text-muted-foreground">
                {data.trackingNumber}
                <CopyButton notify value={data.trackingNumber} label="Copy tracking number" />
              </p>
            )}
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <Button id="download-label" type="button" disabled={!labelReady} onClick={downloadLabel}>
              <Download className="h-4 w-4" aria-hidden="true" />
              Download label
            </Button>
            <Button type="button" variant="secondary" disabled={!labelReady} onClick={printLabel}>
              <Printer className="h-4 w-4" aria-hidden="true" />
              Print label
            </Button>
            {data.trackingPageUrl === undefined ? null : (
              <a href={data.trackingPageUrl} target="_blank" rel="noreferrer" className={buttonVariants({ variant: 'ghost' })}>
                <ExternalLink className="h-4 w-4" aria-hidden="true" />
                Track on courier site
              </a>
            )}
            <Menu items={menuItems} label="More shipment actions" />
          </div>
        </div>
        {refreshError === null ? null : <p className="mt-2 text-caption text-danger">{refreshError}</p>}
        <div className="mt-6 border-t border-border pt-5">
          <JourneyTrack status={data.status} />
        </div>
      </Card>

      {created ? <CreatedBanner shipmentId={data.id} /> : null}
      <StatusBanner shipment={data} />

      {/* Mobile: single column in the order Tracking, Route, Summary, Package, Cost, Activity.
          Desktop: two columns (2/3 and 1/3). The column wrappers use display: contents below 1024px. */}
      <div className="flex flex-col gap-6 lg:grid lg:grid-cols-3 lg:items-start">
        <div className="contents lg:col-span-2 lg:grid lg:gap-6">
          <Card className="order-1 p-5 md:p-6">
            <h2 className="mb-4 font-display text-h3 font-bold">Tracking</h2>
            <TrackingTimeline events={data.events ?? []} {...(data.estimatedDeliveryAt === undefined ? {} : { estimatedDeliveryAt: data.estimatedDeliveryAt })} />
          </Card>
          <div className="order-4">
            <PackageItemsTable shipment={data} />
          </div>
          <div className="order-6">
            <ActivityList entries={activity.data ?? []} />
          </div>
        </div>
        <div className="contents lg:grid lg:gap-6">
          <div className="order-2">
            <RouteCard origin={data.originAddress} destination={data.destinationAddress} />
          </div>
          <Card className="order-3 p-5 md:p-6">
            <h2 className="font-display text-h3 font-bold">Summary</h2>
            <dl className="mt-4 grid gap-3 text-small">
              <SummaryRow label="Courier and service">
                {data.courierName === undefined ? (
                  '—'
                ) : (
                  <span className="inline-flex items-center gap-2">
                    <Avatar name={data.courierName} size="xs" shape="square" className="rounded" />
                    {data.courierName}
                    {data.serviceName === undefined ? '' : ` · ${data.serviceName}`}
                  </span>
                )}
              </SummaryRow>
              <SummaryRow label="Created">
                <DateText value={data.createdAt} />
              </SummaryRow>
              <SummaryRow label="Created by">
                <span className="inline-flex items-center gap-2">
                  <Avatar name={data.createdBy.name} size="xs" />
                  {data.createdBy.name}
                </span>
              </SummaryRow>
              <SummaryRow label="Reference">{data.reference ?? '—'}</SummaryRow>
              <SummaryRow label="Insurance">{data.isInsured ? 'Insured' : 'Not insured'}</SummaryRow>
              <SummaryRow label="Duties and taxes paid by">{data.taxesDutiesPaidBy ?? '—'}</SummaryRow>
            </dl>
          </Card>
          <div className="order-5">
            <CostSummaryCard shipment={data} />
          </div>
        </div>
      </div>

      <CancelShipmentDialog
        shipment={data}
        open={cancelOpen}
        onClose={() => setCancelOpen(false)}
        onCancelled={(updated) => {
          queryClient.setQueryData(queryKeys.shipment(data.id), updated);
          void queryClient.invalidateQueries({ queryKey: queryKeys.shipmentActivity(data.id) });
          setCancelOpen(false);
        }}
      />
    </div>
  );
}

function SummaryRow({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="flex items-start justify-between gap-4 border-b border-border pb-3 last:border-b-0 last:pb-0">
      <dt className="text-muted-foreground">{label}</dt>
      <dd className="text-right font-medium text-foreground">{children}</dd>
    </div>
  );
}

function DetailSkeleton() {
  return (
    <div className="grid gap-6" aria-hidden="true">
      <Card className="p-5 md:p-6">
        <Skeleton className="h-3 w-40" />
        <div className="mt-4 flex flex-wrap items-center justify-between gap-4">
          <div className="grid gap-2">
            <Skeleton className="h-8 w-56" />
            <Skeleton className="h-4 w-40" />
          </div>
          <div className="flex gap-2">
            <Skeleton className="h-10 w-36" />
            <Skeleton className="h-10 w-28" />
          </div>
        </div>
        <Skeleton className="mt-8 h-6 w-full rounded-pill" />
      </Card>
      <div className="grid gap-6 lg:grid-cols-3">
        <div className="grid gap-6 lg:col-span-2">
          <Card className="grid gap-5 p-6">
            {[0, 1, 2, 3].map((index) => (
              <div key={index} className="flex gap-4">
                <Skeleton className="h-8 w-8 rounded-full" />
                <div className="grid flex-1 gap-2">
                  <Skeleton className="h-4 w-2/3" />
                  <Skeleton className="h-3 w-1/3" />
                </div>
              </div>
            ))}
          </Card>
          <Skeleton className="h-48 rounded-lg" />
        </div>
        <div className="grid gap-6">
          <Skeleton className="h-64 rounded-lg" />
          <Skeleton className="h-56 rounded-lg" />
          <Skeleton className="h-40 rounded-lg" />
        </div>
      </div>
    </div>
  );
}
