import * as React from "react";
import { HistoryChartProps } from "./HistoryChart.models";
import HistoryChartView from "./HistoryChart.view";
import { buildChartData, tabToKey } from "./HistoryChart.adapter";

export default function HistoryChart(props: HistoryChartProps) {
  const {
    tabs,
    reportData,
    flow,
    comparison,
    selectedPeriodId,
    setSelectedPeriodId
  } = props;

  const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
  const [startIndex, setStartIndex] = React.useState(0);

  const activeDataKey = tabToKey(activeTab);

  const currentData = React.useMemo(() => {
    return buildChartData(reportData, activeDataKey, flow, comparison);
  }, [reportData, activeDataKey, flow, comparison]);

  const maxAmount =
    currentData.length > 0
      ? Math.max(
          ...currentData.flatMap((d) =>
            comparison
              ? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
              : [d.amount]
          ),
          1
        )
      : 1;

  const visibleCountMap = {
    daily: 7,
    weekly: 6,
    monthly: 4,
    all: 4,
  };

  const visibleCount = visibleCountMap[activeDataKey] ?? 4;

  const total = currentData.length;

  const clampedStartIndex = Math.min(
    startIndex,
    Math.max(total - visibleCount, 0)
  );

  React.useEffect(() => {
    if (startIndex !== clampedStartIndex) {
      setStartIndex(clampedStartIndex);
    }
  }, [startIndex, clampedStartIndex]);

  const visibleData = currentData.slice(
    clampedStartIndex,
    clampedStartIndex + visibleCount
  );

  React.useEffect(() => {
    setSelectedPeriodId(null);
  }, [activeTab]);

  React.useEffect(() => {
    if (
      selectedPeriodId &&
      !visibleData.some((p) => p.id === selectedPeriodId)
    ) {
      setSelectedPeriodId(null);
    }
  }, [visibleData, selectedPeriodId]);

  return (
    <HistoryChartView
      {...props}
      activeTab={activeTab}
      setActiveTab={setActiveTab}
      currentData={currentData}
      visibleData={visibleData}
      maxAmount={maxAmount}
      visibleCount={visibleCount}
      startIndex={clampedStartIndex}
      setStartIndex={setStartIndex}
      activeDataKey={activeDataKey}
    />
  );
}
