'use client';

import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';

interface StatData {
  value: number;
  change: number;
  sparkline: number[];
}

interface OverviewData {
  totalConversations: StatData;
  bookingRate: StatData;
  avgResponseTime: StatData;
  customerSatisfaction: StatData;
}

interface CardConfig {
  key: keyof OverviewData;
  label: string;
  format: (v: number) => string;
  suffix?: string;
  gradient: string;
  sparkColor: string;
  sparkFill: string;
}

const cards: CardConfig[] = [
  {
    key: 'totalConversations',
    label: 'Total Conversations',
    format: (v) => v.toLocaleString(),
    gradient: 'from-pink-500/20 via-rose-500/10 to-red-500/5',
    sparkColor: '#f43f5e',
    sparkFill: 'rgba(244,63,94,0.15)',
  },
  {
    key: 'bookingRate',
    label: 'Booking Rate',
    format: (v) => `${v}%`,
    gradient: 'from-emerald-500/20 via-green-500/10 to-teal-500/5',
    sparkColor: '#22c55e',
    sparkFill: 'rgba(34,197,94,0.15)',
  },
  {
    key: 'avgResponseTime',
    label: 'Avg Response Time',
    format: (v) => `${v}s`,
    gradient: 'from-blue-500/20 via-sky-500/10 to-cyan-500/5',
    sparkColor: '#3b82f6',
    sparkFill: 'rgba(59,130,246,0.15)',
  },
  {
    key: 'customerSatisfaction',
    label: 'Customer Satisfaction',
    format: (v) => `${v}/5`,
    gradient: 'from-purple-500/20 via-violet-500/10 to-indigo-500/5',
    sparkColor: '#a855f7',
    sparkFill: 'rgba(168,85,247,0.15)',
  },
];

function Sparkline({
  data,
  color,
  fill,
  width = 120,
  height = 40,
}: {
  data: number[];
  color: string;
  fill: string;
  width?: number;
  height?: number;
}) {
  if (!data || data.length === 0) return null;

  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = max - min || 1;
  const padding = 2;

  const points = data.map((v, i) => {
    const x = padding + (i / (data.length - 1)) * (width - padding * 2);
    const y = height - padding - ((v - min) / range) * (height - padding * 2);
    return `${x},${y}`;
  });

  const polylinePoints = points.join(' ');
  // Build area fill path
  const firstX = padding;
  const lastX = padding + ((data.length - 1) / (data.length - 1)) * (width - padding * 2);
  const areaPath = `M ${firstX},${height} L ${points.map((p) => p).join(' L ')} L ${lastX},${height} Z`;

  return (
    <svg width={width} height={height} className="overflow-visible">
      <defs>
        <linearGradient id={`grad-${color.replace('#', '')}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={fill} />
          <stop offset="100%" stopColor="transparent" />
        </linearGradient>
      </defs>
      <path d={areaPath} fill={`url(#grad-${color.replace('#', '')})`} />
      <polyline
        points={polylinePoints}
        fill="none"
        stroke={color}
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      {/* Dot on last point */}
      {data.length > 0 && (
        <circle
          cx={padding + ((data.length - 1) / (data.length - 1)) * (width - padding * 2)}
          cy={height - padding - ((data[data.length - 1] - min) / range) * (height - padding * 2)}
          r="3"
          fill={color}
        />
      )}
    </svg>
  );
}

function ChangeIndicator({ change }: { change: number }) {
  const isPositive = change >= 0;
  return (
    <div
      className={cn(
        'flex items-center gap-1 text-xs font-semibold rounded-full px-2 py-0.5',
        isPositive ? 'text-emerald-400 bg-emerald-500/10' : 'text-rose-400 bg-rose-500/10'
      )}
    >
      <svg width="10" height="10" viewBox="0 0 10 10" className={cn(!isPositive && 'rotate-180')}>
        <path d="M5 1L9 6H1L5 1Z" fill="currentColor" />
      </svg>
      {Math.abs(change).toFixed(1)}%
    </div>
  );
}

export default function StatCardSparkline() {
  const [data, setData] = useState<OverviewData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/analytics/overview')
      .then((r) => r.json())
      .then((d) => setData(d))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
      {cards.map((card) => {
        const stat = data?.[card.key];

        return (
          <div
            key={card.key}
            className={cn(
              'relative overflow-hidden rounded-xl border border-slate-700/40 bg-gradient-to-br p-5 transition-all duration-300 hover:scale-[1.02] hover:border-slate-600/60',
              card.gradient
            )}
            style={{ backdropFilter: 'blur(12px)' }}
          >
            {/* Background shimmer */}
            <div className="absolute inset-0 bg-[#0f1729]/60 pointer-events-none" />

            <div className="relative z-10">
              {/* Header row: label + change */}
              <div className="flex items-center justify-between mb-3">
                <p className="text-xs font-medium uppercase tracking-wider text-slate-400">
                  {card.label}
                </p>
                {stat && <ChangeIndicator change={stat.change} />}
              </div>

              {/* Value + sparkline row */}
              <div className="flex items-end justify-between">
                <div>
                  {loading || !stat ? (
                    <div className="h-10 w-24 animate-pulse rounded bg-slate-700/40" />
                  ) : (
                    <p className="text-3xl font-bold text-white tracking-tight">
                      {card.format(stat.value)}
                    </p>
                  )}
                  <p className="text-[11px] text-slate-500 mt-1">vs last period</p>
                </div>

                {stat && (
                  <Sparkline
                    data={stat.sparkline}
                    color={card.sparkColor}
                    fill={card.sparkFill}
                    width={100}
                    height={36}
                  />
                )}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}
