import React, { useEffect, useRef, useState } from 'react'
import { View, Modal, TouchableOpacity, StyleSheet, SafeAreaView, KeyboardAvoidingView, Platform, ScrollView } from 'react-native'
import { OButton, OIcon, OInput, OModal, OText } from '../shared'
import { OTab, OTabs, TabBtn } from './styles'
import { PaymentOptionKushki as PaymentOptionHushkiController, useLanguage, useSession } from 'ordering-components-Ubanku-Custom/native'
import { StripeCardsListUI } from '../StripeCardsList'
import { useTheme } from 'styled-components/native';
import { CreditCardInput } from "react-native-credit-card-input-plus";
import Alert from '../../providers/AlertProvider'
import { KushkiCash } from './KuskiCash'
import Picker from 'react-native-picker-select'
import { PlaceholderLine } from 'rn-placeholder'
import OtpInputs from 'react-native-otp-inputs'

const PaymentOptionHushkiUI = (props: any) => {
    const {
        cardSelected,
        deleteCard,
        onSelectCard,
        handleCardClick,
        cardsList,
        setNewCard,
        newCard,
        requestSubcriptionToken,
        paymethod,
        credentials,
        setCredentials,
        handleChangeInput,
        addCardOpen,
        setAddCardOpen,
        setBankSelected,
        bankSelected,
        bankList,
        setSecureData,
        secureData,
        openOtpModal,
        setOpenOtpModal,
        handlerequestSecureService,
        handleUpdateUser
    } = props
    const [, t] = useLanguage()
    const theme = useTheme()
    const [{ user, token }] = useSession()
    const [dataFormOpen, setDataFormOpen] = useState(false)
    const [alertState, setAlertState] = useState<{ open: boolean, content: Array<string> }>({ open: false, content: [] })
    const inputRef = useRef<any>()
    const kushkiForms = ['kushki_cash', 'kushki_bank']
    const filterData = (data: string) => {
        if (paymethod === 'kushki_cash') {
            return !['user_type'].includes(data)
        } else {
            return true
        }
    }

    const onChangeCardForm = (values) => {
        if (values?.valid) {
            const expiry = values?.values?.expiry?.split('/')
            const expiryMonth = expiry[0]
            const expiryYear = expiry[1]
            setNewCard({
                name: values?.values.name,
                number: values?.values.number.replace(/\s/g, ''),
                cvc: values?.values.cvc,
                expiryMonth: expiryMonth,
                expiryYear: expiryYear
            })
        }
    }

    const handleCloseOtpModal = () => {
        setSecureData({ secureId: null, otp: null, otpError: null })
        setOpenOtpModal(false)
    }

    const handleCloseCardModal = () => {
        setAddCardOpen(false)
        setNewCard(null)
        setDataFormOpen(false)
    }

    useEffect(() => {
        if (cardsList.error && !cardsList.loading) {
            setAlertState({
                open: true,
                content: cardsList.error
            })
        }
    }, [JSON.stringify(cardsList)])

    useEffect(() => {
        if (secureData?.otp?.length === 3) {
            handlerequestSecureService()
        }
    }, [secureData?.otp])

    const style = StyleSheet.create({
        wrapperIcon: {
            marginLeft: 25,
            marginTop: Platform.OS === 'ios' ? 40 : 12,
            marginBottom: 20,
            alignItems: 'center',
            justifyContent: 'center',
        },
        container: {
            width: '100%',
            flexDirection: 'row',
            justifyContent: 'center',
            marginVertical: 15
        },
        underlineStyleBase: {
            width: 45,
            height: 50,
            borderWidth: 1,
            fontSize: 16,
            borderRadius: 8,
            borderColor: theme.colors.lightGray,
            margin: 20,
            textAlign: 'center'
        },
        underlineStyleHighLighted: {
            borderColor: theme.colors.primary,
            color: theme.colors.primary,
            fontSize: 16
        },
        closeContainer: {
            width: '100%',
            flexDirection: 'row',
        },
        otpExample: {
            borderWidth: 1,
            paddingHorizontal: 10,
            paddingVertical: 10,
            borderRadius: 7.6,
            marginTop: 10,
            borderColor: '#ccc',
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center'
        },
        testCashStyle: {
            borderWidth: 1,
            paddingTop: 3,
            paddingHorizontal: 5,
            borderColor: theme?.colors?.primary,
            borderRadius: 8,
        },
        charge: {
            textAlign: 'center'
        },
        chargeContainer: {
            paddingHorizontal: 10,
            backgroundColor: theme?.colors?.primary,
            width: '100%',
            marginTop: 20,
            borderRadius: 8
        }
    })

    const _pickerStyle = StyleSheet.create({
        inputAndroid: {
            color: '#000',
            borderWidth: 1,
            paddingHorizontal: 10,
            paddingEnd: 24,
            height: 50,
            borderColor: '#000',
            marginBottom: 20,
            borderRadius: 8,
            backgroundColor: '#ddd'
        },
        inputIOS: {
            color: '#000',
            borderWidth: 1,
            paddingHorizontal: 10,
            paddingEnd: 24,
            height: 50,
            borderColor: '#000',
            marginBottom: 20,
            borderRadius: 8,
            backgroundColor: '#ddd'
        },
        icon: {
            width: 10,
            marginTop: 9,
            marginEnd: 10,
        },
        placeholder: {
            color: theme.colors.secundaryContrast
        },
    })

    return (
        <View>
            <View style={{
                marginTop: 20
            }}>
                {paymethod === 'kushki_bank' && (
                    <>
                        {bankList?.length > 0 ? (
                            <Picker
                                value={bankSelected?.value}
                                onValueChange={value => setBankSelected(value)}
                                style={_pickerStyle}
                                items={bankList}
                                placeholder={{
                                    label: t('SELECT_YOUR_BANK', 'Select your bank'),
                                    value: null,
                                    color: theme.colors.disabled,
                                }}
                                Icon={() => <View style={_pickerStyle.icon}><OIcon src={theme.images.general.arrow_down} color={theme.colors.black} style={{ width: '100%', top: 2 }} /></View>}
                            />
                        ) : (
                            <PlaceholderLine
                                height={50}
                                noMargin
                                style={{ marginBottom: 20 }}
                            />
                        )}
                    </>
                )}
                <View style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between'
                }}>
                    <OText>
                        {t('YOUR_PAYMENT_INFORMATION', 'Your payment information')}
                    </OText>
                    <TouchableOpacity onPress={() => setDataFormOpen(true)}>
                        <OText
                            color={theme?.colors?.primary}
                            style={{
                                textDecorationLine: 'underline'
                            }}
                        >
                            {t('MODIFY', 'Modify')}
                        </OText>
                    </TouchableOpacity>
                </View>
                <View style={{ marginLeft: 10, marginTop: 5 }}>
                    {Object.keys(credentials || {}).filter(data => filterData(data)).map(data => (
                        <OText key={data}>
                            {t(data.toUpperCase(), data)}: {data === 'user_type' ? credentials?.[data] === '1' ? t('NATURAL', 'Natural') : t('JURIDICAL', 'Juridical') : credentials?.[data]}
                        </OText>
                    ))}
                </View>
            </View>
            {paymethod === 'kushki_card' && (
                <>
                    <OButton
                        text={t('ADD_PAYMENT_CARD', 'Add New Payment Card')}
                        bgColor={theme.colors.white}
                        borderColor={theme.colors.primary}
                        style={{
                            marginVertical: 20,
                            borderRadius: 7.6,
                            shadowOpacity: 0,
                            height: 44,
                            borderWidth: 1
                        }}
                        textStyle={{ color: theme.colors.primary, fontSize: 12 }}
                        imgRightSrc={null}
                        onClick={() => setAddCardOpen(true)}
                    />
                    <StripeCardsListUI
                        cardSelected={cardSelected}
                        deleteCard={deleteCard}
                        onSelectCard={onSelectCard}
                        handleCardClick={handleCardClick}
                        cardsList={cardsList}
                        noShowErrors
                    />
                </>
            )}

            <Modal
                animationType="slide"
                visible={addCardOpen || dataFormOpen}
                onDismiss={() => handleCloseCardModal()}
            >
                <KeyboardAvoidingView
                    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                    style={{
                        flex: 1,
                    }}
                >
                    <ScrollView>
                        <TouchableOpacity onPress={() => handleCloseCardModal()}>
                            <OIcon
                                src={theme.images.general.close}
                                width={16}
                                style={style.wrapperIcon}
                            />
                        </TouchableOpacity>
                        {addCardOpen && (
                            <>
                                <CreditCardInput
                                    onChange={onChangeCardForm}
                                    requiresName
                                />
                                {alertState?.content?.[0] && !cardsList?.loading && (
                                    <OText
                                        color={theme?.colors?.error}
                                        style={{
                                            alignSelf: 'center'
                                        }}
                                        size={20}
                                    >
                                        {alertState.content[0]}
                                    </OText>
                                )}
                                <OButton
                                    text={t('ADD_CARD', 'Add card')}
                                    isDisabled={!newCard || cardsList?.loading}
                                    isLoading={cardsList?.loading}
                                    onClick={requestSubcriptionToken}
                                    style={{
                                        margin: 20
                                    }}
                                />
                            </>
                        )}
                        {dataFormOpen && (
                            <KushkiCash
                                credentials={credentials}
                                setCredentials={setCredentials}
                                handleChangeInput={handleChangeInput}
                                setAddCardOpen={setAddCardOpen}
                                handleCloseCardModal={handleCloseCardModal}
                                paymethod={paymethod}
                                handleUpdateUser={handleUpdateUser}
                            />
                        )}
                    </ScrollView>
                </KeyboardAvoidingView>
            </Modal>
            <Modal
                animationType="slide"
                visible={openOtpModal}
                onDismiss={() => handleCloseOtpModal()}
            >
                <KeyboardAvoidingView
                    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                    style={{
                        flex: 1,
                    }}
                >
                    <ScrollView>
                        <View style={{
                            flexDirection: 'row',
                            alignItems: 'center'
                        }}>
                            <TouchableOpacity onPress={() => handleCloseOtpModal()}>
                                <OIcon
                                    src={theme.images.general.close}
                                    width={16}
                                    style={style.wrapperIcon}
                                />
                            </TouchableOpacity>
                            <OText size={22} style={{
                                marginLeft: 20,
                                marginBottom: 5
                            }}>
                                {t('ENTER_VERIFICATION_CODE', 'Enter verification code')}
                            </OText>
                        </View>
                        <View style={{ padding: 20 }}>
                            <OText size={18}>
                                {t('OTP_KUSHKI_VALIDATION', 'Please insert the security code of 3 digits correspondent to the')}{' '}
                                <OText size={19} weight={'bold'}>
                                    {t('AMOUNT_CHARGED_TO_YOUR_CARD', 'amount charged to your card')}
                                </OText>
                            </OText>
                            <View style={style.otpExample}>
                                <OText>
                                    {t('PAY_WITH_KUSHKI', 'Pay with Kushki')}
                                </OText>
                                <OText style={style.testCashStyle}>
                                    $X.XX
                                </OText>
                            </View>
                            <View style={style?.chargeContainer}>
                                <OText
                                    style={style.charge}
                                >
                                    {t('THIS_CHARGE_WILL_BE_CANCELED', 'This charge will be canceled automatically')}
                                </OText>
                            </View>
                            <View>
                                <OtpInputs
                                    ref={inputRef}
                                    numberOfInputs={3}
                                    handleChange={(code: string) => setSecureData({ ...secureData, otp: code, otpError: null })}
                                    style={style.container}
                                    inputStyles={style.underlineStyleBase}
                                />
                            </View>
                            {!!secureData?.otpError && (
                                <OText
                                    color={theme?.colors?.error}
                                    style={{ textAlign: 'center' }}
                                    size={20}
                                >
                                    {secureData?.otpError}
                                </OText>
                            )}
                        </View>
                    </ScrollView>
                </KeyboardAvoidingView>
            </Modal>
            <Alert
                open={alertState?.open || false}
                title=''
                content={alertState.content}
                onClose={() => setAlertState({ open: false, content: [] })}
                onAccept={() => setAlertState({ open: false, content: [] })}
            />
        </View>
    )
}

export const PaymentOptionHushki = (props) => {
    const paymentOptions = {
        ...props,
        UIComponent: PaymentOptionHushkiUI
    }
    return (
        <PaymentOptionHushkiController {...paymentOptions} />
    )
}
