'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { ArrowDown, ArrowUp, ChevronsUpDown, Download, Plus, RefreshCw } from 'lucide-react';

import { Can } from '@/components/can';
import { EmptyBoxIllustration, NoResultsIllustration } from '@/components/illustrations';
import { PageHeader } from '@/components/layout/page-header';
import { CancelShipmentDialog } from '@/components/shipments/cancel-shipment-dialog';
import { ShipmentCard } from '@/components/shipments/shipment-card';
import { ShipmentRowActions } from '@/components/shipments/shipment-row-actions';
import { ShipmentsFilterBar } from '@/components/shipments/shipments-filter-bar';
import { StatusBadge } from '@/components/shipments/status-badge';
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 { Checkbox } from '@/components/ui/input';
import { MoneyText } from '@/components/ui/money-text';
import { Pagination } from '@/components/ui/pagination';
import { EmptyState, ErrorState, ForbiddenState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip } from '@/components/ui/tooltip';
import { ApiError, api, apiBlob, apiEnvelope, downloadBlob } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { countryName, flagEmoji } from '@/lib/format';
import { usePermission } from '@/hooks/use-permission';
import { queryKeys } from '@/lib/query-keys';
import { cn } from '@/lib/utils';
import {
  formatRelative,
  isFinalStatus,
  parseShipmentFilters,
  shipmentFiltersToSearch,
  shipmentQueryString,
  type ShipmentListFilters,
  type ShipmentListItem,
} from '@/lib/shipments';

interface PaginatedShipments {
  data: ShipmentListItem[];
  meta: { page: number; pageSize: number; total: number; totalPages: number };
}

export default function ShipmentsPage() {
  return (
    <Suspense fallback={<Skeleton className="h-64" />}>
      <ShipmentsPageInner />
    </Suspense>
  );
}

