import { View, Text, TouchableOpacity, TextInput } from 'react-native'
import React, { useCallback, useEffect, useState } from 'react'
import appColors from '../../../../../theme/appColors'
import styles from './styles'
import { Button } from '../../../../../commonComponents'
import LoginViewProps from '../../types'
import { useFocusEffect } from '@react-navigation/native'
import { useValues } from '../../../../../utils/context'
import { useDispatch, useSelector } from 'react-redux'
import { AppDispatch } from '../../../../../api/store'
import { windowHeight, windowWidth } from '../../../../../theme/appConstant'
import { AuthTitle } from '../authtitle'
import {
  taxidosettingDataGet,
  translateDataGet,
} from '../../../../../api/store/action'
import {
  validateEmail,
  ValidatePhoneNumber,
} from '../../../../../utils/validation'
import CountryPicker, {
  getAllCountries,
} from 'react-native-country-picker-modal'

export function LoginView({
  gotoOTP,
  phoneNumber,
  setPhoneNumber,
  setCountryCode,
  borderColor,
  setCca2,
  driverLoading,
  setDriverLoading,
  smsGateway,
  fleetLoading,
  setFleetLoading,
  gotoOTPFleet,
}: LoginViewProps) {
  const [error, setError] = useState<string>('')
  const { textRtlStyle, viewRtlStyle, isDark, rtl } = useValues()
  const dispatch = useDispatch<AppDispatch>()
  const { translateData, taxidoSettingData } = useSelector(
    (state: any) => state.setting,
  )
  const [numberShow, setNumberShow] = useState(true)
  const [country, setCountry] = useState<any>({
    callingCode: [
      `${taxidoSettingData?.cabbooking_values?.ride?.country_code || ''}`,
    ],
    cca2: '',
    emoji: '',
  })
  const [isSelected, setIsSelected] = useState('driver')

  useEffect(() => {
    const fetchCountryFromCode = async () => {
      const code = taxidoSettingData?.cabbooking_values?.ride?.country_code

      if (code) {
        try {
          const countries = await getAllCountries()
          const match = countries.find(c =>
            c.callingCode.includes(code.toString()),
          )

          if (match) {
            setCountry({
              callingCode: [code.toString()],
              cca2: match.cca2,
              emoji: '',
            })
          }
        } catch (err) { }
      }
    }

    fetchCountryFromCode()
  }, [taxidoSettingData?.cabbooking_values?.ride?.country_code])

  useFocusEffect(
    useCallback(() => {
      dispatch(translateDataGet()).then(re => { })
      dispatch(taxidosettingDataGet())
    }, [dispatch]),
  )

  const handlePhoneNumberChange = (newPhoneNumber: string) => {
    if (smsGateway === 'firebase') {
      const onlyNumbers = newPhoneNumber.replace(/[^0-9]/g, '')
      setPhoneNumber(onlyNumbers)
      setNumberShow(true)
      return
    }

    setPhoneNumber(newPhoneNumber)

    const isNumeric = /^\d+$/.test(newPhoneNumber)
    setNumberShow(isNumeric)
  }

  const handleGetOTP = async (userType: string) => {
    setDriverLoading(true)
    const isNumeric = /^\d+$/.test(phoneNumber)

    if (isNumeric) {
      const errorMsg = ValidatePhoneNumber(phoneNumber)
      if (errorMsg) {
        setError(errorMsg)
        setDriverLoading(false)
        return
      }
    } else if (phoneNumber.includes('@')) {
      const errorMsg = validateEmail(phoneNumber)
      if (errorMsg) {
        setError(errorMsg)
        setDriverLoading(false)
        return
      }
    } else {
      setError(translateData.validPhoneEmail)
      setDriverLoading(false)
      return
    }

    setError('')
    try {
      await gotoOTP(userType)
    } catch (error) { }
  }

  const handleGetOTPFleet = async (userType: string) => {
    setFleetLoading(true)
    const isNumeric = /^\d+$/.test(phoneNumber)

    if (isNumeric) {
      const errorMsg = ValidatePhoneNumber(phoneNumber)
      if (errorMsg) {
        setError(errorMsg)
        setFleetLoading(false)
        return
      }
    } else if (phoneNumber.includes('@')) {
      const errorMsg = validateEmail(phoneNumber)
      if (errorMsg) {
        setError(errorMsg)
        setFleetLoading(false)
        return
      }
    } else {
      setError(translateData.validPhoneEmail)
      setFleetLoading(false)
      return
    }

    setError('')
    try {
      await gotoOTPFleet(userType)
    } catch (error) { }
  }

  const [visible, setVisible] = useState(false)

  const onSelect = (selectedCountry: any) => {
    setCountry(selectedCountry)
    setVisible(false)
    if (setCountryCode && selectedCountry?.callingCode?.[0]) {
      setCountryCode(`+${selectedCountry.callingCode[0]}`)
    }

    if (setCca2) {
      setCca2(selectedCountry.cca2)
    }
  }

  return (
    <View
      style={[
        styles.main,
        { backgroundColor: isDark ? appColors.darkThemeSub : appColors.white },
      ]}
    >
      <View>
        <View style={styles.line} />
        <AuthTitle title={translateData.authTitle} />

        <View style={[styles.mainView, { flexDirection: viewRtlStyle }]}>
          <TouchableOpacity
            style={[
              styles.box,
              {
                backgroundColor: isDark
                  ? appColors.darkThemeSub
                  : appColors.white,
                borderColor:
                  isSelected === 'driver'
                    ? appColors.primary
                    : isDark
                      ? appColors.darkborder
                      : appColors.loader,
              },
            ]}
            activeOpacity={0.7}
            onPress={() => setIsSelected('driver')}
          >
            <Text
              style={[
                styles.buttonText,
                { color: isDark ? appColors.white : appColors.black },
              ]}
            >
              {translateData?.driver}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              styles.box,
              {
                backgroundColor: isDark
                  ? appColors.darkThemeSub
                  : appColors.white,
                borderColor:
                  isSelected === 'fleet'
                    ? appColors.primary
                    : isDark
                      ? appColors.darkborder
                      : appColors.loader,
              },
            ]}
            activeOpacity={0.7}
            onPress={() => setIsSelected('fleet')}
          >
            <Text
              style={[
                styles.buttonText,
                { color: isDark ? appColors.white : appColors.black },
              ]}
            >
              {translateData?.fleet}
            </Text>
          </TouchableOpacity>
        </View>

        <Text
          style={[
            styles.title,
            { color: isDark ? appColors.white : appColors.black },
          ]}
        >
          {' '}
          {numberShow ? translateData?.phone : translateData.email}
        </Text>
        <View
          style={[
            styles.countryCodeContainer,
            {
              flexDirection: viewRtlStyle,
              backgroundColor: isDark ? appColors.primaryFont : appColors.white,
              borderColor: isDark ? appColors.darkborder : appColors.loader,
            },
          ]}
        >
          {numberShow && (
            <View style={[styles.codeComponent]}>
              <TouchableOpacity
                style={[rtl ? styles.countryCode1 : styles.countryCode]}
                onPress={() => setVisible(true)}
              >
                <View style={[styles.pickerButton]}>
                  <CountryPicker
                    countryCode={country.callingCode ? country.callingCode : ''}
                    withFilter={true}
                    withFlag={false}
                    withCallingCode={true}
                    withAlphaFilter={true}
                    withEmoji={true}
                    onSelect={onSelect}
                    visible={visible}
                    onClose={() => setVisible(false)}
                    withFlagButton={false}
                  />

                  {country.callingCode[0] && (
                    <Text
                      style={[
                        styles.codeText,
                        { color: isDark ? appColors.white : appColors.black },
                      ]}
                    >
                      +{country.callingCode[0]}
                    </Text>
                  )}
                </View>
              </TouchableOpacity>
            </View>
          )}

          {numberShow && (
            <View
              style={[
                styles.divison,
                {
                  marginLeft: rtl ? windowWidth(4) : windowWidth(-1),
                  marginRight: rtl ? windowWidth(-1) : windowWidth(4),
                  backgroundColor: isDark
                    ? appColors.darkborder
                    : appColors.loader,
                },
              ]}
            />
          )}
          <TextInput
            placeholder={translateData.enterPhoneandEmailBoth}
            placeholderTextColor={
              isDark ? appColors.darkText : appColors.secondaryFont
            }
            value={phoneNumber}
            onChangeText={handlePhoneNumberChange}
            keyboardType={
              smsGateway === 'firebase' ? 'phone-pad' : 'email-address'
            }
            autoCapitalize="none"
            style={{
              flex: 1,
              height: windowHeight(5.9),
              color: isDark ? appColors.white : appColors.black,
              textAlign: rtl ? 'right' : 'left',
            }}
          />
        </View>

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

      <View style={styles.button}>
        <View style={{ width: '100%', marginBottom: windowHeight(2.8) }}>
          <Button
            title={translateData?.getOtp}
            backgroundColor={isDark ? appColors.white : appColors.black}
            color={isDark ? appColors.black : appColors.white}
            loading={isSelected === 'driver' ? driverLoading : fleetLoading}
            onPress={() =>
              isSelected === 'driver'
                ? handleGetOTP('driver')
                : handleGetOTPFleet('fleet')
            }
          />
        </View>
      </View>
    </View>
  )
}
