/**
 * Allocation Chart Component
 * Displays portfolio allocations as a donut chart
 */

import React from 'react';
import type { PortfolioAllocation } from '../../../services/portfolio.service';

interface AllocationChartProps {
  allocations: PortfolioAllocation[];
  size?: number;
}

// Asset colors mapping
const ASSET_COLORS: Record<string, string> = {
  BTC: '#F7931A',
  ETH: '#627EEA',
  USDT: '#26A17B',
  SOL: '#9945FF',
  LINK: '#2A5ADA',
  AVAX: '#E84142',
  ADA: '#0033AD',
  DOT: '#E6007A',
  MATIC: '#8247E5',
  default: '#6B7280',
};

function getAssetColor(asset: string): string {
  return ASSET_COLORS[asset] || ASSET_COLORS.default;
}

export const AllocationChart: React.FC<AllocationChartProps> = ({
  allocations,
  size = 200,
}) => {
  const radius = size / 2;
  const innerRadius = radius * 0.6;
  const centerX = radius;
  const centerY = radius;

  // Calculate segments
  let currentAngle = -90; // Start from top
  const segments = allocations.map((alloc) => {
    const angle = (alloc.currentPercent / 100) * 360;
    const startAngle = currentAngle;
    const endAngle = currentAngle + angle;
    currentAngle = endAngle;

    // Convert to radians
    const startRad = (startAngle * Math.PI) / 180;
    const endRad = (endAngle * Math.PI) / 180;

    // Calculate arc path
    const x1 = centerX + radius * Math.cos(startRad);
    const y1 = centerY + radius * Math.sin(startRad);
    const x2 = centerX + radius * Math.cos(endRad);
    const y2 = centerY + radius * Math.sin(endRad);

    const x1Inner = centerX + innerRadius * Math.cos(startRad);
    const y1Inner = centerY + innerRadius * Math.sin(startRad);
    const x2Inner = centerX + innerRadius * Math.cos(endRad);
    const y2Inner = centerY + innerRadius * Math.sin(endRad);

    const largeArc = angle > 180 ? 1 : 0;

    const pathData = [
      `M ${x1Inner} ${y1Inner}`,
      `L ${x1} ${y1}`,
      `A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}`,
      `L ${x2Inner} ${y2Inner}`,
      `A ${innerRadius} ${innerRadius} 0 ${largeArc} 0 ${x1Inner} ${y1Inner}`,
      'Z',
    ].join(' ');

    return {
      ...alloc,
      pathData,
      color: getAssetColor(alloc.asset),
    };
  });

  const totalValue = allocations.reduce((sum, a) => sum + a.value, 0);

  return (
    <div className="flex flex-col items-center">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        {segments.map((segment, index) => (
          <path
            key={index}
            d={segment.pathData}
            fill={segment.color}
            className="transition-opacity hover:opacity-80 cursor-pointer"
          >
            <title>
              {segment.asset}: {segment.currentPercent.toFixed(1)}% ($
              {segment.value.toLocaleString()})
            </title>
          </path>
        ))}
        {/* Center text */}
        <text
          x={centerX}
          y={centerY - 10}
          textAnchor="middle"
          className="fill-gray-500 dark:fill-gray-400 text-xs"
        >
          Valor Total
        </text>
        <text
          x={centerX}
          y={centerY + 15}
          textAnchor="middle"
          className="fill-gray-900 dark:fill-white text-lg font-bold"
        >
          ${totalValue.toLocaleString(undefined, { maximumFractionDigits: 0 })}
        </text>
      </svg>

      {/* Legend */}
      <div className="flex flex-wrap justify-center gap-3 mt-4">
        {allocations.map((alloc) => (
          <div key={alloc.asset} className="flex items-center gap-2">
            <div
              className="w-3 h-3 rounded-full"
              style={{ backgroundColor: getAssetColor(alloc.asset) }}
            />
            <span className="text-sm text-gray-600 dark:text-gray-400">
              {alloc.asset} ({alloc.currentPercent.toFixed(1)}%)
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default AllocationChart;
