'use client';
import { FC } from 'react';
import {
  Bar,
  CartesianGrid,
  Tooltip,
  XAxis,
  YAxis,
  BarChart,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import { Open_Sans } from 'next/font/google';
import clsx from 'clsx';
import { TotalGraphicProps } from '@/pagesComponents/Dashboard/Graphics/types';

interface BarChartProps<T extends Record<string, any>> extends TotalGraphicProps {
  data: T[];
  isMixBarChart?: boolean;
  xKey: keyof T;
  yKeys: Array<keyof T>;
  xFormat?: (value: any, index: number) => string;
  labelFormatter?: (payload: T) => React.ReactNode;
}

const openSans = Open_Sans({ subsets: ['latin'] });

export const BarChartGraphic = <T extends object>({
  data,
  className,
  height = 256,
  isMixBarChart,
  yKeys,
  xKey,
  xFormat,
  labelFormatter
}: BarChartProps<T>) => {
  return (
    <ResponsiveContainer width='100%' height={height}>
      <BarChart data={data} className={clsx(className)}>
        {isMixBarChart && <Legend />}
        <CartesianGrid strokeDasharray='3 3' />
        {!isMixBarChart && (
          <>
            <XAxis
              dataKey={xKey as string}
              className={`[&_text]:text-[12px] [&_text]:leading-4 [&_text]:text-[#6B6B6B] ${openSans.className} [&_line]:hidden`}
              tickFormatter={xFormat}
            />
            <YAxis
              className={`[&_text]:text-[12px] [&_text]:leading-4 [&_text]:text-[#6B6B6B] ${openSans.className} [&_line]:hidden`}
            />
          </>
        )}

        <Tooltip labelFormatter={labelFormatter ? (_, item) => {return !item[0] ? null : labelFormatter(item[0]?.payload)} : undefined}/>
        {yKeys.map((el) => (
          <Bar
            key={el as string}
            dataKey={el as string}
            fill='#01CFE7'
            radius={0}
            width={24}
            stackId={isMixBarChart ? 'a' : undefined}
          />
        ))}
        {isMixBarChart && <Bar dataKey='amt' fill='#15CAB8' radius={10} />}
      </BarChart>
    </ResponsiveContainer>
  );
};
