import {
  View,
  Text,
  TouchableOpacity,
  TextInput,
  KeyboardAvoidingView,
  Platform,
} from 'react-native'
import React, { useState, useRef, useCallback } from 'react'
import { useRoute, useNavigation } from '@react-navigation/native'
import { Button, Header, Input } from '../../../commonComponents'
import { useValues } from '../../../utils/context'
import { useDispatch, useSelector } from 'react-redux'
import appColors from '../../../theme/appColors'
import {
  windowHeight,
  windowWidth,
  fontSizes,
} from '../../../theme/appConstant'
import appFonts from '../../../theme/appFonts'
import CountrySelect from 'react-native-country-select'
import { ICountry } from 'react-native-country-select/lib/interface/country'
import {
  BottomSheetModal,
  BottomSheetModalProvider,
  BottomSheetView,
} from '@gorhom/bottom-sheet'
import OTPTextInput from 'react-native-otp-textinput'
import { updateMobileEmail, verifyMobileEmail } from '../../../api/store/action'
import { UpdateProfileInterface } from '../../../api/interface/accountInterface'
import { styles } from './styles'

export function EditDetails() {
  const route = useRoute()
  const navigation = useNavigation()
  const { field, formData } = route.params as { field: string; formData: any }
  const { isDark, viewRtlStyle, rtl } = useValues()
  const { translateData } = useSelector((state: any) => state.setting)
  const [phoneNumber, setPhoneNumber] = useState('')
  const [email, setEmail] = useState('')
  const [selectedCountry, setSelectedCountry] = useState<ICountry | null>(null)
  const [countryPickerVisible, setCountryPickerVisible] = useState(false)
  const [otp, setOtp] = useState('')
  const dispatch = useDispatch()

  // Refs for bottom sheets
  const otpBottomSheetRef = useRef<BottomSheetModal>(null)
  const otpInputRef = useRef<OTPTextInput>(null)

  // Function to get the primary calling code
  const getPrimaryCallingCode = useCallback(
    (country: ICountry | null): string => {
      if (!country) return '+1'
      const root = country.idd?.root || '+'
      // Use only the first suffix to avoid issues like +1201 instead of +1
      const suffix = country.idd?.suffixes?.[0] || ''
      return root + suffix
    },
    [],
  )

  const handleCountrySelect = useCallback((country: ICountry) => {
    setSelectedCountry(country)
    setCountryPickerVisible(false)
  }, [])

  const handleVerify = useCallback(() => {
    const payload: UpdateProfileInterface = {
      email: email,
      phone: phoneNumber,
      country_code: (selectedCountry?.idd?.root || '1').replace('+', ''),
    }

    dispatch(updateMobileEmail(payload) as any)
      .unwrap()
      .then((res: any) => {})
      .catch((err: any) => {})
    otpBottomSheetRef.current?.present()
  }, [email, phoneNumber, selectedCountry, dispatch])

  const handleOtpVerify = useCallback(() => {
    const payload: UpdateProfileInterface = {
      token: otp,
      email_or_phone: phoneNumber || email,
    }

    dispatch(verifyMobileEmail(payload) as any)
      .unwrap()
      .then((res: any) => {})
      .catch((err: any) => {})

    otpBottomSheetRef.current?.close()
    navigation.goBack()
  }, [navigation, otp, phoneNumber, email, dispatch])

  const handleOpenCountryPicker = useCallback(() => {
    setCountryPickerVisible(true)
  }, [])

  const handleCloseCountryPicker = useCallback(() => {
    setCountryPickerVisible(false)
  }, [])

  const formatPhoneNumber = useCallback((): string => {
    if (!selectedCountry) return formData?.countryCode
    return getPrimaryCallingCode(selectedCountry)
  }, [selectedCountry, getPrimaryCallingCode])

  return (
    <BottomSheetModalProvider>
      <View
        style={{
          flex: 1,
          backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
        }}
      >
        <Header
          title={`${
            field === 'email'
              ? translateData.email
              : translateData?.mobileNumber
          }`}
          style={
            field === 'email' ? (rtl ? styles.gap : styles.gap) : styles.gap
          }
        />
        <View
          style={{
            paddingHorizontal: windowWidth(2),
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            marginTop: windowHeight(2),
            borderWidth: windowWidth(0.45),
            borderColor: isDark ? appColors.darkborder : appColors.loader,
            borderRadius: windowWidth(5),
            marginHorizontal: windowWidth(2),
          }}
        >
          <Text
            style={{
              color: isDark ? appColors.white : appColors.black,
            }}
          >
            {field === 'mobile'
              ? translateData.updatePhoneNumber
              : translateData.updateEmail}
          </Text>

          {field === 'mobile' ? (
            <View style={{ marginHorizontal: windowWidth(2) }}>
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.primaryFont,
                  marginBottom: windowHeight(1),
                }}
              >
                {translateData.mobileNumber}
              </Text>
              <View
                style={{
                  flexDirection: viewRtlStyle,
                  justifyContent: 'space-between',
                  borderWidth: windowWidth(0.45),
                  borderColor: isDark ? appColors.darkborder : appColors.loader,
                  borderRadius: windowWidth(35),
                  height: windowHeight(6),
                }}
              >
                <TouchableOpacity
                  style={[
                    styles.countryCodeContainer,
                    isDark && styles.darkCountryCodeContainer,
                    {
                      flexDirection: viewRtlStyle,
                      alignItems: 'center',
                      justifyContent: 'center',
                    },
                  ]}
                  onPress={handleOpenCountryPicker}
                >
                  <Text
                    style={[
                      styles.codeText,
                      {
                        color: isDark
                          ? appColors.white
                          : appColors.secondaryFont,
                        fontSize: fontSizes.FONT3,
                      },
                    ]}
                  >
                    {formatPhoneNumber()}
                  </Text>
                </TouchableOpacity>
                <View
                  style={{
                    height: windowHeight(2.2),
                    width: windowWidth(0.25),
                    backgroundColor: isDark
                      ? appColors.darkText
                      : appColors.lightGray,
                    alignSelf: 'center',
                    marginRight: rtl ? 0 : windowWidth(4),
                    marginLeft: rtl ? windowWidth(4) : 0,
                  }}
                />
                <View
                  style={[
                    styles.phoneNumberInput,
                    {
                      width: '80%',
                    },
                  ]}
                >
                  <TextInput
                    style={{
                      left: rtl ? windowWidth(40) : windowWidth(1),
                      color: isDark ? appColors.white : appColors.secondaryFont,
                      width: windowWidth(80),
                      fontFamily: appFonts.regular,
                      fontSize: fontSizes.FONT3,
                    }}
                    placeholderTextColor={
                      isDark ? appColors.darkText : appColors.secondaryFont
                    }
                    placeholder={translateData?.newPhonenumber}
                    keyboardType="phone-pad"
                    value={phoneNumber}
                    onChangeText={setPhoneNumber}
                  />
                </View>
              </View>
            </View>
          ) : (
            // Email Field
            <View style={{ marginHorizontal: windowWidth(2) }}>
              <Input
                title={translateData.email}
                titleShow={true}
                borderColor={isDark ? appColors.darkborder : appColors.loader}
                backgroundColor={
                  isDark ? appColors.primaryFont : appColors.white
                }
                placeholder={translateData?.enternewemail}
                value={email}
                onChangeText={setEmail}
              />
            </View>
          )}

          <View
            style={{
              marginTop: windowHeight(3),
              marginBottom: windowHeight(2),
              marginHorizontal: windowWidth(-2),
            }}
          >
            <Button
              title={translateData.verify}
              onPress={handleVerify}
              backgroundColor={isDark ? appColors.white : appColors.black}
              color={isDark ? appColors.black : appColors.white}
            />
          </View>

          {countryPickerVisible && (
            <CountrySelect
              visible={true}
              onClose={handleCloseCountryPicker}
              onSelect={handleCountrySelect}
              theme={isDark ? 'dark' : 'light'}
              showAlphabetFilter={true}
              showSearchInput={true}
            />
          )}
          <BottomSheetModal
            ref={otpBottomSheetRef}
            snapPoints={[Platform.OS === 'ios' ? '45%' : '41%']}
            handleIndicatorStyle={{
              backgroundColor: appColors.primary,
              height: windowHeight(0.6),
              width: windowWidth(10),
              marginTop: windowHeight(0.2),
            }}
            containerStyle={{ borderRadius: windowWidth(5) }}
            backgroundStyle={{
              backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            }}
          >
            <KeyboardAvoidingView
              style={{ flex: 1 }}
              behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            >
              <BottomSheetView
                style={{
                  padding: windowWidth(2),
                  flex: 1,
                  paddingHorizontal: windowWidth(1),
                }}
              >
                <Text
                  style={{
                    color: isDark ? appColors.white : appColors.primaryFont,
                    marginBottom: windowHeight(1),
                    fontFamily: appFonts.regular,
                    marginHorizontal: windowWidth(5),
                  }}
                >
                  {translateData.otpSendTo || 'Enter the otp sent to'}{' '}
                  {field === 'mobile' ? phoneNumber : email}
                </Text>
                <View
                  style={{
                    flexDirection: 'row',
                    justifyContent: 'center',
                    marginBottom: windowHeight(3),
                  }}
                >
                  <OTPTextInput
                    ref={otpInputRef}
                    inputCount={6}
                    handleTextChange={value => {
                      setOtp(value)
                      if (value.length === 6) {
                      }
                    }}
                    textInputStyle={{
                      width: windowHeight(6),
                      height: windowHeight(6),
                      borderWidth: windowWidth(0.45),
                      borderColor: isDark
                        ? appColors.darkborder
                        : appColors.border,
                      borderRadius: windowHeight(6),
                      backgroundColor: isDark
                        ? appColors.primaryFont
                        : appColors.white,
                      borderBottomWidth: windowWidth(0.45),
                      color: isDark ? appColors.white : appColors.black,
                    }}
                    keyboardType="numeric"
                    tintColor={isDark ? appColors.primary : appColors.primary}
                    offTintColor={
                      isDark ? appColors.darkborder : appColors.lightGray
                    }
                    defaultValue={otp}
                  />
                </View>

                <Button
                  title={translateData.verify}
                  onPress={handleOtpVerify}
                  backgroundColor={isDark ? appColors.white : appColors.black}
                  color={isDark ? appColors.black : appColors.white}
                />
              </BottomSheetView>
            </KeyboardAvoidingView>
          </BottomSheetModal>
        </View>
      </View>
    </BottomSheetModalProvider>
  )
}
