"use client";

import React, { useState, useMemo, useEffect } from "react";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  Legend,
  Sector,
} from "recharts";
import { CURRENCY_SYMBOLS, formatMoneyAbbreviated, PRIMARY_COLOR } from "@/lib/common";

interface PieChartData {
  name: string;
  value: number;
  color?: string;
  percentage?: number;
  [key: string]: any;
}

interface StandardizedPieChartProps {
  data: PieChartData[];
  height?: number;
  innerRadius?: number;
  outerRadius?: number;
  showLegend?: boolean;
  legendFormatter?: (value: string, entry: any) => React.ReactNode;
  tooltipFormatter?: (value: any, name: string) => React.ReactNode;
  dataKey?: string;
  nameKey?: string;
  paddingAngle?: number;
  colors?: string[];
  onSegmentClick?: (data: PieChartData, index: number) => void;
  customTooltip?: React.ComponentType<any>;
  minAngle?: number; // Minimum angle in degrees for small segments
  showLabels?: boolean; // Show percentage labels on segments
  labelThreshold?: number; // Minimum percentage to show label (default 3%)
  currency?: string; // Currency code for formatting values (e.g., "USD", "EUR")
}

// Standard sizes for consistency across the project
const STANDARD_HEIGHT = 400;
const STANDARD_INNER_RADIUS = 80;
const STANDARD_OUTER_RADIUS = 140;
const STANDARD_PADDING_ANGLE = 0; // No padding for cleaner look

// Default color palette - includes PRIMARY_COLOR for consistency
const DEFAULT_COLORS = [
  "#4A90E2", "#7B68EE", "#00CED1", "#FF6B6B", "#9B59B6",
  "#FFA500", "#E91E63", "#8B4513", "#FF4500", "#A9A9A9",
  "#20B2AA", "#2E8B57", PRIMARY_COLOR
];

// Format currency value using common utilities
const formatCurrency = (amount: number, currencyCode?: string): string => {
  if (!currencyCode) {
    return amount.toLocaleString("en-US", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    });
  }
  return formatMoneyAbbreviated(amount, currencyCode);
};

