import Styles from "@/constants/Styles";
import { Dimensions, View } from "react-native";
import { BarChart } from "react-native-gifted-charts";
import { useTheme } from "@/providers/ThemeProvider";
import { useMemo } from "react";
import Text from "../Text";

export default function ReportChartEvent({ data }: { data: { label: string; value: number; }[] }) {
   const { colors } = useTheme();
   const width = Dimensions.get("window").width;
 
   const maxValue = useMemo(() => {
      const maxVal = data.reduce((max: number, obj: { value: number; }) => Math.max(max, obj.value), 0);
      if (maxVal === 0) return 10;
      if (maxVal < 5) return 5;
      return Math.ceil(maxVal / 10) * 10;
   }, [data]);
 
   const barData = useMemo(() => {
      return data.map(item => ({
         ...item,
         frontColor: item.value > 0 ? "#177AD5" : "transparent",
         topLabelComponent: () => (
            <View style={{ marginBottom: 5 }}>
               <View
                  style={{
                     alignItems: 'center',
                     justifyContent: 'center',
                     width: width * 0.25
                  }}>
                  <Text style={{ color: colors.text, fontSize: 12 }}>{item.value > 0 ? item.value : ""}</Text>
               </View>
            </View>
         )
      }))
   }, [data, colors.text]);

   return (
      <View style={[Styles.wrapPaper, Styles.contentItemCenter, Styles.mb15, { backgroundColor: colors.card, borderColor: colors.background }]}>
         <Text style={[Styles.textSubtitle, Styles.mv15]}>ACARA DIVISI</Text>
         <BarChart
            key={JSON.stringify(data)}
            xAxisLabelTextStyle={{ color: colors.text }}
            yAxisTextStyle={{ color: colors.text }}
            showFractionalValues={false}
            showYAxisIndices
            noOfSections={maxValue < 5 ? (maxValue === 0 ? 4 : maxValue) : 4}
            maxValue={maxValue}
            data={barData}
            isAnimated
            width={width - 140}
            barWidth={width * 0.25}
         />
      </View>
   )
}