'use client';

import { useQuery } from '@tanstack/react-query';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { CircleDollarSign, Package, PackageCheck, Plus, Truck } from 'lucide-react';
import Link from 'next/link';
import { useState, useSyncExternalStore } from 'react';

import { Can } from '@/components/can';
import { AttentionList } from '@/components/dashboard/attention-list';
import { KpiCard } from '@/components/dashboard/kpi-card';
import { OnboardingChecklist } from '@/components/dashboard/onboarding-checklist';
import { RecentShipments } from '@/components/dashboard/recent-shipments';
import { ShipmentsBarChart } from '@/components/dashboard/shipments-bar-chart';
import { SpendByCourierChart } from '@/components/dashboard/spend-by-courier-chart';
import { WalletCard } from '@/components/dashboard/wallet-card';
import { PageHeader } from '@/components/layout/page-header';
import { Reveal } from '@/components/motion/reveal';
import { buttonVariants } from '@/components/ui/button';
import { Segmented } from '@/components/ui/segmented';
import { ErrorState } from '@/components/ui/states';
import { ApiError, api } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { dashboardSummarySchema, recentShipment } from '@/lib/dashboard';
import { greeting } from '@/lib/format';
import { deliveryRate, formatMoney } from '@/lib/money';
import { queryKeys } from '@/lib/query-keys';

type Range = 7 | 30 | 90;

const subscribe = () => () => undefined;
const getHour = () => new Date().getHours();
const getToday = () => new Date().toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric' });

export default function DashboardPage() {
  const { user } = useAuth();
  const reduce = useReducedMotion();
  const [range, setRange] = useState<Range>(30);
  const summary = useQuery({
    queryKey: queryKeys.dashboard(range),
    queryFn: async () => dashboardSummarySchema.parse(await api(`/dashboard/summary?range=${range}`)),
  });
  // Local hour and date are read on the client only to avoid server/client mismatches.
  const hour = useSyncExternalStore(subscribe, getHour, () => 9);
  const today = useSyncExternalStore(subscribe, getToday, () => '');
  const firstName = user?.name.split(' ')[0] ?? 'there';
  const error = summary.error instanceof ApiError ? summary.error.message : summary.error instanceof Error ? summary.error.message : undefined;
  const forbidden = summary.error instanceof ApiError && summary.error.status === 403;
  const data = summary.data;
  const onboardingDone = data !== undefined && Object.values(data.onboarding).every(Boolean);
  const rate = data === undefined ? null : deliveryRate(data.kpis.deliveredCount, data.kpis.finalStateCount);
  const recent = (data?.recent ?? []).flatMap((row) => {
    const shipment = recentShipment(row);
    return shipment === null ? [] : [shipment];
  });
  const currency = data?.kpis.currency ?? 'USD';
  const retry = () => void summary.refetch();
  if (forbidden) return <ErrorState message="You do not have permission to view the dashboard." />;

  const showKpis = summary.isLoading || onboardingDone || data === undefined;

  return (
    <div>
      <PageHeader
        title={`${greeting(hour)}, ${firstName}`}
        description="Here is what is happening with your shipments."
        actions={
          <>
            <Segmented<`${Range}`>
              label="Date range"
              value={`${range}`}
              onChange={(value) => setRange(Number(value) as Range)}
              options={[
                { value: '7', label: '7 days' },
                { value: '30', label: '30 days' },
                { value: '90', label: '90 days' },
              ]}
              className="h-10 items-center"
            />
            <Can permission="shipments:create">
              <Link href="/shipments/new" className={buttonVariants()}>
                <Plus className="h-4 w-4" aria-hidden="true" />
                New shipment
              </Link>
            </Can>
          </>
        }
      />
      {today === '' ? null : <p className="-mt-4 mb-6 text-[13px] text-subtle-foreground">{today}</p>}

      <AnimatePresence initial={false}>
        {data !== undefined && !onboardingDone ? (
          <motion.div
            key="onboarding"
            initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
            animate={reduce ? { opacity: 1 } : { opacity: 1, height: 'auto' }}
            exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
            transition={{ duration: 0.28, ease: [0.2, 0.8, 0.2, 1] }}
            className="overflow-hidden"
          >
            <div className="pb-6">
              <OnboardingChecklist progress={data.onboarding} />
            </div>
          </motion.div>
        ) : null}
      </AnimatePresence>

      {showKpis ? (
        <div className="mb-6 grid gap-6 sm:grid-cols-2 xl:grid-cols-4">
          <Reveal index={0}>
            <KpiCard
              label="Shipments"
              icon={Package}
              tone="primary"
              loading={summary.isLoading}
              error={error}
              onRetry={retry}
              numeric={data?.kpis.shipmentsCount}
              value="—"
              current={data?.kpis.shipmentsCount}
              previous={data?.kpis.shipmentsPrevCount ?? null}
              spark={data?.series.map((point) => point.count)}
            />
          </Reveal>
          <Reveal index={1}>
            <KpiCard
              label="In transit"
              icon={Truck}
              tone="warning"
              loading={summary.isLoading}
              error={error}
              onRetry={retry}
              numeric={data?.kpis.inTransitCount}
              value="—"
              current={data?.kpis.inTransitCount}
              previous={null}
            />
          </Reveal>
          <Reveal index={2}>
            <KpiCard
              label="Delivery rate"
              icon={PackageCheck}
              tone="success"
              loading={summary.isLoading}
              error={error}
              onRetry={retry}
              numeric={rate ?? undefined}
              value="—"
              format={(value) => `${Math.round(value)}%`}
              current={rate ?? undefined}
              previous={null}
            />
          </Reveal>
          <Reveal index={3}>
            <KpiCard
              label="Spend"
              icon={CircleDollarSign}
              tone="info"
              loading={summary.isLoading}
              error={error}
              onRetry={retry}
              numeric={data?.kpis.spendMinor}
              value="—"
              format={(value) => formatMoney(Math.round(value), currency)}
              current={data?.kpis.spendMinor}
              previous={data?.kpis.spendPrevMinor ?? null}
              spark={data?.series.map((point) => point.spendMinor)}
            />
          </Reveal>
        </div>
      ) : null}

      <div className="grid gap-6 lg:grid-cols-3">
        <Reveal index={0} className="lg:col-span-2">
          <ShipmentsBarChart points={data?.series ?? []} currency={currency} rangeLabel={`${range} days`} loading={summary.isLoading} error={error} onRetry={retry} />
        </Reveal>
        <Reveal index={1}>
          <WalletCard currency={data?.kpis.currency} />
        </Reveal>
      </div>

      <div className="mt-6 grid gap-6 lg:grid-cols-2">
        <Reveal index={0}>
          <SpendByCourierChart rows={data?.byCourier ?? []} currency={currency} loading={summary.isLoading} error={error} onRetry={retry} />
        </Reveal>
        <Reveal index={1}>
          <AttentionList items={data?.attention ?? []} loading={summary.isLoading} error={error} onRetry={retry} />
        </Reveal>
      </div>

      <Reveal className="mt-6">
        <RecentShipments rows={recent} currency={currency} loading={summary.isLoading} error={error} onRetry={retry} />
      </Reveal>
    </div>
  );
}
