import React, { useEffect } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  Image,
  ScrollView,
  BackHandler,
  ImageBackground,
} from 'react-native'
import appColors from '../../theme/appColors'
import { fontSizes, windowHeight, windowWidth } from '../../theme/appConstant'
import appFonts from '../../theme/appFonts'
import Icons from '../../utils/icons/icons'
import Images from '../../utils/images/images'
import { useSelector } from 'react-redux'
import { useNavigation, useTheme } from '@react-navigation/native'
import { useValues } from '../../utils/context'
import { notificationHelper } from '../../commonComponents'
import styles from './styles'
import { useAppNavigation } from '../../utils/navigation'
import commanStyles from '../../style/commanStyles'
import Svg, {
  Rect,
  Defs,
  LinearGradient,
  Stop,
  Pattern,
  Path,
  ClipPath,
  G,
} from 'react-native-svg'

export function DashBoard() {
  const { dashBoardList } = useSelector((state: any) => state.dashboard)
  const size = windowHeight(20)
  const strokeWidth = windowHeight(2)
  const radius = (size - strokeWidth) / 2
  const cx = size / 2
  const cy = size / 2
  const total =
    dashBoardList?.ride?.completed_rides +
    dashBoardList?.ride?.pending_rides +
    dashBoardList?.ride?.cancelled_rides
  const { navigate } = useAppNavigation()
  const { isDark, rtl, viewRtlStyle } = useValues()
  const { translateData } = useSelector((state: any) => state.setting)
  const { selfDriver } = useSelector((state: any) => state.account)
  const char = selfDriver?.name ? selfDriver.name.charAt(0) : ''
  const { colors } = useTheme()

  const data = [
    {
      value: dashBoardList?.ride?.completed_rides,
      color: appColors.online,
      label: translateData.completed,
      textColor: appColors.online,
    },
    {
      value: dashBoardList?.ride?.pending_rides,
      color: appColors.pending,
      label: translateData.pendingRide,
      textColor: appColors.pending,
    },
    {
      value: dashBoardList?.ride?.cancelled_rides,
      color: appColors.reject,
      label: translateData.cancelled,
      textColor: appColors.reject,
    },
  ]

  const gotoDetails = () => {
    if (dashBoardList?.ride?.total_earnings > 0) {
      navigate('TotalEarnings')
    } else {
      notificationHelper('', translateData?.earnnote, 'success')
    }
  }
  const navigation = useNavigation<any>()
  useEffect(() => {
    const backAction = () => {
      navigation.goBack()
      return true
    }

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

    return () => backHandler.remove()
  }, [])
  const gotoBack = () => {
    navigation.goBack()
  }
  const total1 = data.reduce((sum, item) => sum + item.value, 0)
  const barWidth = 300 // Adjust width
  const barHeight = 25
  const borderRadius = 12

  let startX = 0

  return (
    <ScrollView
      showsVerticalScrollIndicator={false}
      style={{
        marginBottom: windowHeight(8),
        backgroundColor: isDark ? appColors.bgDark : appColors.graybackground,
        flex: 1,
      }}
    >
      <View>
        <View
          style={{
            flexDirection: rtl ? 'row-reverse' : 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            height: windowHeight(11),
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            borderBottomEndRadius: windowWidth(5),
            borderBottomStartRadius: windowWidth(5),
            paddingHorizontal: windowWidth(4),
            elevation: 1,
          }}
        >
          <View
            style={{
              flexDirection: rtl ? 'row-reverse' : 'row',
              alignItems: 'center',
            }}
          >
            <TouchableOpacity
              activeOpacity={0.7}
              onPress={gotoBack}
              style={[
                commanStyles.backButtonMain,
                {
                  backgroundColor: colors.card,
                  borderColor: isDark ? appColors.darkborder : appColors.border,
                },
              ]}
            >
              <Icons.Back color={colors.text} />
            </TouchableOpacity>

            <Text
              style={{
                color: isDark ? appColors.white : appColors.primaryFont,
                fontFamily: appFonts.semiBold,
                fontSize: fontSizes.FONT4HALF,
                marginHorizontal: windowWidth(4),
              }}
            >
              {translateData.dashboard}
            </Text>
          </View>

          <View
            style={{
              backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
              width: windowWidth(28),
              height: windowHeight(6),
              borderRadius: windowWidth(25),
              flexDirection: viewRtlStyle,
              alignItems: 'center',
              paddingHorizontal: windowWidth(2.5),
            }}
          >
            <TouchableOpacity
              onPress={() => navigate('Notification')}
              activeOpacity={0.9}
              style={{
                height: windowHeight(4.5),
                width: windowHeight(4.5),
                backgroundColor: isDark
                  ? appColors.primaryFont
                  : appColors.white,
                borderRadius: windowHeight(15),
                alignItems: 'center',
                justifyContent: 'center',
                borderColor: isDark ? appColors.darkborder : appColors.white,
                borderWidth: 1,
              }}
            >
              <Icons.Notification
                color={isDark ? appColors.white : appColors.primaryFont}
              />
            </TouchableOpacity>
            <View
              style={{
                height: windowHeight(3),
                width: windowWidth(0.45),
                backgroundColor: isDark
                  ? appColors.darkborder
                  : appColors.border,
                marginHorizontal: windowWidth(2),
              }}
            />

            <TouchableOpacity
              activeOpacity={0.9}
              onPress={() => navigate('ProfileSetting')}
            >
              {selfDriver?.profile_image_url ? (
                <Image
                  style={{
                    backgroundColor: appColors.primary,
                    height: windowHeight(4.5),
                    width: windowHeight(4.5),
                    borderRadius: windowHeight(5),
                  }}
                  source={{
                    uri: selfDriver?.profile_image_url,
                  }}
                />
              ) : (
                <View
                  style={{
                    alignItems: 'center',
                    justifyContent: 'center',
                    width: windowHeight(4.5),
                    height: windowHeight(4.5),
                    backgroundColor: isDark ? appColors.white : appColors.black,
                    borderRadius: windowHeight(74),
                  }}
                >
                  <Text
                    style={{
                      color: isDark ? appColors.black : appColors.white,
                      fontFamily: appFonts.bold,
                      fontSize: fontSizes.FONT5,
                    }}
                  >
                    {char}
                  </Text>
                </View>
              )}
            </TouchableOpacity>
          </View>
        </View>

        <View
          style={[
            styles.box,
            {
              backgroundColor: colors.card,
              borderColor: colors.border,
            },
          ]}
        >
          <View
            style={{
              flexDirection: viewRtlStyle,
              alignItems: 'center',
              justifyContent: 'space-between',
              width: windowWidth(83),
            }}
          >
            <ImageBackground
              style={{
                width: windowWidth(40),
                height: windowHeight(13),
                paddingVertical: windowHeight(1.5),
              }}
              source={Images.cardBackground}
              borderRadius={windowWidth(5)}
            >
              <View
                style={{
                  flexDirection: viewRtlStyle,
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  marginHorizontal: windowWidth(3),
                }}
              >
                <Text
                  style={{
                    color: appColors.iconColor,
                    fontSize: windowWidth(4),
                    fontFamily: appFonts.medium,
                  }}
                >
                  {translateData?.todayEarning}
                </Text>
              </View>
              <Text
                style={{
                  color: appColors.black,
                  fontSize: fontSizes.FONT5HALF,
                  fontFamily: appFonts.bold,
                  marginTop: windowHeight(1),
                  marginHorizontal: windowWidth(4),
                }}
              >
                {dashBoardList?.ride?.currency_symbol}
                {dashBoardList?.ride?.total_earnings}
              </Text>
              {/* <View
                style={{
                  alignItems: 'center',
                  flexDirection: viewRtlStyle,
                  marginHorizontal: windowWidth(4),
                  marginTop: windowHeight(0.5),
                }}
              >
                <Icons.UpArrow />
                <Text
                  style={{
                    color: appColors.online,
                    fontSize: fontSizes.FONT3HALF1,
                    fontFamily: appFonts.semiBold,
                    marginHorizontal: windowWidth(0.5),
                  }}
                >
                  +10%
                </Text>
              </View> */}
            </ImageBackground>

            <ImageBackground
              style={{
                width: windowWidth(40),
                height: windowHeight(13),
                paddingVertical: windowHeight(1.5),
              }}
              source={Images.chart}
              borderRadius={windowWidth(5)}
            >
              <TouchableOpacity onPress={gotoDetails} activeOpacity={0.7}>
                <View
                  style={{
                    flexDirection: viewRtlStyle,
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    marginHorizontal: windowWidth(3),
                  }}
                >
                  <Text
                    style={{
                      color: appColors.iconColor,
                      fontSize: windowWidth(4),
                      fontFamily: appFonts.medium,
                    }}
                  >
                    {translateData?.totalEarning}
                  </Text>

                  <Icons.GoArrow />
                </View>
                <Text
                  style={{
                    color: appColors.black,
                    fontSize: fontSizes.FONT5HALF,
                    fontFamily: appFonts.bold,
                    marginTop: windowHeight(1),
                    marginHorizontal: windowWidth(4),
                  }}
                >
                  {dashBoardList?.ride?.currency_symbol}
                  {dashBoardList?.ride?.total_earnings}
                </Text>
                <Text
                  style={{
                    color: appColors.iconColor,
                    fontSize: fontSizes.FONT3HALF1,
                    fontFamily: appFonts.medium,
                    marginTop: windowHeight(1),
                    marginHorizontal: windowWidth(4),
                  }}
                >
                  {translateData?.alltimeearing}
                </Text>
              </TouchableOpacity>
            </ImageBackground>
          </View>

          <Text
            style={{
              marginTop: windowHeight(1.5),
              color: appColors.iconColor,
              fontFamily: appFonts.regular,
            }}
          >
            {translateData?.dashBoardLine}
          </Text>
        </View>

        <View
          style={[
            styles.chartContainer,
            {
              backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            },
            { borderColor: isDark ? appColors.darkborder : appColors.border },
          ]}
        >
          <View style={[styles.centerText, { flexDirection: viewRtlStyle }]}>
            <Text
              style={[
                styles.title,
                { color: isDark ? appColors.white : appColors.black },
              ]}
            >
              {translateData.totalBooking}
            </Text>
            <Text style={styles.count}>{total}</Text>
          </View>

          <Image source={Images.barImage} style={styles.image} />
          <View style={{ alignItems: 'center', marginTop: 0 }}>
            <Svg width={barWidth} height={barHeight}>
              <Defs>
                <Pattern
                  id="diagonalPattern"
                  patternUnits="userSpaceOnUse"
                  width="8"
                  height="8"
                  patternTransform="rotate(45)"
                >
                  <Path
                    d="M 0 0 L 0 8"
                    stroke="white"
                    strokeWidth="2"
                    opacity="0.2"
                  />
                </Pattern>

                <ClipPath id="clipRounded">
                  <Rect
                    width={barWidth}
                    height={barHeight}
                    rx={borderRadius}
                    ry={borderRadius}
                  />
                </ClipPath>
              </Defs>

              <G clipPath="url(#clipRounded)">
                {total1 > 0 ? (
                  data.map((item, index) => {
                    const segmentWidth = (item.value / total1) * barWidth

                    const rect = (
                      <Rect
                        key={index}
                        x={startX}
                        y={0}
                        width={segmentWidth - 1}
                        height={barHeight}
                        fill={item.color}
                      />
                    )

                    const stripeOverlay = (
                      <Rect
                        key={`pattern-${index}`}
                        x={startX}
                        y={0}
                        width={segmentWidth - 1}
                        height={barHeight}
                        fill="url(#diagonalPattern)"
                      />
                    )

                    startX += segmentWidth
                    return [rect, stripeOverlay]
                  })
                ) : (
                  // 👇 Default gray bar when data = 0
                  <Rect
                    x={0}
                    y={0}
                    width={barWidth}
                    height={barHeight}
                    fill="#EEEEEE"
                  />
                )}
              </G>

              <Rect
                x={0}
                y={0}
                width={barWidth}
                height={barHeight}
                rx={borderRadius}
                ry={borderRadius}
                fill="none"
              />
            </Svg>
          </View>

          <View
            style={[
              styles.statusContainer,
              {
                backgroundColor: isDark
                  ? appColors.primaryFont
                  : appColors.white,
                flexDirection: rtl ? 'row-reverse' : 'row',
              },
            ]}
          >
            {data.map((item, index) => (
              <View style={styles.statusBox} key={index}>
                <View style={styles.statusTop}>
                  <Text
                    style={[
                      styles.statusLabel,
                      {
                        color: isDark
                          ? appColors.darkText
                          : appColors.iconColor,
                      },
                    ]}
                  >
                    {item.label}
                  </Text>
                </View>
                <Text
                  style={[
                    styles.statusValue,
                    {
                      color:
                        item.textColor ||
                        (isDark ? appColors.white : appColors.black),
                      textAlign: 'center',
                    },
                  ]}
                >
                  {item.value}
                </Text>
              </View>
            ))}
          </View>
        </View>

        <Text
          style={{
            color: isDark ? appColors.white : appColors.black,
            marginHorizontal: windowWidth(5),
            marginTop: windowHeight(2.5),
            fontFamily: appFonts.semiBold,
            fontSize: fontSizes.FONT4HALF,
          }}
        >
          {translateData.drivePerformance}
        </Text>

        <View
          style={{
            flexDirection: viewRtlStyle,
            alignItems: 'center',
            justifyContent: 'space-between',
            marginBottom: windowHeight(5),
            alignSelf: 'center',
            width: '100%',
            // backgroundColor:'red'
          }}
        >
          <View
            style={{
              gap: 5,
              paddingHorizontal: windowWidth(3),
            }}
          >
            <View
              style={{
                height: windowHeight(24),
                width: windowHeight(21),
                borderColor: isDark ? appColors.darkborder : appColors.border,
                borderWidth: windowWidth(0.45),
                borderRadius: windowWidth(5),
                marginTop: windowHeight(2),
                backgroundColor: colors.card,
              }}
            >
              <View style={{ flexDirection: rtl ? 'row-reverse' : 'row' }}>
                <View
                  style={{
                    backgroundColor: '#E9F4FE',
                    height: windowHeight(6),
                    width: windowHeight(6),
                    borderRadius: windowHeight(0.7),
                    marginTop: windowHeight(2),
                    marginHorizontal: windowHeight(1.5),
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Image
                    source={Images.mapFrame1}
                    resizeMode="contain"
                    style={{
                      height: windowHeight(4),
                      width: windowHeight(3),
                    }}
                    tintColor={appColors.active}
                  />
                </View>
                <View>
                  <Text
                    style={{
                      color: appColors.active,
                      top: windowHeight(2.5),
                      fontFamily: appFonts.bold,
                      fontSize: fontSizes.FONT5,
                    }}
                  >
                    {dashBoardList?.driver_performance?.total_distance}
                  </Text>
                  <Text
                    style={{
                      color: appColors.iconColor,
                      top: windowHeight(2),
                      fontFamily: appFonts.medium,
                      fontSize: fontSizes.FONT3HALF1,
                    }}
                  >
                    {dashBoardList?.driver_performance?.unit}
                  </Text>
                </View>
              </View>
              <Image
                source={Images.mapFrame4}
                style={{
                  height: windowHeight(10),
                  width: windowHeight(20),
                  alignSelf: 'center',
                  top: windowHeight(0.5),
                }}
              />
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.black,
                  marginHorizontal: windowHeight(2),
                  marginTop: windowHeight(1.7),
                  fontFamily: appFonts.semiBold,
                  textAlign: rtl ? 'right' : 'left',
                }}
              >
                {translateData.totalDistances}
              </Text>
            </View>
            <View
              style={{
                height: windowHeight(14),
                width: windowHeight(20),
                borderColor: isDark ? appColors.darkborder : appColors.border,
                borderWidth: windowWidth(0.45),
                borderRadius: windowWidth(5),
                marginTop: windowHeight(2),
                backgroundColor: colors.card,
              }}
            >
              <View style={{ flexDirection: rtl ? 'row-reverse' : 'row' }}>
                <View
                  style={{
                    backgroundColor: appColors.approvBg,
                    height: windowHeight(6),
                    width: windowHeight(6),
                    borderRadius: windowHeight(0.7),
                    marginTop: windowHeight(2),
                    marginHorizontal: windowHeight(2),
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Image
                    source={Images.mapFrame}
                    resizeMode="contain"
                    style={{
                      height: windowHeight(4),
                      width: windowHeight(3),
                    }}
                    tintColor={appColors.online}
                  />
                </View>
                <View>
                  <Text
                    style={{
                      color: appColors.online,
                      top: windowHeight(2),
                      fontFamily: appFonts.bold,
                      fontSize: fontSizes.FONT5,
                      textAlign: rtl ? 'right' : 'left',
                    }}
                  >
                    {dashBoardList?.driver_performance?.average_distance}
                  </Text>
                  <Text
                    style={{
                      color: appColors.iconColor,
                      top: windowHeight(2),
                      fontFamily: appFonts.medium,
                      fontSize: fontSizes.FONT3HALF1,
                      textAlign: rtl ? 'right' : 'left',
                    }}
                  >
                    {dashBoardList?.driver_performance?.unit}
                  </Text>
                </View>
              </View>
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.black,
                  marginHorizontal: windowHeight(2),
                  marginTop: windowHeight(1.7),
                  fontFamily: appFonts.semiBold,
                  textAlign: rtl ? 'right' : 'left',
                  fontSize: fontSizes.FONT3HALF1,
                  width: '100%',
                }}
              >
                {translateData.averageDistances}
              </Text>
            </View>
          </View>

          <View
            style={{
              gap: 5,
              paddingHorizontal: windowWidth(4),
            }}
          >
            <View
              style={{
                height: windowHeight(14),
                width: windowHeight(20),
                borderColor: isDark ? appColors.darkborder : appColors.border,
                borderWidth: windowWidth(0.45),
                borderRadius: windowWidth(5),
                marginTop: windowHeight(2),
                backgroundColor: colors.card,
              }}
            >
              <View style={{ flexDirection: rtl ? 'row-reverse' : 'row' }}>
                <View
                  style={{
                    backgroundColor: appColors.pendingBg,
                    height: windowHeight(6),
                    width: windowHeight(6),
                    borderRadius: windowHeight(0.7),
                    marginTop: windowHeight(2),
                    marginHorizontal: windowHeight(2),
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Image
                    source={Images.mapFrame3}
                    resizeMode="contain"
                    style={{
                      height: windowHeight(4),
                      width: windowHeight(3),
                    }}
                    tintColor={appColors.pending}
                  />
                </View>

                <View>
                  <Text
                    style={{
                      color: appColors.pending,
                      fontFamily: appFonts.bold,
                      fontSize: fontSizes.FONT5,
                      marginTop: windowHeight(3.5),
                    }}
                  >
                    {dashBoardList?.driver_performance?.average_hours}
                  </Text>
                </View>
              </View>
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.black,
                  marginHorizontal: windowHeight(2),
                  marginTop: windowHeight(1.7),
                  fontFamily: appFonts.semiBold,
                  textAlign: rtl ? 'right' : 'left',
                }}
              >
                {translateData.totalHours}
              </Text>
            </View>

            <View
              style={{
                height: windowHeight(24),
                width: windowHeight(20),
                borderColor: isDark ? appColors.darkborder : appColors.border,
                borderWidth: windowWidth(0.45),
                borderRadius: windowWidth(5),
                marginTop: windowHeight(2),
                backgroundColor: colors.card,
              }}
            >
              <View
                style={{
                  flexDirection: rtl ? 'row-reverse' : 'row',
                }}
              >
                <View
                  style={{
                    backgroundColor: appColors.hoursbg,
                    height: windowHeight(6),
                    width: windowHeight(6),
                    borderRadius: windowHeight(0.7),
                    marginTop: windowHeight(2),
                    marginHorizontal: windowHeight(2),
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Image
                    source={Images.mapFrame8}
                    resizeMode="contain"
                    style={{
                      height: windowHeight(4),
                      width: windowHeight(3),
                    }}
                    tintColor={appColors.hours}
                  />
                </View>
                <View>
                  <Text
                    style={{
                      color: appColors.hours,
                      fontFamily: appFonts.bold,
                      fontSize: fontSizes.FONT5HALF,
                      marginTop: windowHeight(3),
                    }}
                  >
                    {dashBoardList?.driver_performance?.average_hours}
                  </Text>
                </View>
              </View>

              <Image
                source={Images.mapFrame7}
                style={{
                  height: windowHeight(10),
                  width: windowHeight(20),
                  alignSelf: 'center',
                  top: windowHeight(0.5),
                }}
              />
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.black,
                  marginHorizontal: windowHeight(2),
                  marginTop: windowHeight(1.7),
                  fontFamily: appFonts.semiBold,
                  textAlign: rtl ? 'right' : 'left',
                }}
              >
                {translateData.averageHours}{' '}
              </Text>
            </View>
          </View>
        </View>
      </View>
    </ScrollView>
  )
}
