'use client';
import { AppRouterOutput } from '@/server/trpc/types';
import {
  Cell,
  Pie,
  PieChart,
  PieLabelRenderProps,
  ResponsiveContainer,
  LegendProps
} from 'recharts';

type PollResultItem = NonNullable<
  AppRouterOutput['poll']['get']
>['questions'][number];

type RadioParams = PollResultItem['params'] & {
  options: { label: string; value: string }[];
};

const generateColors = (count: number) =>
  Array.from(
    { length: count },
    (_, i) => `hsl(${(i * 360) / count}, 70%, 55%)`
  );

export default function PollPieChart({ item }: { item: PollResultItem }) {
  if (!item.params || !item.stat) return null;

  const params = item.params as RadioParams;

  const data = params.options.map((option) => {
    return {
      name: option.label,
      value:
        (typeof item.stat === 'object' &&
          !('average' in item.stat) &&
          (item.stat[option.value] ?? 0)) ||
        0
    };
  });

  const colors = generateColors(data.length);
  const total = data.reduce((sum, d) => sum + d.value, 0);

  const dataWithPercent = (() => {
    let accumulated = 0;

    return data.map((d, index) => {
      const rawPercent = (d.value / total) * 100;

      const percent =
        index === data.length - 1 ? 100 - accumulated : Math.round(rawPercent);

      accumulated += percent;

      return {
        ...d,
        percent
      };
    });
  })();

  return (
    <div className='grid gap-4'>
      <CustomLegend
        payload={dataWithPercent.map((param, index) => ({
          value: param.name,
          color: colors[index]
        }))}
      />
      <ResponsiveContainer width='100%' height={260}>
        <PieChart>
          <Pie
            data={dataWithPercent}
            dataKey='value'
            nameKey='name'
            labelLine={false}
            label={renderInsideLabel}
            outerRadius={120}
          >
            {dataWithPercent.map((_, index) => (
              <Cell key={`cell-${index}`} fill={colors[index]} />
            ))}
          </Pie>
        </PieChart>
      </ResponsiveContainer>
      <span className='text-end font-serif text-lg text-neutral-700'>
        {total} stemmer
      </span>
    </div>
  );
}

const renderInsideLabel = (
  props: PieLabelRenderProps & { payload?: { percent: number } }
) => {
  const { cx, cy, midAngle, innerRadius, outerRadius, payload } = props;

  if (
    cx == null ||
    cy == null ||
    innerRadius == null ||
    outerRadius == null ||
    !payload
  ) {
    return null;
  }

  if (payload.percent < 1) return null;

  const radius = +innerRadius + (+outerRadius - +innerRadius) * 0.5;
  const x = +cx + radius * Math.cos(-midAngle * (Math.PI / 180));
  const y = +cy + radius * Math.sin(-midAngle * (Math.PI / 180));

  return (
    <text
      x={x}
      y={y}
      fill='white'
      fontSize={14}
      fontWeight={600}
      textAnchor='middle'
      dominantBaseline='central'
    >
      {payload.percent}%
    </text>
  );
};

const CustomLegend = ({ payload }: LegendProps) => {
  if (!payload) return null;

  return (
    <ul className='flex flex-col gap-2'>
      {payload.map((entry, index) => (
        <li
          key={index}
          className='flex items-center gap-3 font-serif text-lg text-black'
        >
          <span
            className='inline-block size-6 rounded-full'
            style={{ backgroundColor: entry.color }}
          />
          <span>{entry.value}</span>
        </li>
      ))}
    </ul>
  );
};
