'use client';

import { animate, useReducedMotion } from 'framer-motion';
import type { LucideIcon } from 'lucide-react';
import { useEffect, useId, useRef, useState, type ReactNode } from 'react';
import { Area, AreaChart, ResponsiveContainer } from 'recharts';

import { TrendDelta } from '@/components/dashboard/trend-delta';
import { Card } from '@/components/ui/card';
import { ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';

const tones = {
  primary: { chip: 'bg-primary-soft text-primary', line: 'text-primary' },
  warning: { chip: 'bg-warning-soft text-warning', line: 'text-warning' },
  success: { chip: 'bg-success-soft text-success', line: 'text-success' },
  info: { chip: 'bg-info-soft text-info', line: 'text-info' },
} as const;

/** Counts up from the previous value whenever `value` changes. */
function CountUp({ value, format }: { value: number; format: (value: number) => string }) {
  const reduce = useReducedMotion();
  const [display, setDisplay] = useState(value);
  const previous = useRef(value);
  useEffect(() => {
    const from = previous.current;
    previous.current = value;
    if (from === value) return undefined;
    const controls = animate(from, value, {
      duration: reduce ? 0 : 0.6,
      ease: [0.2, 0.8, 0.2, 1],
      onUpdate: (latest) => setDisplay(latest),
    });
    return () => controls.stop();
  }, [reduce, value]);
  return <>{format(display)}</>;
}

function Sparkline({ data, tone }: { data: number[]; tone: keyof typeof tones }) {
  const id = useId().replace(/:/g, '');
  const points = data.map((value, index) => ({ index, value }));
  return (
    <div className={cn('h-14 w-24 shrink-0', tones[tone].line)} aria-hidden="true">
      <ResponsiveContainer width="100%" height="100%">
        <AreaChart data={points} margin={{ top: 4, right: 0, bottom: 0, left: 0 }}>
          <defs>
            <linearGradient id={`spark-${id}`} x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="currentColor" stopOpacity={0.3} />
              <stop offset="100%" stopColor="currentColor" stopOpacity={0} />
            </linearGradient>
          </defs>
          <Area
            type="monotone"
            dataKey="value"
            stroke="currentColor"
            strokeWidth={2}
            fill={`url(#spark-${id})`}
            isAnimationActive={false}
            dot={false}
            activeDot={false}
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}

export function KpiCard({
  label,
  icon: Icon,
  tone,
  value,
  numeric,
  format = (number) => Math.round(number).toLocaleString(),
  current,
  previous,
  spark,
  loading,
  error,
  onRetry,
}: {
  label: string;
  icon: LucideIcon;
  tone: keyof typeof tones;
  /** Static value when no numeric count-up applies (e.g. em dash). */
  value?: ReactNode;
  /** Numeric value to count up to; rendered with `format`. */
  numeric?: number;
  format?: (value: number) => string;
  current?: number;
  previous?: number | null;
  spark?: number[];
  loading?: boolean;
  error?: string;
  onRetry?: () => void;
}) {
  if (loading) {
    return (
      <Card className="p-5">
        <div className="flex items-center gap-3">
          <Skeleton className="h-9 w-9 rounded-lg" />
          <Skeleton className="h-4 w-24" />
        </div>
        <Skeleton className="mt-4 h-9 w-28" />
        <Skeleton className="mt-3 h-5 w-32 rounded-pill" />
      </Card>
    );
  }
  if (error !== undefined) {
    return (
      <Card className="p-5">
        <ErrorState title={`${label} unavailable`} message={error} onRetry={onRetry} />
      </Card>
    );
  }
  const hasSpark = spark !== undefined && spark.length > 1 && spark.some((point) => point > 0);
  return (
    <Card variant="interactive" className="p-5">
      <div className="flex items-center gap-3">
        <span className={cn('grid h-9 w-9 place-items-center rounded-lg', tones[tone].chip)}>
          <Icon className="h-[18px] w-[18px]" aria-hidden="true" />
        </span>
        <p className="text-[13px] font-medium text-muted-foreground">{label}</p>
      </div>
      <div className="mt-3 flex items-end justify-between gap-3">
        <p className="min-w-0 truncate font-display text-[32px] font-extrabold leading-10 tracking-[-0.02em] tabular-nums text-foreground">
          {numeric === undefined ? value : <CountUp value={numeric} format={format} />}
        </p>
        {hasSpark ? <Sparkline data={spark} tone={tone} /> : null}
      </div>
      <div className="mt-2 flex items-center gap-2">
        {current === undefined ? null : <TrendDelta current={current} previous={previous ?? null} />}
        <span className="text-caption text-subtle-foreground">{previous === null || previous === undefined ? 'no comparison' : 'vs previous period'}</span>
      </div>
    </Card>
  );
}
