import React, { useEffect, useState } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  FlatList,
  BackHandler,
} from 'react-native'
import { Header } from '../../../commonComponents'
import appColors from '../../../theme/appColors'
import { useNavigation, useTheme } from '@react-navigation/native'
import { useSelector } from 'react-redux'
import {
  fontSizes,
  windowHeight,
  windowWidth,
} from '../../../theme/appConstant'
import { useValues } from '../../../utils/context'
import styles from './styles'
import Icons from '../../../utils/icons/icons'
import appFonts from '../../../theme/appFonts'

export function Subscription() {
  const { colors } = useTheme()
  const { isDark } = useValues()
  const { planData, translateData } = useSelector((state: any) => state.setting)
  const { zoneValue } = useSelector((state: any) => state.zoneUpdate)
  const navigation = useNavigation<any>()

  const [selectedPlan, setSelectedPlan] = useState<any>(null)

  const sortedPlans = [...(planData?.data || [])].sort(
    (a, b) => a.price - b.price,
  )

  useEffect(() => {
    if (sortedPlans.length > 0 && !selectedPlan) {
      setSelectedPlan(sortedPlans[0])
    }
  }, [sortedPlans])

  const gotopayment = () => {
    if (selectedPlan) {
      navigation.navigate('PaymentSelect', { planId: selectedPlan.id })
    }
  }

  useEffect(() => {
    const backAction = () => {
      if (navigation.canGoBack()) {
        navigation.goBack()
        return true
      }
      return false
    }
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    )
    return () => backHandler.remove()
  }, [navigation])

  const renderPlanItem = ({ item }: any) => {
    const isSelected = selectedPlan?.id === item.id

    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => setSelectedPlan(item)}
        style={{
          borderRadius: 16,
          marginHorizontal: 6,
          backgroundColor: isSelected
            ? isDark
              ? appColors.white
              : appColors.black
            : isDark
              ? appColors.primaryFont
              : appColors.white,
          paddingVertical: windowHeight(2.2),
          alignItems: 'center',
          borderWidth: windowWidth(0.45),
          borderColor: isSelected
            ? appColors.black
            : isDark
              ? appColors.darkborder
              : appColors.loader,
          height: windowHeight(12),
          paddingHorizontal: windowWidth(4),
          width: windowWidth(35),
          justifyContent: 'center',
        }}
      >
        <Text
          style={{
            color: isSelected
              ? isDark
                ? appColors.black
                : appColors.white
              : colors.text,
            marginTop: windowHeight(0.45),
            fontSize: fontSizes.FONT5,
            textAlign: 'center',
            fontFamily: appFonts.semiBold,
          }}
        >
          {zoneValue?.currency_symbol}
          {zoneValue?.exchange_rate * Math.floor(item.price)}
          <Text
            style={{
              fontSize: fontSizes.FONT3HALF,
              fontFamily: appFonts.regular,
              color: appColors.iconColor,
            }}
          >
            {translateData?.perMonth}
          </Text>
        </Text>

        <Text
          style={{
            color: '#4CAF50',
            marginTop: windowHeight(0.45),
            fontSize: fontSizes.FONT3HALF,
            textAlign: 'center',
            fontFamily: appFonts.regular,
          }}
        >
          {item.name?.toUpperCase()}
        </Text>
      </TouchableOpacity>
    )
  }

  return (
    <View
      style={[
        styles.MainContainer,
        { backgroundColor: colors.background, flex: 1 },
      ]}
    >
      <Header title={translateData.planDetails} style={styles.gap} />

      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingBottom: windowHeight(16) }}
      >
        <Text style={[styles.planTitle, { color: colors.text }]}>
          {translateData?.subscriptionTitle}
        </Text>

        {sortedPlans.length > 0 ? (
          <>
            <View style={{ height: windowHeight(60) }}>
              <View style={{ height: windowHeight(35) }}>
                <View
                  style={{
                    backgroundColor: isDark
                      ? appColors.primaryFont
                      : appColors.white,
                    maxHeight: windowHeight(30),
                    paddingVertical: windowHeight(3),
                    width: '90%',
                    alignSelf: 'center',
                    marginTop: windowHeight(2),
                    borderRadius: windowWidth(5),
                    borderWidth: windowWidth(0.45),
                    borderColor: colors.border,
                  }}
                >
                  {selectedPlan?.description?.map(
                    (feature: string, index: number) => (
                      <View
                        key={index}
                        style={{
                          flexDirection: 'row',
                          alignItems: 'center',
                          marginBottom: windowHeight(0.5),
                          marginHorizontal: windowWidth(4),
                        }}
                      >
                        <Icons.ShildTik
                          background={appColors.primary}
                          tik={appColors.white}
                        />
                        <Text
                          style={{
                            color: colors.text,
                            marginHorizontal: windowWidth(3),
                            width: '90%',
                          }}
                        >
                          {feature}
                        </Text>
                      </View>
                    ),
                  )}

                  <View
                    style={[
                      styles.line,
                      { backgroundColor: colors.background },
                    ]}
                  />

                  <Text
                    style={{
                      color: colors.text,
                      fontSize: 13,
                      opacity: 0.7,
                      marginTop: windowHeight(0.45),
                      marginHorizontal: windowWidth(4),
                    }}
                  >
                    {translateData.subNote}
                  </Text>
                </View>
              </View>

              <FlatList
                data={sortedPlans}
                renderItem={renderPlanItem}
                horizontal
                keyExtractor={item => item.id.toString()}
                showsHorizontalScrollIndicator={false}
                contentContainerStyle={{ paddingHorizontal: windowWidth(3) }}
              />
            </View>

            <TouchableOpacity
              activeOpacity={0.8}
              disabled={!selectedPlan}
              onPress={gotopayment}
              style={{
                backgroundColor: selectedPlan
                  ? isDark
                    ? appColors.white
                    : appColors.black
                  : appColors.gray,
                alignItems: 'center',
                marginHorizontal: windowWidth(4),
                marginTop: windowHeight(2),
                height: windowHeight(6),
                borderRadius: windowWidth(25),
                justifyContent: 'center',
              }}
            >
              <Text
                style={{
                  color: isDark ? appColors.black : appColors.white,
                  fontSize: fontSizes.FONT4,
                  fontFamily: appFonts.medium,
                }}
              >
                {translateData?.continue}
              </Text>
            </TouchableOpacity>
          </>
        ) : (
          <View
            style={{
              alignItems: 'center',
              justifyContent: 'center',
              height: windowHeight(50),
            }}
          >
            <Text style={{ color: colors.text, fontSize: 16, opacity: 0.7 }}>
              {translateData?.noPlanData || 'No plan data available'}
            </Text>
          </View>
        )}
      </ScrollView>

      <View
        style={[
          styles.noteContainer,
          {
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            position: 'absolute',
            bottom: 0,
            width: '100%',
            paddingVertical: windowHeight(1.5),
            paddingHorizontal: windowWidth(4),
          },
        ]}
      >
        <Text style={[styles.note, { color: appColors.iconColor }]}>
          {translateData.subscriptionNote}
        </Text>
      </View>
    </View>
  )
}
