'use client';
import { AppRouterOutput } from '@/server/trpc/types';

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

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

export default function PollBarChart({ 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 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-6'>
      {dataWithPercent.map((item) => (
        <div key={item.name} className='flex flex-col gap-2'>
          <span className='font-serif text-lg text-neutral-800'>
            {item.name}
          </span>

          <div className='relative h-10 w-full overflow-hidden'>
            <div
              className='bg-client-red flex size-full items-center transition-all'
              style={{ width: `${item.percent}%` }}
            >
              <span className='w-full px-1 text-end font-bold break-normal text-white'>
                {item.percent > 0 && `${item.percent}%`}
              </span>
            </div>
          </div>
        </div>
      ))}
      <span className='text-end font-serif text-lg text-neutral-700'>
        {total} stemmer
      </span>
    </div>
  );
}
