'use client';

import { motion, useReducedMotion } from 'framer-motion';

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';
import { cn } from '@/lib/utils';

// One token color per row, in order of spend.
const barColors = ['bg-brand-gradient', 'bg-info', 'bg-success', 'bg-warning', 'bg-accent', 'bg-danger', 'bg-subtle-foreground'] as const;

export function SpendByCourierChart({
  rows,
  currency,
  loading,
  error,
  onRetry,
}: {
  rows: Array<{ courierName: string; spendMinor: number }>;
  currency: string;
  loading?: boolean;
  error?: string;
  onRetry?: () => void;
}) {
  const reduce = useReducedMotion();
  const sorted = [...rows].sort((left, right) => right.spendMinor - left.spendMinor);
  const top = sorted.slice(0, 6);
  const otherMinor = sorted.slice(6).reduce((sum, row) => sum + row.spendMinor, 0);
  const display = otherMinor > 0 ? [...top, { courierName: 'Other', spendMinor: otherMinor }] : top;
  const total = display.reduce((sum, row) => sum + row.spendMinor, 0);
  const max = Math.max(1, ...display.map((row) => row.spendMinor));

  return (
    <DashCard title="Spend by courier" caption={loading || error !== undefined || total === 0 ? undefined : `${formatMoney(total, currency)} total`}>
      {loading ? (
        <div className="grid gap-5">
          {[0, 1, 2, 3].map((index) => (
            <div key={index} className="grid gap-2">
              <Skeleton className="h-4 w-1/3" />
              <Skeleton className="h-2 w-full rounded-pill" />
            </div>
          ))}
        </div>
      ) : null}
      {!loading && error !== undefined ? <ErrorState message={error} onRetry={onRetry} /> : null}
      {!loading && error === undefined && display.length === 0 ? (
        <EmptyState compact illustration={<EmptyBoxIllustration size={80} />} title="No courier spend yet" description="Spend appears here once you buy labels in this range." />
      ) : null}
      {!loading && error === undefined && display.length > 0 ? (
        <ul className="grid gap-4">
          {display.map((row, index) => {
            const share = total === 0 ? 0 : Math.round((row.spendMinor / total) * 100);
            return (
              <li key={row.courierName}>
                <div className="flex items-baseline justify-between gap-3 text-small">
                  <span className="min-w-0 truncate font-medium text-foreground">{row.courierName}</span>
                  <span className="shrink-0 tabular-nums">
                    <span className="font-semibold text-foreground">{formatMoney(row.spendMinor, currency)}</span>
                    <span className="ml-2 inline-block w-9 text-right text-caption text-muted-foreground">{share}%</span>
                  </span>
                </div>
                <div className="mt-1.5 h-2 overflow-hidden rounded-[8px] bg-surface-muted" aria-hidden="true">
                  <motion.div
                    className={cn('h-full rounded-[8px]', barColors[index] ?? barColors[barColors.length - 1])}
                    initial={{ width: reduce ? `${(row.spendMinor / max) * 100}%` : 0 }}
                    whileInView={{ width: `${(row.spendMinor / max) * 100}%` }}
                    viewport={{ once: true }}
                    transition={{ duration: reduce ? 0 : 0.7, delay: reduce ? 0 : index * 0.06, ease: [0.2, 0.8, 0.2, 1] }}
                  />
                </div>
              </li>
            );
          })}
        </ul>
      ) : null}
    </DashCard>
  );
}
