'use client';

import { useState } from 'react';
import {
  PieChart as RechartsPieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  Legend,
  Sector,
} from 'recharts';

import { ChartContainer, ChartEmptyState } from './chart-container';

interface PieChartDataPoint {
  name: string;
  value: number;
  color: string;
}

interface PieChartProps {
  /** Chart title */
  title: string;
  /** Optional description */
  description?: string;
  /** Data points to display */
  data: PieChartDataPoint[];
  /** Whether data is loading */
  isLoading?: boolean;
  /** Chart height */
  height?: number;
  /** Whether to show legend */
  showLegend?: boolean;
  /** Whether to show as donut chart */
  donut?: boolean;
  /** Inner radius for donut chart (percentage) */
  innerRadius?: number;
  /** Whether to show labels */
  showLabels?: boolean;
  /** Whether to animate on hover */
  activeOnHover?: boolean;
  /** Additional CSS classes */
  className?: string;
}

/**
 * Render active sector for hover effect
 */
const renderActiveShape = (props: any) => {
  const {
    cx,
    cy,
    innerRadius,
    outerRadius,
    startAngle,
    endAngle,
    fill,
    payload,
    percent,
    value,
  } = props;

  return (
    <g>
      <text x={cx} y={cy - 10} dy={8} textAnchor="middle" fill="hsl(var(--foreground))" className="text-sm font-medium">
        {payload.name}
      </text>
      <text x={cx} y={cy + 10} dy={8} textAnchor="middle" fill="hsl(var(--muted-foreground))" className="text-xs">
        {value} ({(percent * 100).toFixed(0)}%)
      </text>
      <Sector
        cx={cx}
        cy={cy}
        innerRadius={innerRadius}
        outerRadius={outerRadius + 10}
        startAngle={startAngle}
        endAngle={endAngle}
        fill={fill}
      />
      <Sector
        cx={cx}
        cy={cy}
        startAngle={startAngle}
        endAngle={endAngle}
        innerRadius={outerRadius + 12}
        outerRadius={outerRadius + 14}
        fill={fill}
      />
    </g>
  );
};

/**
 * Pie/Donut Chart component using Recharts
 * Supports pie and donut variants with hover effects
 */
export function PieChart({
  title,
  description,
  data,
  isLoading = false,
  height = 300,
  showLegend = true,
  donut = false,
  innerRadius = 60,
  showLabels = false,
  activeOnHover = true,
  className,
}: PieChartProps) {
  const [activeIndex, setActiveIndex] = useState<number | undefined>(undefined);

  if (!isLoading && data.length === 0) {
    return (
      <ChartContainer title={title} description={description} height={height} className={className}>
        <ChartEmptyState />
      </ChartContainer>
    );
  }

  const onPieEnter = (_: any, index: number) => {
    if (activeOnHover) {
      setActiveIndex(index);
    }
  };

  const onPieLeave = () => {
    if (activeOnHover) {
      setActiveIndex(undefined);
    }
  };

  const total = data.reduce((sum, item) => sum + item.value, 0);

  return (
    <ChartContainer
      title={title}
      description={description}
      isLoading={isLoading}
      height={height}
      className={className}
    >
      <ResponsiveContainer width="100%" height="100%">
        <RechartsPieChart>
          <Pie
            data={data}
            cx="50%"
            cy="50%"
            innerRadius={donut ? `${innerRadius}%` : 0}
            outerRadius="80%"
            paddingAngle={data.length > 1 ? 2 : 0}
            dataKey="value"
            onMouseEnter={onPieEnter}
            onMouseLeave={onPieLeave}
            activeIndex={activeIndex}
            activeShape={activeOnHover ? renderActiveShape : undefined}
            label={
              showLabels && !activeOnHover
                ? ({ name, percent }) => `${name} (${(percent * 100).toFixed(0)}%)`
                : false
            }
            labelLine={showLabels && !activeOnHover}
          >
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={entry.color} />
            ))}
          </Pie>

          <Tooltip
            contentStyle={{
              backgroundColor: 'hsl(var(--popover))',
              border: '1px solid hsl(var(--border))',
              borderRadius: '0.5rem',
              color: 'hsl(var(--popover-foreground))',
            }}
            formatter={(value: number, name: string) => [
              `${value} (${((value / total) * 100).toFixed(1)}%)`,
              name,
            ]}
          />

          {showLegend && (
            <Legend
              layout="vertical"
              align="right"
              verticalAlign="middle"
              wrapperStyle={{ paddingLeft: '20px' }}
              formatter={(value, entry: any) => (
                <span className="text-sm text-foreground">{value}</span>
              )}
            />
          )}
        </RechartsPieChart>
      </ResponsiveContainer>
    </ChartContainer>
  );
}