export const StandardizedPieChart: React.FC<StandardizedPieChartProps> = ({
  data,
  height = STANDARD_HEIGHT,
  innerRadius = STANDARD_INNER_RADIUS,
  outerRadius = STANDARD_OUTER_RADIUS,
  showLegend = false,
  legendFormatter,
  tooltipFormatter,
  dataKey = "value",
  nameKey = "name",
  paddingAngle = STANDARD_PADDING_ANGLE,
  colors = DEFAULT_COLORS,
  onSegmentClick,
  customTooltip,
  minAngle = 2, // Minimum 2 degrees for visibility
  showLabels = false,
  labelThreshold = 3, // Show label if percentage >= 3%
  currency,
}) => {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);

  // Remove focus outline from SVG elements
  useEffect(() => {
    const styleId = 'pie-chart-no-outline';
    if (!document.getElementById(styleId)) {
      const style = document.createElement('style');
      style.id = styleId;
      style.textContent = `
        .pie-chart-container svg:focus,
        .pie-chart-container svg:focus-visible,
        .pie-chart-container svg *:focus,
        .pie-chart-container svg *:focus-visible {
          outline: none !important;
        }
      `;
      document.head.appendChild(style);
    }
  }, []);

  // Process data to calculate percentages and prepare for display
  const processedData = useMemo(() => {
    if (!data || data.length === 0) return [];
    
    const total = data.reduce((sum, entry) => sum + Math.abs(entry.value || 0), 0);
    if (total === 0) return [];

    // Calculate percentages for all entries
    const processed = data.map((entry) => {
      const value = Math.abs(entry.value || 0);
      const percentage = total > 0 ? (value / total) * 100 : 0;
      
      return {
        ...entry,
        value,
        percentage: parseFloat(percentage.toFixed(2)),
        displayValue: value,
      };
    });

    return processed;
  }, [data]);

  const handleClick = (data: any, index: number) => {
    setActiveIndex(activeIndex === index ? null : index);
    if (onSegmentClick) {
      onSegmentClick(data, index);
    }
  };

  const handleMouseEnter = (_: any, index: number) => {
    setHoveredIndex(index);
  };

  const handleMouseLeave = () => {
    setHoveredIndex(null);
  };

  // Get color - don't dim segments when one is active
  const getColor = (entry: PieChartData, index: number) => {
    const baseColor = entry.color || colors[index % colors.length];
    if (hoveredIndex !== null && hoveredIndex !== index) {
      // Slightly dim on hover
      return `${baseColor}CC`; // 80% opacity
    }
    return baseColor;
  };

  // Calculate offset for exploded segment
  const getExplodedOffset = (startAngle: number, endAngle: number, cx: number, cy: number) => {
    const midAngle = (startAngle + endAngle) / 2;
    const RADIAN = Math.PI / 180;
    const explodeDistance = 15; // Distance to move the segment away
    const offsetX = explodeDistance * Math.cos(-midAngle * RADIAN);
    const offsetY = explodeDistance * Math.sin(-midAngle * RADIAN);
    return { offsetX, offsetY };
  };

  // Custom label renderer for segments
  const renderCustomLabel = (entry: any) => {
    if (!showLabels) return null;
    const percentage = entry.percentage || 0;
    if (percentage < labelThreshold) return null;
    
    // Calculate position for label (midpoint of arc)
    const midAngle = (entry.startAngle + entry.endAngle) / 2;
    const RADIAN = Math.PI / 180;
    const cx = entry.cx;
    const cy = entry.cy;
    const radius = (entry.innerRadius + entry.outerRadius) / 2;
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);
    
    return (
      <text
        x={x}
        y={y}
        fill="#fff"
        textAnchor="middle"
        dominantBaseline="central"
        fontSize="11"
        fontWeight="700"
        style={{
          textShadow: "0 1px 3px rgba(0,0,0,0.7), 0 0 8px rgba(0,0,0,0.3)",
          pointerEvents: "none",
        }}
      >
        {percentage.toFixed(1)}%
      </text>
    );
  };

  if (!data || data.length === 0 || processedData.length === 0) {
    return (
      <div 
        className="flex items-center justify-center text-sm text-slate-400"
        style={{ height: `${height}px`, width: '100%' }}
      >
        No data available
      </div>
    );
  }

  return (
    <div 
      className="pie-chart-container [&_svg]:outline-none [&_svg]:focus:outline-none [&_svg]:focus-visible:outline-none [&_svg_*]:outline-none [&_svg_*]:focus:outline-none [&_svg_*]:focus-visible:outline-none" 
      style={{ outline: 'none' }}
    >
      <ResponsiveContainer 
        width="100%" 
        height={height}
        className="outline-none focus:outline-none"
        style={{ outline: 'none' }}
      >
        <PieChart 
          margin={{ top: 20, right: 30, bottom: 20, left: 30 }}
          style={{ outline: 'none' }}
        >
        <defs>
          {processedData.map((entry, index) => {
            const baseColor = entry.color || colors[index % colors.length];
            return (
              <linearGradient key={`gradient-${index}`} id={`gradient-${index}`} x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor={baseColor} stopOpacity={1} />
                <stop offset="100%" stopColor={baseColor} stopOpacity={0.85} />
              </linearGradient>
            );
          })}
        </defs>
        <Pie
          data={processedData}
          cx="50%"
          cy="50%"
          innerRadius={innerRadius}
          outerRadius={outerRadius}
          paddingAngle={0}
          dataKey={dataKey}
          nameKey={nameKey}
          minAngle={minAngle}
          onClick={handleClick}
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
          animationBegin={0}
          animationDuration={600}
          animationEasing="ease-out"
          activeShape={(props: any) => {
            const { cx, cy, innerRadius: ir, outerRadius: or, startAngle, endAngle, payload } = props;
            const baseColor = payload?.color || colors[(activeIndex || 0) % colors.length];
            const { offsetX, offsetY } = getExplodedOffset(startAngle, endAngle, cx, cy);
            return (
              <g transform={`translate(${offsetX}, ${offsetY})`}>
                <Sector
                  cx={cx}
                  cy={cy}
                  innerRadius={ir}
                  outerRadius={or}
                  startAngle={startAngle}
                  endAngle={endAngle}
                  fill={baseColor}
                  style={{
                    filter: "drop-shadow(0 4px 12px rgba(0,0,0,0.25))",
                    transition: "all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",
                    cursor: "pointer",
                  }}
                />
              </g>
            );
          }}
          label={showLabels ? renderCustomLabel : false}
        >
          {processedData.map((entry, index) => {
            const baseColor = entry.color || colors[index % colors.length];
            return (
              <Cell
                key={`cell-${index}`}
                fill={getColor(entry, index)}
                style={{
                  cursor: "pointer",
                  transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
                  filter: hoveredIndex === index 
                    ? "brightness(1.15) drop-shadow(0 4px 12px rgba(0,0,0,0.2))" 
                    : "drop-shadow(0 1px 3px rgba(0,0,0,0.1))",
                }}
              />
            );
          })}
        </Pie>
        {customTooltip ? (
          <Tooltip content={customTooltip as any} />
        ) : tooltipFormatter ? (
          <Tooltip
            formatter={(value: any, name: string, props: any) => {
              const entry = props.payload;
              const percentage = entry?.percentage || 0;
              const formattedValue = tooltipFormatter(value, name);
              return [`${formattedValue} (${percentage.toFixed(2)}%)`, name];
            }}
            contentStyle={{
              backgroundColor: "#fff",
              border: "1px solid #e2e8f0",
              borderRadius: "12px",
              boxShadow: "0 8px 16px rgba(0,0,0,0.15)",
              padding: "12px",
            }}
            labelStyle={{
              fontWeight: 600,
              color: "#1e293b",
              marginBottom: "4px",
            }}
          />
        ) : (
          <Tooltip
            formatter={(value: any, name: string, props: any) => {
              const entry = props.payload;
              const percentage = entry?.percentage || 0;
              const formattedValue = currency 
                ? formatCurrency(Number(value), currency)
                : Number(value).toLocaleString("en-US", {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  });
              return [`${formattedValue} (${percentage.toFixed(2)}%)`, name];
            }}
            contentStyle={{
              backgroundColor: "#fff",
              border: "1px solid #e2e8f0",
              borderRadius: "12px",
              boxShadow: "0 8px 16px rgba(0,0,0,0.15)",
              padding: "12px",
            }}
            labelStyle={{
              fontWeight: 600,
              color: "#1e293b",
              marginBottom: "4px",
            }}
          />
        )}
        {showLegend && (
          <Legend
            verticalAlign="bottom"
            height={60}
            layout="horizontal"
            align="center"
            formatter={legendFormatter}
          />
        )}
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
};
