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'

const PaymentOptionHushkiUI = (props: any) => {
    const {
        cardSelected,
        deleteCard,
        onSelectCard,
        handleCardClick,
        cardsList,
        setNewCard,
        newCard,
        requestSubcriptionToken,
        paymethod,
        credentials,
        setCredentials,
        handleChangeInput,
        addCardOpen,
        setAddCardOpen,
        setBankSelected,
        bankSelected,
        bankList
    } = props
    const [, t] = useLanguage()
    const theme = useTheme()
    const [{ user, token }] = useSession()
    const [alertState, setAlertState] = useState<{ open: boolean, content: Array<string> }>({ open: false, content: [] })

    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
            })
        }
    }

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

    const style = StyleSheet.create({
        wrapperIcon: {
            marginLeft: 25,
            marginTop: Platform.OS === 'ios' ? 40 : 12,
            marginBottom: 20,
            alignItems: 'center',
            justifyContent: 'center',
        },
    })

    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={() => setAddCardOpen(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}
                onDismiss={() => setAddCardOpen(false)}
            >
                <KeyboardAvoidingView
                    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                    style={{
                        flex: 1,
                    }}
                >
                    <ScrollView>
                        <TouchableOpacity onPress={() => setAddCardOpen(false)}>
                            <OIcon
                                src={theme.images.general.close}
                                width={16}
                                style={style.wrapperIcon}
                            />
                        </TouchableOpacity>
                        {paymethod === 'kushki_card' && (
                            <>
                                <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
                                    }}
                                />
                            </>
                        )}
                        {(
                            kushkiForms.includes(paymethod) && (
                                <KushkiCash
                                    credentials={credentials}
                                    setCredentials={setCredentials}
                                    handleChangeInput={handleChangeInput}
                                    setAddCardOpen={setAddCardOpen}
                                    paymethod={paymethod}
                                />
                            )
                        )}
                    </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} />
    )
}
