import { useCallback, useMemo, useState } from 'react';

import { groupBy } from '../../utils/helperUtil';

import React from 'react';
import { getConfig } from '../ColorsConfig';
import { YearBox } from './YearBox';
import {
  IYearsCalendarConfig,
  MousePos,
  YearCalendarData,
  YearsCalendarConfig,
  defaultConfig,
} from './YearConfigs';
import { ChartTooltip } from './ChartTooltip';

export type YearsCalendarProps = {
  items: Array<YearCalendarData>;
  config?: IYearsCalendarConfig;
  onClick?: (data: YearCalendarData | null) => void;
  onHover?: (data: YearCalendarData | null) => void;
  tooltip?: React.FC<{ item?: YearCalendarData }>;
};

export function YearsCalendar(props: YearsCalendarProps) {
  const { items, config, onClick, onHover, tooltip } = props;

  const [selected, setSelected] = useState<YearCalendarData | null>(null);
  const [pos, setPos] = useState<MousePos | null>(null);

  const groupedItems = useMemo(
    () => groupBy(items, (item: YearCalendarData) => item.date.getFullYear()),
    [items]
  );

  const theConfig = useMemo(
    () =>
      ({
        ...defaultConfig,
        ...getConfig(config),
      } as YearsCalendarConfig),
    [config]
  );

  const handleHover = useCallback(
    (item: YearCalendarData, pos1: MousePos) => {
      setSelected(item);
      setPos(pos1);
      if (onHover) onHover(item);
    },
    [setSelected, onHover]
  );

  return (
    <div
      style={{
        padding: '10px',
        display: 'flex',
        flexDirection: 'column',
        rowGap: 8,
      }}
    >
      {Object.keys(groupedItems).map((key: any, i: number) => (
        <YearBox
          key={i}
          year={key}
          items={groupedItems[key]}
          config={theConfig}
          onClick={onClick}
          onHover={handleHover}
        />
      ))}
      <ChartTooltip
        tooltip={tooltip}
        selected={selected}
        pos={pos}
        onClose={useCallback(() => setSelected(null), [])}
      />
    </div>
  );
}
