import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  Share,
  Image,
  FlatList,
} from 'react-native'
import React, { useEffect } from 'react'
import {
  fontSizes,
  windowHeight,
  windowWidth,
} from '../../../../theme/appConstant'
import appFonts from '../../../../theme/appFonts'
import appColors from '../../../../theme/appColors'
import Images from '../../../../utils/images/images'
import { useDispatch, useSelector } from 'react-redux'
import { useAppNavigation } from '../../../../utils/navigation'
import { useValues } from '../../../../utils/context'
import Clipboard from '@react-native-clipboard/clipboard'
import Icons from '../../../../utils/icons/icons'
import { Header } from '../../../../commonComponents'
import styles from './styles'
import { referralData } from '../../../../api/store/action'
import { useTheme } from '@react-navigation/native'
import { AppDispatch } from '../../../../api/store'

export function ReferralHome() {
  const { viewRtlStyle, isDark, rtl } = useValues()
  const { selfDriver } = useSelector((state: any) => state.account)
  const { taxidoSettingData, translateData } = useSelector(
    (state: any) => state.setting,
  )
  const { navigate }: any = useAppNavigation()
  const dispatch = useDispatch<AppDispatch>()
  const { colors } = useTheme()

  const Workdata = [
    { data: `${translateData.referralTerm1}` },
    {
      data: `${translateData.referralEarn} ${taxidoSettingData?.cabbooking_values?.referral?.referrer_bonus_percentage}% ${translateData.referralTerm2}`,
    },
    { data: `${translateData.referralTerm3}` },
  ]

  const gotoList = () => {
    dispatch(referralData())
      .unwrap()
      .then(res => { })
    navigate('ReferralList')
  }

  useEffect(() => {
    dispatch(referralData())
      .unwrap()
      .then(res => { })
  }, [])

  const handleShareReferral = async () => {
    try {
      const referralCode = selfDriver?.referral_code
      const message = `${translateData.referralShare1} *${referralCode}* ${translateData.referralShare2}\n\n ${translateData.referralShare3}\n👉 https://play.google.com/store/apps/details?id=com.taxidouserui&hl=en_IN`

      await Share.share({
        message,
        title: 'Invite to Gocab',
      })
    } catch (error) {
      console.error('❌ Error sharing referral:', error)
    }
  }
  const { referralList } = useSelector((state: any) => state.refer)

  const referralData1 = referralList?.data?.data || []

  const renderItem = ({ item }: any) => {
    const referredUser = item?.referred || {}
    const status = item?.status || ''
    const isPending = status === 'pending'

    const statusColor = isPending ? '#FFB400' : '#28A745'
    const bgColor = isPending ? '#FFF7E5' : '#E8F4F1'
    return (
      <View
        style={[
          styles.itemContainer,
          {
            backgroundColor: isDark ? appColors.bgDark : appColors.white,
            borderColor: isDark ? appColors.darkborder : appColors.border,
          },
        ]}
      >
        {!item?.referred?.profile_image_url ? (
          <View
            style={[
              styles.userImage1,
              { backgroundColor: isDark ? appColors.white : appColors.black },
            ]}
          >
            <Text
              style={[
                styles.nameText,
                {
                  fontSize: fontSizes.FONT5,
                  color: isDark ? appColors.black : appColors.white,
                },
              ]}
            >
              {referredUser?.name?.charAt(0)?.toUpperCase()}
            </Text>
          </View>
        ) : (
          <Image
            source={{ uri: item?.referred?.profile_image_url }}
            style={styles.userImage}
            resizeMode="cover"
          />
        )}

        <View style={styles.textContainer}>
          <View>
            <Text
              style={[
                styles.nameText,
                { color: isDark ? appColors.white : appColors.black },
              ]}
            >
              {referredUser?.name || translateData.unknownUser}
            </Text>
            <Text
              style={[
                styles.nameText,
                { color: isDark ? appColors.white : appColors.black },
              ]}
            >
              {referredUser?.email}
            </Text>
          </View>
          {item?.referrer_bonus_amount > 0 && (
            <Text style={styles.amountText}>
              +{item?.referrer_bonus_amount}
            </Text>
          )}{' '}
        </View>

        <View
          style={[
            styles.statusContainer,
            {
              backgroundColor: bgColor,
              paddingHorizontal: windowWidth(5),
              paddingVertical: windowHeight(1),
              borderRadius: windowHeight(7),
            },
          ]}
        >
          <Text style={[styles.statusText, { color: statusColor }]}>
            {status.charAt(0).toUpperCase() + status.slice(1)}
          </Text>
        </View>
      </View>
    )
  }

  return (
    <View style={{ flex: 1 }}>
      <View
        style={{
          backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
          flex: 1,
        }}
      >
        <Header title={translateData.referralHeader} style={styles.gap} />

        <ScrollView
          contentContainerStyle={{
            paddingBottom: windowHeight(5),
            paddingTop: windowHeight(0.8),
          }}
        >
          <View
            style={[
              styles.box1,
              {
                backgroundColor: isDark
                  ? appColors.primaryFont
                  : appColors.black,
              },
            ]}
          >
            <View style={styles.position}>
              <View
                style={{
                  flexDirection: viewRtlStyle,
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}
              >
                <View>
                  <Text
                    style={{
                      fontFamily: appFonts.medium,
                      fontSize: fontSizes.FONT4,
                      color: isDark ? appColors.white : appColors.white,
                      marginBottom: windowHeight(1),
                    }}
                  >
                    {translateData?.invitefrd}
                  </Text>
                  <Text style={[styles.des]}>
                    {translateData.referralEarn}{' '}
                    <Text
                      style={[
                        {
                          fontFamily: appFonts.medium,
                          color: appColors.iconColor,
                        },
                      ]}
                    >
                      {
                        taxidoSettingData?.cabbooking_values?.referral
                          ?.referral_amount
                      }
                    </Text>{' '}
                    {translateData.referralFirst}
                  </Text>
                  <TouchableOpacity
                    activeOpacity={0.7}
                    style={[styles.button, { flexDirection: viewRtlStyle }]}
                    onPress={() => {
                      Clipboard.setString(selfDriver?.referral_code || '')
                    }}
                  >
                    <Icons.Copy color={appColors.black} />
                    <Text style={styles.buttonText}>
                      {selfDriver?.referral_code}
                    </Text>
                  </TouchableOpacity>
                </View>
                <Image source={Images.referral} style={styles.image} />
              </View>
            </View>
          </View>

          <View
            style={[
              styles.box,
              {
                borderColor: isDark
                  ? appColors.darkBorderBlack
                  : appColors.loader,
              },
              {
                backgroundColor: isDark ? appColors.bgDark : appColors.white,
              },
            ]}
          >
            <View
              style={[
                {
                  flexDirection: viewRtlStyle,
                  marginHorizontal: windowWidth(4),
                },
                {
                  justifyContent: 'space-between',
                  alignItems: 'center',
                },
              ]}
            >
              <Text
                style={[
                  styles.que,
                  { color: isDark ? appColors.white : appColors.black },
                ]}
              >
                {translateData.referralWork}
              </Text>
              <Text style={[styles.trems]}>{translateData.referralTC}</Text>
            </View>

            <View
              style={{
                marginHorizontal: windowWidth(5),
                marginVertical: windowHeight(1),
              }}
            >
              {Workdata.map((item, id) => (
                <View
                  key={id}
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    marginVertical: windowHeight(0.2),
                  }}
                >
                  <Text
                    style={{
                      fontFamily: appFonts.medium,
                      color: appColors.iconColor,
                      marginRight: rtl ? 0 : 8,
                      marginLeft: rtl ? 8 : 0,
                    }}
                  >
                    {id + 1}.
                  </Text>
                  <Text
                    style={{
                      fontFamily: appFonts.medium,
                      fontSize: fontSizes.FONT3HALF,
                      color: appColors.iconColor,
                    }}
                  >
                    {item.data}
                  </Text>
                </View>
              ))}
            </View>

            <View
              style={[styles.line, { backgroundColor: colors.background }]}
            />
            <Text style={styles.note}>
              <Text style={{ fontFamily: appFonts.bold }}>
                {translateData.referralNote}{' '}
              </Text>
              {translateData.referralNoteData}
            </Text>
          </View>
          <View
            style={{
              flexDirection: viewRtlStyle,
              alignItems: 'center',
              justifyContent: 'space-between',
              marginVertical: windowHeight(3),
              marginHorizontal: windowWidth(5),
              marginBottom: 0,
            }}
          >
            <Text
              style={{
                fontFamily: appFonts.semiBold,
                fontSize: windowWidth(4.3),
                color: isDark ? appColors.white : appColors.black,
              }}
            >
              {translateData?.yourreferral}
            </Text>
            {referralData1.length >= 3 && (
              <TouchableOpacity style={styles.viewButton} onPress={gotoList}>
                <Text style={styles.text}>{translateData.referralViewAll}</Text>
              </TouchableOpacity>
            )}
          </View>

          <FlatList
            data={referralData1.slice(0, 3)}
            keyExtractor={item => item.id?.toString()}
            renderItem={renderItem}
            contentContainerStyle={{ padding: windowHeight(2) }}
            ItemSeparatorComponent={() => (
              <View style={{ marginVertical: windowHeight(1) }} />
            )}
            ListEmptyComponent={
              <View
                style={{
                  alignItems: 'center',
                  flex: 1,
                  justifyContent: 'center',
                  marginTop: windowHeight(5),
                  marginHorizontal: windowWidth(2),
                }}
              >
                <Image
                  source={
                    isDark ? Images.emptyDriverListDark : Images.emptyDriverList
                  }
                  style={{
                    height: windowHeight(45),
                    width: windowWidth(85),
                    resizeMode: 'contain',
                  }}
                />
                <Text
                  style={{
                    fontFamily: appFonts.bold,
                    fontSize: fontSizes.FONT4HALF,
                    color: isDark ? appColors.white : appColors.black,
                  }}
                >
                  {translateData.noReferralList}{' '}
                </Text>
                <Text
                  style={{
                    fontFamily: appFonts.regular,
                    color: appColors.secondaryFont,
                    textAlign: 'center',
                    marginTop: windowHeight(1.2),
                  }}
                >
                  {translateData.noReferralDetail}
                </Text>
              </View>
            }
          />
        </ScrollView>

        <TouchableOpacity
          onPress={handleShareReferral}
          style={{
            backgroundColor: isDark ? appColors.white : appColors.black,
            paddingVertical: 15,
            alignItems: 'center',
            justifyContent: 'center',
            borderRadius: 58,
            margin: 15,
          }}
        >
          <Text
            style={{
              color: isDark ? appColors.black : appColors.white,
              fontFamily: appFonts.medium,
              fontSize: fontSizes.FONT4,
            }}
          >
            {translateData.referralShare}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  )
}
