'use client';

import { useId, useState } from 'react';
import { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';

import { DashCard } from '@/components/dashboard/dash-card';
import { EmptyBoxIllustration } from '@/components/illustrations';
import { EmptyState, ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { formatMoney } from '@/lib/money';

interface Point {
  date: string;
  count: number;
  spendMinor?: number;
}

const shortDate = (value: string): string => {
  const date = new Date(`${value}T00:00:00`);
  return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
};

function ChartTooltip({ active, payload, currency }: { active?: boolean; payload?: ReadonlyArray<{ payload?: unknown }>; currency: string }) {
  const point = payload?.[0]?.payload as Point | undefined;
  if (active !== true || point === undefined) return null;
  return (
    <div className="rounded-lg border border-border bg-surface px-3 py-2 shadow-md">
      <p className="text-caption text-muted-foreground">{shortDate(point.date)}</p>
      <p className="mt-0.5 text-small font-bold tabular-nums text-foreground">
        {point.count} {point.count === 1 ? 'shipment' : 'shipments'}
      </p>
      {point.spendMinor === undefined ? null : <p className="text-caption tabular-nums text-muted-foreground">{formatMoney(point.spendMinor, currency)} spent</p>}
    </div>
  );
}

export function ShipmentsBarChart({
  points,
  currency = 'USD',
  rangeLabel,
  loading,
  error,
  onRetry,
}: {
  points: Point[];
  currency?: string;
  rangeLabel?: string;
  loading?: boolean;
  error?: string;
  onRetry?: () => void;
}) {
  const id = useId().replace(/:/g, '');
  const [active, setActive] = useState<number | null>(null);
  const total = points.reduce((sum, point) => sum + point.count, 0);
  const empty = points.every((point) => point.count === 0);
  const ticks = points.length > 14 ? Math.ceil(points.length / 7) - 1 : 0;

  return (
    <DashCard
      title="Shipments per day"
      caption={loading || error !== undefined ? undefined : `${total.toLocaleString()} shipments${rangeLabel === undefined ? '' : ` in the last ${rangeLabel}`}`}
      action={
        <span className="hidden items-center gap-1.5 text-caption text-muted-foreground sm:inline-flex">
          <span className="h-2.5 w-2.5 rounded-[3px] bg-brand-gradient" aria-hidden="true" />
          Shipments
        </span>
      }
    >
      {loading ? <Skeleton className="h-[280px] w-full" /> : null}
      {!loading && error !== undefined ? <ErrorState message={error} onRetry={onRetry} /> : null}
      {!loading && error === undefined && empty ? (
        <EmptyState compact illustration={<EmptyBoxIllustration size={96} />} title="No shipments in this range" description="Shipments you create will show up here day by day." />
      ) : null}
      {!loading && error === undefined && !empty ? (
        <div className="chart h-[280px]" role="img" aria-label={`Bar chart of shipments per day, ${total} in total`}>
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={points}
              margin={{ top: 8, right: 4, bottom: 0, left: -16 }}
              onMouseMove={(state) => setActive(typeof state.activeTooltipIndex === 'number' ? state.activeTooltipIndex : null)}
              onMouseLeave={() => setActive(null)}
            >
              <defs>
                <linearGradient id={`bars-${id}`} x1="0" x2="0" y1="0" y2="1">
                  <stop offset="0%" style={{ stopColor: 'rgb(var(--primary))', stopOpacity: 0.85 }} />
                  <stop offset="100%" style={{ stopColor: 'rgb(var(--accent))', stopOpacity: 0.85 }} />
                </linearGradient>
              </defs>
              <CartesianGrid vertical={false} />
              <XAxis dataKey="date" tickFormatter={shortDate} axisLine={false} tickLine={false} interval={ticks} tickMargin={8} />
              <YAxis allowDecimals={false} axisLine={false} tickLine={false} width={40} />
              <Tooltip cursor={false} content={(props) => <ChartTooltip active={props.active} payload={props.payload} currency={currency} />} />
              <Bar dataKey="count" radius={[6, 6, 6, 6]} fill={`url(#bars-${id})`} maxBarSize={36} animationDuration={600}>
                {points.map((point, index) => (
                  <Cell key={point.date} fillOpacity={active === null || active === index ? 1 : 0.35} style={{ transition: 'fill-opacity 180ms' }} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </div>
      ) : null}
    </DashCard>
  );
}
