/**
 * PerformanceWidgetChart Component
 * Compact sparkline-style performance chart for embedding in cards
 * OQI-004: Cuentas de Inversion
 */

import React, { useRef, useEffect, useMemo } from 'react';
import { TrendingUp, TrendingDown, Minus } from 'lucide-react';

// ============================================================================
// Types
// ============================================================================

export interface PerformanceDataPoint {
  date: string;
  value: number;
  balance?: number;
}

interface PerformanceWidgetChartProps {
  data: PerformanceDataPoint[];
  period?: 'week' | 'month' | 'quarter' | 'year' | 'all';
  height?: number;
  showTrend?: boolean;
  showValue?: boolean;
  lineColor?: string;
  fillColor?: string;
  compact?: boolean;
  onClick?: () => void;
}

// ============================================================================
// Helper Functions
// ============================================================================

const calculateTrend = (data: PerformanceDataPoint[]) => {
  if (data.length < 2) return { direction: 'neutral' as const, change: 0, changePercent: 0 };

  const first = data[0].value;
  const last = data[data.length - 1].value;
  const change = last - first;
  const changePercent = first !== 0 ? (change / Math.abs(first)) * 100 : 0;

  return {
    direction: change > 0 ? 'up' as const : change < 0 ? 'down' as const : 'neutral' as const,
    change,
    changePercent,
  };
};

const formatValue = (value: number) => {
  if (Math.abs(value) >= 1000000) {
    return `$${(value / 1000000).toFixed(1)}M`;
  }
  if (Math.abs(value) >= 1000) {
    return `$${(value / 1000).toFixed(1)}K`;
  }
  return `$${value.toFixed(0)}`;
};

// ============================================================================
// Component
// ============================================================================

export const PerformanceWidgetChart: React.FC<PerformanceWidgetChartProps> = ({
  data,
  period = 'month',
  height = 60,
  showTrend = true,
  showValue = true,
  lineColor,
  fillColor,
  compact = false,
  onClick,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const trend = useMemo(() => calculateTrend(data), [data]);

  const defaultLineColor = trend.direction === 'up' ? '#10b981' : trend.direction === 'down' ? '#ef4444' : '#6b7280';
  const defaultFillColor = trend.direction === 'up' ? 'rgba(16, 185, 129, 0.1)' : trend.direction === 'down' ? 'rgba(239, 68, 68, 0.1)' : 'rgba(107, 114, 128, 0.1)';

  const actualLineColor = lineColor || defaultLineColor;
  const actualFillColor = fillColor || defaultFillColor;

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || data.length < 2) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();

    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    ctx.scale(dpr, dpr);

    const width = rect.width;
    const chartHeight = rect.height;
    const padding = 2;

    // Calculate min/max with some padding
    const values = data.map((d) => d.value);
    const minValue = Math.min(...values);
    const maxValue = Math.max(...values);
    const valueRange = maxValue - minValue || 1;
    const paddedMin = minValue - valueRange * 0.1;
    const paddedMax = maxValue + valueRange * 0.1;
    const paddedRange = paddedMax - paddedMin;

    // Map data points to canvas coordinates
    const points = data.map((d, i) => ({
      x: padding + (i / (data.length - 1)) * (width - 2 * padding),
      y: chartHeight - padding - ((d.value - paddedMin) / paddedRange) * (chartHeight - 2 * padding),
    }));

    // Clear canvas
    ctx.clearRect(0, 0, width, chartHeight);

    // Draw fill area
    ctx.beginPath();
    ctx.moveTo(points[0].x, chartHeight);
    points.forEach((p) => ctx.lineTo(p.x, p.y));
    ctx.lineTo(points[points.length - 1].x, chartHeight);
    ctx.closePath();
    ctx.fillStyle = actualFillColor;
    ctx.fill();

    // Draw line
    ctx.beginPath();
    ctx.moveTo(points[0].x, points[0].y);

    // Smooth curve using quadratic bezier
    for (let i = 1; i < points.length; i++) {
      const prev = points[i - 1];
      const curr = points[i];
      const midX = (prev.x + curr.x) / 2;
      ctx.quadraticCurveTo(prev.x, prev.y, midX, (prev.y + curr.y) / 2);
    }
    ctx.lineTo(points[points.length - 1].x, points[points.length - 1].y);

    ctx.strokeStyle = actualLineColor;
    ctx.lineWidth = 2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    ctx.stroke();

    // Draw end point dot
    const lastPoint = points[points.length - 1];
    ctx.beginPath();
    ctx.arc(lastPoint.x, lastPoint.y, 3, 0, Math.PI * 2);
    ctx.fillStyle = actualLineColor;
    ctx.fill();
    ctx.strokeStyle = '#1e293b';
    ctx.lineWidth = 1.5;
    ctx.stroke();
  }, [data, actualLineColor, actualFillColor]);

  const TrendIcon = trend.direction === 'up' ? TrendingUp : trend.direction === 'down' ? TrendingDown : Minus;

  if (compact) {
    return (
      <div
        onClick={onClick}
        className={`flex items-center gap-2 ${onClick ? 'cursor-pointer' : ''}`}
      >
        <canvas
          ref={canvasRef}
          className="flex-1"
          style={{ height: height / 2, width: '100%' }}
        />
        {showTrend && (
          <span
            className={`text-xs font-medium ${
              trend.direction === 'up'
                ? 'text-emerald-400'
                : trend.direction === 'down'
                ? 'text-red-400'
                : 'text-slate-400'
            }`}
          >
            {trend.changePercent > 0 ? '+' : ''}{trend.changePercent.toFixed(1)}%
          </span>
        )}
      </div>
    );
  }

  return (
    <div
      onClick={onClick}
      className={`bg-slate-800/50 rounded-lg border border-slate-700 p-3 ${onClick ? 'cursor-pointer hover:border-slate-600 transition-colors' : ''}`}
    >
      {/* Header */}
      {(showValue || showTrend) && (
        <div className="flex items-center justify-between mb-2">
          {showValue && data.length > 0 && (
            <div className="text-lg font-bold text-white">
              {formatValue(data[data.length - 1].value)}
            </div>
          )}
          {showTrend && (
            <div
              className={`flex items-center gap-1 text-sm ${
                trend.direction === 'up'
                  ? 'text-emerald-400'
                  : trend.direction === 'down'
                  ? 'text-red-400'
                  : 'text-slate-400'
              }`}
            >
              <TrendIcon className="w-4 h-4" />
              <span>
                {trend.changePercent > 0 ? '+' : ''}{trend.changePercent.toFixed(1)}%
              </span>
            </div>
          )}
        </div>
      )}

      {/* Chart */}
      <canvas
        ref={canvasRef}
        className="w-full"
        style={{ height }}
      />

      {/* Period Label */}
      <div className="mt-2 text-xs text-slate-500 text-center capitalize">
        {period === 'all' ? 'All Time' : `Last ${period}`}
      </div>
    </div>
  );
};

export default PerformanceWidgetChart;
