'use client';
import useSWR from "swr";
import { Chart as ChartJS, registerables } from 'chart.js';
import { Bar } from "react-chartjs-2";
import { Ethics, EthicsDataG15, Species } from '../../types/stellaris';
import { number } from "prop-types";

const fetcher = async (url:any) => await fetch(url).then((res) => res.json());

export const EthicsBar = () => {
  const {data: tmpData} = useSWR('/api/ethics',fetcher);
  const {data: empData} = useSWR('/api/empires',fetcher);

  const parseData = (data: Array<Array<any>>) => {
    let parsedData: EthicsDataG15[] = new Array<EthicsDataG15>;
    Object.keys(Ethics).forEach((ethic: number | string) => {
      if (Number.isInteger(Number(ethic))) {
        parsedData[Number(ethic)] = new EthicsDataG15(data[Number(ethic)])
      }
    });
    return parsedData;
  }

  let ethicsData: EthicsDataG15[];
  let data;
  let empireCount = 0;
  let scaleLimit = 0;

  if (tmpData && empData) {
    let sheetData = tmpData.sheetData
    ethicsData = parseData(sheetData);

    empireCount = empData.empireCount;

    let sumArray = new Array<number>;
    let labelArray = new Array<string>;

    ethicsData.forEach((ethicData, index) => {
      sumArray[index] = ethicData.sum(false);
      labelArray[index] = Ethics[index]
    });

    let zipped: Array<{sums: number, labels: string}> = [];
    for (let i = 0; i<ethicsData.length; i++) {
      zipped.push({sums: ethicsData[i].sum(false), labels: Ethics[i]})
    }
    zipped.sort((a:{sums: number, labels: string}, b:{sums: number, labels: string}) => (a.sums > b.sums ? -1 : 1));
    
    for (let i = 0; i<zipped.length; i++) {
      let z = zipped[i];
      sumArray[i] = z.sums,
      labelArray[i] = z.labels
    }

    

    scaleLimit = sumArray[0] * 1.2;
    scaleLimit = Number(scaleLimit.toFixed(0));
    scaleLimit % 2 == 0 ? scaleLimit = scaleLimit : scaleLimit = scaleLimit - 1;

    data = {
      labels: labelArray,
      datasets: [{
        label: 'Portrait Picks',
        data: sumArray,
        backgroundColor: [
          'rgb(3, 99, 143)',
        ],
        hoverOffset: 4
      }]
    };
  }
  else {
    data = {
      labels: [],
      datasets: [{
        data: [],
        fill: true,
        backgroundColor: '#254A6FAA',
        borderColor: '#356A9F',
        radius: 3
      }]
    };
  }
  

  const config = {
    type: 'bar',
    data: data,
    options: {
      scales: {
        y: {
          beginAtZero: true,
          max: scaleLimit
        }
      },
      plugins: {
        tooltip: {
          callbacks: {
            label: function(ctx: any) {
              return (ctx.dataset.data[ctx.dataIndex]*100/empireCount).toFixed(1) + "% | " + ctx.dataset.data[ctx.dataIndex] + " / " + empireCount
            }
          }
        },
        legend: {
          display: false
        },
        datalabels: {
          display: false
        },
      },
    },
  };

  ChartJS.register( ...registerables )

  return (
    <div className="chart-container h-1/2 aspect-square p-2">
      <Bar {...config} />
    </div>
  );
}