function ShipmentsPageInner() {
  const allowed = usePermission('shipments:read');
  const canCreate = usePermission('shipments:create');
  const canManageTeam = usePermission('team:manage');
  const { user } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const queryClient = useQueryClient();
  const filters = useMemo(() => parseShipmentFilters(new URLSearchParams(searchParams.toString())), [searchParams]);
  const [selected, setSelected] = useState<string[]>([]);
  const [cancelTarget, setCancelTarget] = useState<ShipmentListItem | null>(null);
  const [tabVisible, setTabVisible] = useState(true);

  const setFilters = useCallback(
    (next: ShipmentListFilters) => {
      const query = shipmentFiltersToSearch(next);
      router.replace(query.length === 0 ? pathname : `${pathname}?${query}`);
    },
    [pathname, router],
  );

  const listQuery = shipmentQueryString(filters);
  const list = useQuery({
    queryKey: queryKeys.shipments(listQuery),
    enabled: allowed,
    queryFn: () => apiEnvelope<PaginatedShipments>(`/shipments${listQuery}`),
  });

  useEffect(() => {
    const onVisibility = () => setTabVisible(document.visibilityState === 'visible');
    onVisibility();
    document.addEventListener('visibilitychange', onVisibility);
    return () => document.removeEventListener('visibilitychange', onVisibility);
  }, []);

  const updatedAt = list.dataUpdatedAt > 0 ? new Date(list.dataUpdatedAt) : null;

  const rows = useMemo(() => list.data?.data ?? [], [list.data]);
  const hasLiveRows = rows.some((row) => !isFinalStatus(row.status));
  useEffect(() => {
    if (!hasLiveRows || !tabVisible) return undefined;
    const timer = window.setInterval(() => {
      void list.refetch();
    }, 60_000);
    return () => window.clearInterval(timer);
  }, [hasLiveRows, tabVisible, list]);

  // Highlight rows whose status changed after a background refetch (UI only).
  const reduce = useReducedMotion();
  const [flashing, setFlashing] = useState<string[]>([]);
  const previousStatuses = useRef<Map<string, string> | null>(null);
  useEffect(() => {
    const previous = previousStatuses.current;
    const current = new Map(rows.map((row) => [row.id, row.status]));
    previousStatuses.current = current;
    if (previous === null) return undefined;
    const changed = rows.filter((row) => previous.has(row.id) && previous.get(row.id) !== row.status).map((row) => row.id);
    if (changed.length === 0) return undefined;
    const show = window.setTimeout(() => setFlashing(changed), 0);
    const hide = window.setTimeout(() => setFlashing([]), 900);
    return () => {
      window.clearTimeout(show);
      window.clearTimeout(hide);
    };
  }, [rows]);

  const couriers = useQuery({
    queryKey: queryKeys.couriers,
    enabled: allowed,
    queryFn: () => api<Array<{ id: string; name: string }>>('/couriers'),
  });
  const members = useQuery({
    queryKey: queryKeys.teamMembers,
    enabled: allowed && canManageTeam,
    queryFn: () => api<Array<{ id: string; name: string }>>('/team/members'),
  });

  if (!allowed) return <ForbiddenState />;

  const meta = list.data?.meta;
  const historyCouriers = [
    ...(couriers.data ?? []),
    ...rows
      .filter((row) => row.courierId !== undefined && row.courierName !== undefined)
      .map((row) => ({ id: row.courierId as string, name: row.courierName as string })),
  ].filter((courier, index, all) => all.findIndex((item) => item.id === courier.id) === index);
  const error = list.error instanceof ApiError ? list.error : null;
  const noActiveFilters =
    filters.q.length === 0 &&
    filters.status.length === 0 &&
    filters.courierId.length === 0 &&
    filters.dateFrom.length === 0 &&
    filters.dateTo.length === 0 &&
    filters.createdById.length === 0;
  const emptyAll = !list.isLoading && error === null && (meta?.total ?? 0) === 0 && noActiveFilters;
  const emptyFiltered = !list.isLoading && error === null && rows.length === 0 && !emptyAll;
  const allSelected = rows.length > 0 && rows.every((row) => selected.includes(row.id));
  const clearFilters = () => setFilters({ ...filters, q: '', status: [], courierId: '', dateFrom: '', dateTo: '', createdById: '', page: 1 });
  const exportCsv = () => {
    void apiBlob(`/shipments/export.csv${listQuery}`, 'text/csv').then((blob) => downloadBlob(blob, 'shipments.csv'));
  };

  return (
    <div className="grid gap-5">
      <PageHeader
        title="Shipments"
        description={meta === undefined ? 'Shipment history' : `${meta.total.toLocaleString()} shipment${meta.total === 1 ? '' : 's'}`}
        actions={
          <>
            <Button type="button" variant="secondary" onClick={exportCsv}>
              <Download className="h-4 w-4" aria-hidden="true" />
              Export CSV
            </Button>
            <Can permission="shipments:create">
              <Link href="/shipments/new" className={buttonVariants()}>
                <Plus className="h-4 w-4" aria-hidden="true" />
                New shipment
              </Link>
            </Can>
          </>
        }
      />
      <ShipmentsFilterBar
        filters={filters}
        couriers={historyCouriers}
        members={members.data ?? []}
        showCreatedBy={canManageTeam || user?.role === 'OWNER' || user?.role === 'ADMIN'}
        onChange={setFilters}
      />

      <div className="-mb-2 flex items-center justify-end gap-1.5 text-caption text-subtle-foreground">
        <span aria-live="polite">{updatedAt === null ? 'Waiting for data' : `Updated ${formatRelative(updatedAt.toISOString())}`}</span>
        <button
          type="button"
          aria-label="Refresh shipments"
          className="grid h-7 w-7 place-items-center rounded-md transition-colors hover:bg-surface-muted hover:text-foreground"
          onClick={() => void list.refetch()}
        >
          <RefreshCw className={cn('h-3.5 w-3.5', list.isFetching && 'animate-spin')} aria-hidden="true" />
        </button>
      </div>

      {list.isLoading ? (
        <>
          <Card className="hidden overflow-hidden p-0 md:block">
            <div className="h-11 border-b border-border bg-surface-muted" />
            {Array.from({ length: 8 }, (_, index) => (
              <div key={index} className="flex h-14 items-center gap-6 border-b border-border px-4 last:border-b-0">
                <Skeleton className="h-4 w-4 rounded" />
                <Skeleton className="h-4 w-24" />
                <Skeleton className="h-4 w-16" />
                <Skeleton className="h-4 w-28" />
                <Skeleton className="h-4 w-32 flex-1" />
                <Skeleton className="h-5 w-20 rounded-pill" />
                <Skeleton className="h-4 w-14" />
              </div>
            ))}
          </Card>
          <div className="grid gap-3 md:hidden">
            {Array.from({ length: 8 }, (_, index) => (
              <Skeleton key={index} className="h-[124px] rounded-lg" />
            ))}
          </div>
        </>
      ) : null}
      {error !== null ? (
        <Card>
          <ErrorState message={error.message} requestId={error.requestId} onRetry={() => void list.refetch()} />
        </Card>
      ) : null}
      {emptyAll ? (
        <Card>
          <EmptyState
            illustration={<EmptyBoxIllustration size={120} />}
            title="You have not created any shipments yet"
            description="Compare couriers and buy your first label in a few minutes."
            action={
              canCreate ? (
                <Link href="/shipments/new" className={buttonVariants()}>
                  <Plus className="h-4 w-4" aria-hidden="true" />
                  Create your first shipment
                </Link>
              ) : undefined
            }
          />
        </Card>
      ) : null}
      {emptyFiltered ? (
        <Card>
          <EmptyState
            illustration={<NoResultsIllustration size={120} />}
            title="No shipments match your filters"
            description="Try a different search, or widen the date range."
            action={
              <Button type="button" variant="secondary" onClick={clearFilters}>
                Clear filters
              </Button>
            }
          />
        </Card>
      ) : null}

      {!list.isLoading && rows.length > 0 ? (
        <>
          {/* Mobile cards */}
          <div className="grid gap-3 md:hidden">
            {rows.map((shipment, index) => (
              <div key={shipment.id} className="motion-safe:animate-fade-up" style={{ animationDelay: `${Math.min(index, 10) * 20}ms` }}>
                <ShipmentCard shipment={shipment} highlighted={flashing.includes(shipment.id)} />
              </div>
            ))}
          </div>

          {/* Desktop table */}
          <Card className="relative hidden overflow-hidden p-0 md:block">
            <AnimatePresence>
              {selected.length > 0 ? (
                <motion.div
                  initial={reduce ? { opacity: 0 } : { opacity: 0, y: -44 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={reduce ? { opacity: 0 } : { opacity: 0, y: -44 }}
                  transition={{ duration: 0.18, ease: [0.2, 0.8, 0.2, 1] }}
                  className="absolute inset-x-0 top-0 z-20 flex h-11 items-center gap-3 border-b border-primary/20 bg-primary-soft px-4"
                  role="region"
                  aria-label="Selection"
                >
                  <Checkbox className="mt-0" aria-label="Select all" checked={allSelected} onChange={(event) => setSelected(event.target.checked ? rows.map((row) => row.id) : [])} />
                  <p className="text-small font-semibold text-primary" aria-live="polite">
                    {selected.length} selected
                  </p>
                  <Button
                    type="button"
                    size="sm"
                    variant="secondary"
                    className="h-8 min-h-8"
                    onClick={() => {
                      void apiBlob(`/shipments/export.csv${shipmentQueryString(filters, selected)}`, 'text/csv').then((blob) => downloadBlob(blob, 'shipments-selected.csv'));
                    }}
                  >
                    <Download className="h-3.5 w-3.5" aria-hidden="true" />
                    Export selected
                  </Button>
                  <button type="button" className="text-small font-semibold text-muted-foreground underline-offset-4 hover:text-foreground hover:underline" onClick={() => setSelected([])}>
                    Clear selection
                  </button>
                </motion.div>
              ) : null}
            </AnimatePresence>
            <div className="overflow-x-auto">
              <table className="w-full min-w-[960px] text-left text-small [&_th]:whitespace-nowrap">
                <thead>
                  <tr className="h-11 border-b border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground backdrop-blur">
                    <th scope="col" className="w-10 pl-3 pr-1.5">
                      <Checkbox className="mt-0" aria-label="Select all" checked={allSelected} onChange={(event) => setSelected(event.target.checked ? rows.map((row) => row.id) : [])} />
                    </th>
                    <SortHeader label="Created" field="createdAt" sort={filters.sort} onSort={(sort) => setFilters({ ...filters, sort, page: 1 })} />
                    <th scope="col" className="px-2.5 font-semibold">Reference</th>
                    <th scope="col" className="px-2.5 font-semibold">Tracking</th>
                    <th scope="col" className="px-2.5 font-semibold">Recipient</th>
                    <th scope="col" className="px-2.5 font-semibold">Courier</th>
                    <th scope="col" className="px-2.5 font-semibold">Status</th>
                    <SortHeader label="Cost" field="chargedMinor" align="right" sort={filters.sort} onSort={(sort) => setFilters({ ...filters, sort, page: 1 })} />
                    <th scope="col" className="hidden px-2.5 font-semibold xl:table-cell">Created by</th>
                    <th scope="col" className="w-11 pr-2">
                      <span className="sr-only">Actions</span>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((shipment, index) => {
                    const isSelected = selected.includes(shipment.id);
                    const destination = shipment.destinationAddress;
                    return (
                      <tr
                        key={shipment.id}
                        className={cn(
                          'group h-14 cursor-pointer border-b border-border transition-colors duration-180 last:border-b-0 hover:bg-surface-muted/60 motion-safe:animate-fade-up',
                          isSelected && 'bg-primary-soft/50',
                          flashing.includes(shipment.id) && 'motion-safe:animate-[row-flash_800ms_ease-out]',
                        )}
                        style={{ animationDelay: `${Math.min(index, 10) * 20}ms` }}
                        onClick={() => router.push(`/shipments/${shipment.id}`)}
                      >
                        <td className="pl-3 pr-1.5" onClick={(event) => event.stopPropagation()}>
                          <Checkbox
                            className="mt-0"
                            aria-label={`Select ${shipment.trackingNumber ?? shipment.id}`}
                            checked={isSelected}
                            onChange={(event) => setSelected((current) => (event.target.checked ? [...current, shipment.id] : current.filter((id) => id !== shipment.id)))}
                          />
                        </td>
                        <td className="whitespace-nowrap px-2.5">
                          <span className="block text-[14px] text-foreground">{new Date(shipment.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}</span>
                          <span className="block text-caption text-muted-foreground">
                            {new Date(shipment.createdAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} · {formatRelative(shipment.createdAt)}
                          </span>
                        </td>
                        <td className="max-w-[140px] truncate px-2.5 text-muted-foreground">{shipment.reference ?? <span className="text-subtle-foreground">—</span>}</td>
                        <td className="px-2.5" onClick={(event) => event.stopPropagation()}>
                          {shipment.trackingNumber === undefined ? (
                            <span className="text-subtle-foreground">—</span>
                          ) : (
                            <span className="flex items-center gap-1">
                              <Link href={`/shipments/${shipment.id}`} className="rounded-sm font-mono text-small font-semibold text-foreground underline-offset-4 hover:underline">
                                {shipment.trackingNumber}
                              </Link>
                              <CopyButton notify value={shipment.trackingNumber} label="Copy tracking number" className="opacity-0 transition-opacity focus-visible:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100" />
                            </span>
                          )}
                        </td>
                        <td className="max-w-[220px] px-2.5">
                          <span className="block truncate font-semibold text-foreground">{destination.contactName}</span>
                          <span className="block truncate text-caption text-muted-foreground">
                            <span aria-hidden="true">{flagEmoji(destination.countryCode)} </span>
                            {destination.city}, {countryName(destination.countryCode)}
                          </span>
                        </td>
                        <td className="max-w-[200px] px-2.5">
                          {shipment.courierName === undefined ? (
                            <span className="text-subtle-foreground">—</span>
                          ) : (
                            <span className="flex items-center gap-2">
                              <Avatar name={shipment.courierName} size="sm" shape="square" className="h-7 w-7 rounded-md text-[10px]" />
                              <span className="min-w-0">
                                <span className="block truncate font-medium text-foreground">{shipment.courierName}</span>
                                {shipment.serviceName === undefined ? null : <span className="block truncate text-caption text-muted-foreground">{shipment.serviceName}</span>}
                              </span>
                            </span>
                          )}
                        </td>
                        <td className="px-2.5">
                          <StatusBadge status={shipment.status} />
                        </td>
                        <td className="whitespace-nowrap px-2.5 text-right font-semibold tabular-nums text-foreground">
                          {shipment.chargedMinor === undefined ? <span className="text-subtle-foreground">—</span> : <MoneyText minor={shipment.chargedMinor} currency={shipment.currency} />}
                        </td>
                        <td className="hidden px-2.5 xl:table-cell">
                          <Tooltip label={shipment.createdBy.name}>
                            <span tabIndex={0} aria-label={`Created by ${shipment.createdBy.name}`} className="rounded-full">
                              <Avatar name={shipment.createdBy.name} size="sm" />
                            </span>
                          </Tooltip>
                        </td>
                        <td className="pr-2" onClick={(event) => event.stopPropagation()}>
                          <ShipmentRowActions shipment={shipment} onCancel={setCancelTarget} />
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>

          {meta === undefined ? null : (
            <Pagination
              page={meta.page}
              totalPages={meta.totalPages}
              total={meta.total}
              pageSize={filters.pageSize}
              noun="shipments"
              onPage={(page) => setFilters({ ...filters, page })}
              onPageSize={(pageSize) => setFilters({ ...filters, pageSize, page: 1 })}
            />
          )}
        </>
      ) : null}
      <CancelShipmentDialog
        shipment={cancelTarget}
        open={cancelTarget !== null}
        onClose={() => setCancelTarget(null)}
        onCancelled={(updated) => {
          queryClient.setQueryData<PaginatedShipments>(queryKeys.shipments(listQuery), (current) => {
            if (current === undefined) return current;
            return { ...current, data: current.data.map((row) => (row.id === updated.id ? { ...row, ...updated } : row)) };
          });
          void queryClient.invalidateQueries({ queryKey: queryKeys.shipments(listQuery) });
          setCancelTarget(null);
        }}
      />
    </div>
  );
}

function SortHeader({
  label,
  field,
  sort,
  align = 'left',
  onSort,
}: {
  label: string;
  field: 'createdAt' | 'chargedMinor';
  sort: ShipmentListFilters['sort'];
  align?: 'left' | 'right';
  onSort: (sort: ShipmentListFilters['sort']) => void;
}) {
  const active = sort.startsWith(`${field}:`);
  const descending = sort === `${field}:desc`;
  return (
    <th scope="col" aria-sort={active ? (descending ? 'descending' : 'ascending') : 'none'} className={cn('px-2.5 font-semibold', active && 'bg-surface-muted text-foreground', align === 'right' && 'text-right')}>
      <button
        type="button"
        className={cn('inline-flex items-center gap-1 rounded-sm uppercase tracking-[0.08em] transition-colors hover:text-foreground', align === 'right' && 'flex-row-reverse')}
        onClick={() => onSort(descending ? `${field}:asc` : `${field}:desc`)}
      >
        {label}
        {active ? (
          descending ? <ArrowDown className="h-3.5 w-3.5" aria-hidden="true" /> : <ArrowUp className="h-3.5 w-3.5" aria-hidden="true" />
        ) : (
          <ChevronsUpDown className="h-3.5 w-3.5 opacity-50" aria-hidden="true" />
        )}
      </button>
    </th>
  );
}
