import {
  View,
  Text,
  ScrollView,
  LayoutChangeEvent,
  Image,
  BackHandler,
} from 'react-native'
import React, { useState, useEffect } from 'react'
import { Header } from '../../../../commonComponents'
import styles from './styles'
import ProgressBarSvg from './ProgressBarSvg'
import { useNavigation, useRoute } from '@react-navigation/native'
import { useValues } from '../../../../utils/context'
import appColors from '../../../../theme/appColors'
import { useSelector } from 'react-redux'
import Images from '../../../../utils/images/images'
import {
  fontSizes,
  windowHeight,
  windowWidth,
} from '../../../../theme/appConstant'
import appFonts from '../../../../theme/appFonts'
import FastImage from 'react-native-fast-image'

export function IncentiveTask() {
  const route = useRoute<any>()
  const { tasks = [], data: completedRides = 0 } = route.params || {}
  const { isDark, viewRtlStyle } = useValues()
  const [incentiveTasks, setIncentiveTasks] = useState<any[]>([])
  const [progressBarWidth, setProgressBarWidth] = useState(0)
  const { translateData,settingData } = useSelector((state: any) => state.setting)
  const { zoneValue } = useSelector((state: any) => state.zoneUpdate)


  useEffect(() => {
    if (Array.isArray(tasks) && tasks.length > 0) {
      const mappedTasks = tasks.map((level: any) => {
        const rideValue = Math.min(completedRides, level.target_rides)
        return {
          ...level,
          rideValue,
        }
      })
      setIncentiveTasks(mappedTasks)
    } else {
      setIncentiveTasks([])
    }
  }, [tasks, completedRides])

  const getProgress = (rideValue: number, totalRide: number) => {
    if (!totalRide) return 0
    return (rideValue / totalRide) * 100
  }

  const getSvgWidth = (rideValue: number, totalRide: number) => {
    const progressPercentage = getProgress(rideValue, totalRide)
    return (progressBarWidth * progressPercentage) / 100
  }

  const handleProgressBarLayout = (event: LayoutChangeEvent) => {
    const { width } = event.nativeEvent.layout
    if (width > 0 && progressBarWidth === 0) {
      setProgressBarWidth(width)
    }
  }
  const navigation = useNavigation()

  useEffect(() => {
    const backAction = () => {
      if (navigation.canGoBack()) {
        navigation.goBack()
        return true
      }
      return false
    }

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    )

    return () => backHandler.remove()
  }, [navigation])

  return (
    <View
      style={[
        styles.container,
        { backgroundColor: isDark ? appColors.bgDark : appColors.lightGray },
      ]}
    >
      <Header title={translateData.viewAllTask} style={styles.gap} />

      {incentiveTasks.length === 0 ? (
        <View
          style={{
            marginBottom: windowHeight(5),
            alignItems: 'center',
            marginTop: windowHeight(16),
          }}
        >
          <FastImage
            source={isDark ? Images.noVehicleDark : Images.noVehicle}
            style={{
              height: windowHeight(30),
              width: windowHeight(30),
            }}
            resizeMode="contain"
          />

          <View
            style={{
              flexDirection: viewRtlStyle,
              alignItems: 'center',
              marginTop: windowHeight(2),
            }}
          >
            <Text
              style={{
                color: isDark ? appColors.white : appColors.black,
                fontSize: fontSizes.FONT4HALF,
                fontFamily: appFonts.medium,
                textAlign: 'center',
                marginRight: 6,
              }}
            >
              {translateData.EmptyviewList}
            </Text>
            <FastImage
              source={Images.infoCircle}
              style={{
                height: windowHeight(2.5),
                width: windowHeight(2.5),
              }}
              resizeMode="contain"
            />
          </View>

          <Text
            style={{
              textAlign: 'center',
              paddingHorizontal: windowWidth(5),
              color: appColors.darkBorderBlack,
              marginTop: windowHeight(1),
            }}
          >
            {translateData.incentivePleasetryrefreshing}
          </Text>
        </View>
      ) : (
        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={styles.scrollContent}
          showsVerticalScrollIndicator={false}
        >
          {incentiveTasks.map(task => (
            <View
              key={task.id}
              style={[
                styles.taskCard,
                {
                  backgroundColor: isDark
                    ? appColors.darkThemeSub
                    : appColors.white,
                },
                {
                  borderColor: isDark ? appColors.darkborder : appColors.loader,
                },
              ]}
            >
              <View
                style={{
                  flexDirection: viewRtlStyle,
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}
              >
                <Text
                  style={[
                    styles.taskTitle,
                    { color: isDark ? appColors.white : appColors.black },
                  ]}
                >
                  {translateData?.level} {task.level_number} -{' '}
                  {translateData?.complete} {task.target_rides}{' '}
                  {translateData?.ridesearn} {zoneValue?.currency_symbol}{task.incentive_amount}
                </Text>
                <Text
                  style={[
                    styles.progressText,
                    {
                      color: isDark
                        ? appColors.darkText
                        : appColors.secondaryFont,
                    },
                  ]}
                >
                  {task.rideValue}/{task.target_rides}
                </Text>
              </View>

              <Image source={Images.barImage} style={styles.image} />

              <View style={styles.progressContainer}>
                <View
                  style={[
                    styles.progressBarBackground,
                    {
                      backgroundColor: isDark
                        ? appColors.darkborder
                        : appColors.border,
                    },
                  ]}
                  onLayout={handleProgressBarLayout}
                >
                  {progressBarWidth > 0 && (
                    <View
                      style={[
                        styles.progressBarFill,
                        {
                          width: `${getProgress(
                            task.rideValue,
                            task.target_rides,
                          )}%`,
                        },
                      ]}
                    >
                      <ProgressBarSvg
                        width={getSvgWidth(task.rideValue, task.target_rides)}
                        height={16}
                      />
                    </View>
                  )}
                </View>
              </View>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  )
}
