import Styles from "@/constants/Styles";
import { apiGetDataHome } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import { Dimensions, View } from "react-native";
import { BarChart } from "react-native-gifted-charts";
import Skeleton from "../skeleton";
import Text from "../Text";

type Props = {
   value: number;
   label: string;
   frontColor: string;
}[]

export default function ChartDokumenHome({ refreshing }: { refreshing: boolean }) {
   const { decryptToken, token } = useAuthSession()
   const { colors } = useTheme();
   const width = Dimensions.get("window").width;

   // TanStack Query for Document Chart data
   const { data: chartData = [], isLoading, isFetching } = useQuery({
      queryKey: ['homeData', 'dokumen'],
      queryFn: async () => {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDataHome({ cat: "dokumen", user: hasil })
         return response.data.map((item: { color: any; label: any; value: any; }) => {
            const val = Number(item.value) || 0;
            return {
               frontColor: val > 0 ? (item.color || '#fac858') : 'transparent',
               label: item.label,
               value: val,
            }
         }) as Props
      },
      enabled: !!token?.current,
      staleTime: 0,
   })

   // Derived state for maxValue
   const maxValue = useMemo(() => {
      const maxVal = chartData.reduce((max: number, obj: { value: number; }) => Math.max(max, obj.value), 0);
      // Adjust maxValue and intervals based on the data
      if (maxVal === 0) return 10;
      if (maxVal < 5) return 5;
      return Math.ceil(maxVal / 10) * 10;
   }, [chartData]);
 
   const barData = useMemo(() => {
      return chartData.map(item => ({
         ...item,
         topLabelComponent: () => (
            <View style={{ marginBottom: 5 }}>
               <Text style={{ color: colors.text, fontSize: 12 }}>{item.value > 0 ? item.value : ""}</Text>
            </View>
         )
      }))
   }, [chartData, colors.text]);

   return (
      <View style={[Styles.wrapPaper, Styles.contentItemCenter, Styles.mb15, { backgroundColor: colors.card, borderColor: colors.icon + '20' }]}>
         <Text style={[Styles.textSubtitle, Styles.mv15]}>JUMLAH DOKUMEN</Text>
         {
            isLoading || (refreshing && isFetching) ? <Skeleton width={100} height={200} borderRadius={10} widthType="percent" />
               :
               <BarChart
                  key={JSON.stringify(chartData)}
                  showFractionalValues={false}
                  showYAxisIndices
                  noOfSections={maxValue < 5 ? (maxValue === 0 ? 4 : maxValue) : 4}
                  maxValue={maxValue}
                  data={barData}
                  isAnimated
                  width={width - 140}
                  barWidth={width * 0.25}
                  yAxisTextStyle={{ color: colors.text }}
                  xAxisLabelTextStyle={{ color: colors.text }}
               />
         }
      </View>
   )
}