import React, { useCallback, useEffect, useState } from 'react'
import {
  View,
  TouchableOpacity,
  Text,
  TextInput,
  ScrollView,
  BackHandler,
} from 'react-native'
import appColors from '../../../../theme/appColors'
import { ProgressBar } from '../component'
import { Input, Button } from '../../../../commonComponents'
import {
  useFocusEffect,
  useNavigation,
  useTheme,
} from '@react-navigation/native'
import { Header } from '../../component'
import styles from './styles'
import { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { RootStackParamList } from '../../../../navigation/main/types'
import Icons from '../../../../utils/icons/icons'
import { useValues } from '../../../../utils/context'
import { useDispatch, useSelector } from 'react-redux'
import { useAppRoute } from '../../../../utils/navigation'
import { ValidatePhoneNumber } from '../../../../utils/validation'
import {
  fontSizes,
  windowHeight,
  windowWidth,
} from '../../../../theme/appConstant'
import CountryPicker from 'react-native-country-picker-modal'
import { AppDispatch } from '../../../../api/store'
import { countryData, preferenceData } from '../../../../api/store/action'
import DropDownPicker from 'react-native-dropdown-picker'

type navigation = NativeStackNavigationProp<RootStackParamList>

export function CreateAccount() {
  const navigation = useNavigation<navigation>()
  const [showWarning, setShowWarning] = useState<boolean>(false)
  const [emailFormatWarning, setEmailFormatWarning] = useState<string>('')
  const { colors } = useTheme()
  const { textRtlStyle, viewRtlStyle, isDark, setAccountDetail, rtl } =
    useValues()
  const [phoneNumber, setPhoneNumber] = useState<string>('')
  const [isPasswordVisible, setIsPasswordVisible] = useState<boolean>(false)
  const [isConfirmPasswordVisible, setIsConfirmPasswordVisible] =
    useState<boolean>(false)
  const { translateData } = useSelector((state: any) => state.setting)
  const route = useAppRoute()
  const usercredential = route.params?.phoneNumber ?? '1234567890'
  const rawCode = route.params?.countryCode ?? '91'
  const cleanCode = rawCode.replace('+', '')
  const [countryCode, setCountryCode] = useState({
    callingCode: [cleanCode],
    cca2: route?.params?.cca2 ?? 'US',
  })
  const [email, setEmail] = useState('')
  const [referral, setReferral] = useState<string>('')
  const [isEmailUser, setIsEmailUser] = useState(false)
  const dispatch = useDispatch<AppDispatch>()
  const { countryList } = useSelector((state: any) => state.account)
  const [open, setOpen] = useState(false)
  const [value, setValue] = useState<string | null>(null)
  const [items, setItems] = useState<any[]>([])
  const [countryError, setCountryError] = useState<string>('')

  useEffect(() => {
    dispatch(countryData())
    dispatch(preferenceData()).then(res => { })
  }, [])

  useFocusEffect(
    useCallback(() => {
      setShowWarning(false)
      setEmailFormatWarning('')
      setError({
        username: '',
        name: '',
        phoneNumber: '',
        email: '',
        password: '',
        confirmPassword: '',
        countryCode: countryCode,
      })
    }, []),
  )

  useEffect(() => {
    const emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/
    const isEmail = emailRegex.test(usercredential.trim())
    setIsEmailUser(isEmail)

    if (isEmail) {
      setEmail(usercredential.trim())
    } else {
      setPhoneNumber(usercredential.trim())
    }
  }, [usercredential])

  const [formData, setFormData] = useState({
    username: '',
    name: '',
    phoneNumber: '',
    email: '',
    password: '',
    confirmPassword: '',
    countryCode: countryCode,
    referral: '',
  })

  const [error, setError] = useState<any>({
    username: '',
    name: '',
    phoneNumber: '',
    email: '',
    password: '',
    confirmPassword: '',
    countryCode: countryCode,
  })

  useEffect(() => {
    const emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/
    const isEmail = emailRegex.test(usercredential.trim())
    if (isEmail) {
      const cleanEmail = usercredential.trim()
      setEmail(cleanEmail)
      setFormData(prev => ({ ...prev, email: cleanEmail }))
    } else {
      const cleanPhone = usercredential.trim()
      setPhoneNumber(cleanPhone)
      setFormData(prev => ({ ...prev, phoneNumber: cleanPhone }))
    }
  }, [usercredential])

  const handleChange = (key: string, value: string) => {
    if (key === 'phoneNumber') {
      setFormData(prev => ({
        ...prev,
        [key]: numericValue,
      }))
    } else {
      setFormData(prev => ({
        ...prev,
        [key]: value,
      }))
    }

    if (key === 'email') {
      setEmail(value)
      setEmailFormatWarning('')
    }
  }

  const gotoDocument = () => {
    const name = formData.name.trim()
    const phone = formData.phoneNumber.trim()
    const emailValue = formData.email.trim()
    const newErrors: any = {
      phoneNumber: '',
      email: '',
      password: '',
      confirmPassword: '',
    }
    let hasError = false
    if (!value) {
      // <-- value is dropdown selection
      setCountryError(translateData?.selectCountryError) // or use translateData
      hasError = true
    } else {
      setCountryError('')
    }

    const phoneError = ValidatePhoneNumber(phone)
    if (isEmailUser && phoneError) {
      newErrors.phoneNumber = phoneError
      hasError = true
    }

    if (name === '') {
      newErrors.name = translateData.pleaseEnterYourName
      hasError = true
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!isEmailUser && emailValue === '') {
      newErrors.email = translateData.emailVerifyyyyy
      hasError = true
    } else if (!isEmailUser && !emailRegex.test(emailValue)) {
      newErrors.email = translateData.emailformateteee
      hasError = true
    }

    if (formData.password.trim() === '') {
      newErrors.password = translateData.password
      hasError = true
    }
    if (formData.confirmPassword.trim() === '') {
      newErrors.confirmPassword = translateData.confirmPassword
      hasError = true
    }

    if (
      formData.password &&
      formData.confirmPassword &&
      formData.password !== formData.confirmPassword
    ) {
      newErrors.confirmPassword = translateData.doNotMatch
      hasError = true
    }

    if (hasError) {
      setError(newErrors)
      setShowWarning(true)
      return
    }

    setError({ phoneNumber: '', email: '', password: '', confirmPassword: '' })
    setShowWarning(false)
    setAccountDetail(formData)
    navigation.navigate('UploadedDocument')
  }

  const [visible, setVisible] = useState(false)
  const onSelect = (country: any) => {
    setCountryCode(country)
    setVisible(false)
  }

  useEffect(() => {
    const backAction = () => {
      navigation.navigate('Login')
      return true
    }

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

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

  useEffect(() => {
    const formatted = countryList?.data?.map((item: any) => ({
      label: `${item.name}`,
      value: item.calling_code,
    }))
    setItems(formatted)
  }, [countryList])

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
      }}
    >
      <View
        style={{
          backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          height: windowHeight(11.5),
          borderBottomEndRadius: windowWidth(4),
          borderBottomStartRadius: windowWidth(4),
          elevation: 1,
        }}
      >
        <Header
          backgroundColor={isDark ? appColors.primaryFont : appColors.white}
        />
        <ProgressBar fill={1} />
      </View>
      <ScrollView
        style={[
          styles.subView,
          { backgroundColor: isDark ? appColors.bgDark : appColors.lightGray },
        ]}
        showsVerticalScrollIndicator={false}
      >
        <View
          style={[
            styles.space,
            {
              backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            },
          ]}
        >
          <Text
            style={[
              styles.main1,
              {
                color: isDark ? appColors.white : appColors.subFont,
              },
            ]}
          >
            {translateData.createAccount}
          </Text>
          <Text style={[styles.sub]}>{translateData.registerContent}</Text>

          <View style={styles.name}>
            <Input
              title={translateData.name}
              titleShow={true}
              placeholder={translateData.enterYourName}
              value={formData.name}
              onChangeText={text => handleChange('name', text)}
              showWarning={showWarning && formData.name === ''}
              warning={translateData.pleaseEnterYourName}
              backgroundColor={isDark ? appColors.primaryFont : appColors.white}
              borderColor={isDark ? appColors.darkborder : appColors.loader}
            />
          </View>
          <Text
            style={[
              styles.mobileNumber,
              {
                color: isDark ? appColors.white : appColors.primaryFont,

                textAlign: textRtlStyle,
              },
            ]}
          >
            {translateData.mobileNumber}
          </Text>

          <View style={styles.country}>
            <View
              style={[
                styles.input,
                {
                  flexDirection: viewRtlStyle,
                  backgroundColor: isDark
                    ? appColors.primaryFont
                    : appColors.white,
                  borderColor: isDark ? appColors.darkborder : appColors.loader,
                },
              ]}
            >
              <View
                style={[
                  styles.codeComponent,
                  { right: rtl ? windowWidth(3) : windowWidth(0.5) },
                ]}
              >
                <TouchableOpacity style={[styles.countryCode]}>
                  <TouchableOpacity
                    style={styles.pickerButton}
                    onPress={() => setVisible(true)}
                    disabled={!isEmailUser}
                    activeOpacity={0.9}
                  >
                    <CountryPicker
                      countryCode={countryCode.cca2}
                      withFilter={true}
                      withFlag={false}
                      withCallingCode={true}
                      withAlphaFilter={true}
                      withEmoji={true}
                      onSelect={onSelect}
                      visible={visible}
                      withFlagButton={false}
                    />

                    <Text
                      style={[
                        styles.codeText,
                        { color: isDark ? appColors.white : appColors.black },
                      ]}
                    >
                      +{countryCode.callingCode[0]}
                    </Text>
                  </TouchableOpacity>
                </TouchableOpacity>
              </View>
              <View
                style={[
                  styles.divison,
                  {
                    marginLeft: rtl ? windowWidth(4) : windowWidth(-1),
                    marginRight: rtl ? windowWidth(-1) : windowWidth(4),
                    backgroundColor: isDark
                      ? appColors.darkborder
                      : appColors.loader,
                  },
                ]}
              />
              <View
                style={[
                  styles.phone,
                  {
                    backgroundColor: colors.card,
                    borderColor: colors.border,
                    flexDirection: viewRtlStyle,
                  },
                ]}
              >
                <TextInput
                  editable={isEmailUser}
                  placeholder={translateData.enterPhone}
                  placeholderTextColor={
                    isDark ? appColors.darkText : appColors.secondaryFont
                  }
                  value={phoneNumber}
                  onChangeText={text => {
                    const phoneNoError = ValidatePhoneNumber(text)
                    // setError(phoneNoError)

                    setPhoneNumber(text)
                    setFormData(prev => ({
                      ...prev,
                      phoneNumber: text,
                    }))
                  }}
                  keyboardType="phone-pad"
                  style={[
                    styles.number,
                    { color: isDark ? appColors.white : appColors.black },
                    { textAlign: rtl ? 'right' : 'left' },
                  ]}
                />
              </View>
            </View>

            {isEmailUser && error.phoneNumber ? (
              <Text style={[styles.errorText, { textAlign: textRtlStyle }]}>
                {error.phoneNumber}
              </Text>
            ) : null}
          </View>

          <Text
            style={[
              styles.mobileNumber,
              {
                color: isDark ? appColors.white : appColors.primaryFont,

                textAlign: textRtlStyle,
                marginBottom: windowHeight(0.5),
                marginTop: windowHeight(2),
              },
            ]}
          >
            {translateData?.Country}
          </Text>
          <DropDownPicker
            open={open}
            value={value}
            items={items}
            setOpen={setOpen}
            setValue={setValue}
            setItems={setItems}
            searchable={true}
            searchPlaceholder={translateData?.searchCountry || 'Search country'}
            searchTextInputStyle={{
              borderColor: colors.border,
              color: isDark ? appColors.white : appColors.black,
              backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            }}
            searchContainerStyle={{
              borderBottomColor: colors.border,
            }}
            searchPlaceholderTextColor={
              isDark ? appColors.darkText : appColors.secondaryFont
            }
            placeholder={translateData?.selectCountry}
            placeholderStyle={{ color: appColors.iconColor }}
            containerStyle={styles.container}
            style={{
              backgroundColor: isDark ? appColors.primaryFont : appColors.white,
              borderColor: colors.border,
              flexDirection: viewRtlStyle,
              paddingHorizontal: windowHeight(1.9),
              borderRadius: open ? windowWidth(5) : windowWidth(18),
            }}
            dropDownContainerStyle={{
              backgroundColor: isDark ? colors.card : appColors.dropDownColor,
              borderColor: colors.border,
            }}
            textStyle={{
              textAlign: rtl ? 'right' : 'left',
              fontSize: fontSizes.FONT4,
              color: colors.text,
            }}
            listItemLabelStyle={{
              color: isDark ? appColors.white : appColors.black,
            }}
            arrowIconStyle={{
              tintColor: isDark ? appColors.iconColor : appColors.iconColor,
            }}
            tickIconStyle={{
              tintColor: isDark ? appColors.white : appColors.black,
            }}
            listMode="SCROLLVIEW"
            dropDownDirection="AUTO"
            zIndex={2}
          />

          {countryError !== '' && (
            <Text style={[styles.errorText, { textAlign: textRtlStyle }]}>
              {countryError}
            </Text>
          )}

          <View style={styles.email}>
            <Input
              editable={!isEmailUser}
              title={translateData.email}
              titleShow={true}
              placeholder={translateData.enterEmail}
              keyboardType="email-address"
              autoCapitalize="none"
              value={email}
              onChangeText={text => {
                setEmail(text)
                handleChange('email', text)
              }}
              backgroundColor={
                !isEmailUser
                  ? isDark
                    ? appColors.primaryFont
                    : appColors.white
                  : appColors.white
              }
              showWarning={!!error.email}
              warning={error.email}
              borderColor={colors.border}
            />
          </View>
          <View style={{ bottom: windowHeight(0.8) }}>
            {!isEmailUser && emailFormatWarning !== '' && (
              <Text style={[styles.errorText, { textAlign: textRtlStyle }]}>
                {emailFormatWarning}
              </Text>
            )}
          </View>

          <Input
            title={translateData.createaccount}
            titleShow={true}
            placeholder={translateData.password}
            value={formData.password}
            warning={
              showWarning && formData.password === ''
                ? translateData.password
                : formData.password.length > 0 && formData.password.length < 8
                  ? translateData.passwordMinLength
                  : ''
            }
            onChangeText={text => handleChange('password', text)}
            showWarning={
              showWarning &&
              (formData.password === '' || formData.password.length < 8)
            }
            backgroundColor={isDark ? appColors.primaryFont : appColors.white}
            borderColor={colors.border}
            rightIcon={
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => setIsPasswordVisible(!isPasswordVisible)}
              >
                {isPasswordVisible ? <Icons.EyeOpen /> : <Icons.EyeClose />}
              </TouchableOpacity>
            }
            secureText={!isPasswordVisible}
            style={rtl ? styles.view : null}
          />

          <View style={styles.password}>
            <Input
              title={translateData.cPw}
              titleShow={true}
              placeholder={translateData.confirmPassword}
              value={formData.confirmPassword}
              onChangeText={text => handleChange('confirmPassword', text)}
              showWarning={!!error.confirmPassword}
              warning={error.confirmPassword}
              backgroundColor={isDark ? appColors.primaryFont : appColors.white}
              borderColor={colors.border}
              rightIcon={
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() =>
                    setIsConfirmPasswordVisible(!isConfirmPasswordVisible)
                  }
                >
                  {isConfirmPasswordVisible ? (
                    <Icons.EyeOpen />
                  ) : (
                    <Icons.EyeClose />
                  )}
                </TouchableOpacity>
              }
              secureText={!isConfirmPasswordVisible}
              style={rtl ? styles.view : null}
            />
          </View>
          <View style={styles.password}>
            <Input
              optional={true}
              title={translateData?.referralID}
              placeholder={translateData?.referralaidenter}
              titleShow={true}
              keyboardType="email-address"
              autoCapitalize="none"
              value={referral}
              onChangeText={text => {
                setReferral(text)
                handleChange('referral', text)
              }}
              backgroundColor={
                !isEmailUser
                  ? isDark
                    ? appColors.primaryFont
                    : appColors.white
                  : appColors.white
              }
              borderColor={colors.border}
            />
          </View>
        </View>

        <View style={styles.margin}>
          <Button
            onPress={gotoDocument}
            title={translateData.next}
            backgroundColor={isDark ? appColors.white : appColors.black}
            color={isDark ? appColors.black : appColors.white}
          />
        </View>
      </ScrollView>
    </View>
  )
}
