import type { CanvasComponent } from '../../types/canvas';
import { RendererWrapper, type ComponentRenderContext } from './RendererWrapper';
import { TrendingUp, TrendingDown, Minus } from 'lucide-react';

interface Props { component: CanvasComponent; ctx: ComponentRenderContext }

export function KpiTileRenderer({ component, ctx }: Props) {
  const params = component.visualizationParameters as {
    value?: number | string;
    label?: string;
    trend?: string;
    unit?: string;
    comparisonLabel?: string;
    comparisonValue?: string;
  };

  const trendValue = params.trend ?? '';
  const isPositive = trendValue.startsWith('+') || (parseFloat(trendValue) > 0);
  const isNegative = trendValue.startsWith('-') || (parseFloat(trendValue) < 0);
  const TrendIcon = isPositive ? TrendingUp : isNegative ? TrendingDown : Minus;
  const trendColor = isPositive ? '#34d399' : isNegative ? '#f87171' : '#71717a';

  const dataRow = component.dataRows?.[0];
  const displayValue = dataRow
    ? String(Object.values(dataRow)[0] ?? params.value ?? '—')
    : String(params.value ?? '—');

  return (
    <RendererWrapper component={component} ctx={ctx} minHeight={140}>
      <div className="flex flex-col items-start justify-center h-full gap-2 py-2">
        <div className="flex items-baseline gap-2">
          <span
            className="text-4xl font-bold tracking-tight"
            style={{
              background: 'linear-gradient(135deg, #fff 0%, #94a3b8 100%)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
            }}
          >
            {displayValue}
          </span>
          {params.unit && (
            <span className="text-lg text-zinc-500 font-medium">{params.unit}</span>
          )}
        </div>

        {params.label && (
          <p className="text-sm text-zinc-400">{params.label}</p>
        )}

        {trendValue && (
          <div className="flex items-center gap-1.5 mt-1">
            <TrendIcon className="w-4 h-4" style={{ color: trendColor }} />
            <span className="text-sm font-medium" style={{ color: trendColor }}>{trendValue}</span>
            {params.comparisonLabel && (
              <span className="text-xs text-zinc-600">{params.comparisonLabel}</span>
            )}
          </div>
        )}

        {/* Ambient glow */}
        <div
          className="absolute bottom-4 right-4 w-24 h-24 rounded-full pointer-events-none"
          style={{ background: 'radial-gradient(circle, rgba(59,130,246,0.12) 0%, transparent 70%)' }}
        />
      </div>
    </RendererWrapper>
  );
}
