import React, { useRef } from 'react'
import { Controller, useForm } from 'react-hook-form';
import { View, StyleSheet, ScrollView, KeyboardAvoidingView, Platform, SafeAreaView } from 'react-native'
import { sortInputFields } from '../../../utils';
import { useLanguage, useSession, useValidationFields } from 'ordering-components-Ubanku-Custom/native';
import { OText } from 'ordering-ui-native-ubanku-release/src/components/shared';
import { useTheme } from 'styled-components/native';
import { OButton, OIcon, OInput } from '../../shared';
import Picker from 'react-native-picker-select';

const notValidationFields = [
    'coupon',
    'driver_tip',
    'mobile_phone',
    'address',
    'address_notes',
    'middle_name',
    'second_lastname'
]

const additionalInputsField = {
    document_type: {
        code: 'document_type',
        enabled: true,
        required: true,
        type: 'text',
        validate: 'checkout',
        name: 'CC',
        id: 'Document_Type'
    },
    document_number: {
        code: 'document_number',
        enabled: true,
        required: true,
        type: 'text',
        validate: 'checkout',
        name: 'Identification',
        id: 'Document_number'
    },
    user_type: {
        code: 'user_type',
        enabled: true,
        required: true,
        type: 'text',
        validate: 'checkout',
        name: 'User Type',
        id: 'User_type'
    },
    // reference: {
    //     code: 'reference',
    //     enabled: true,
    //     required: true,
    //     type: 'text',
    //     validate: 'checkout',
    //     name: 'Reference',
    //     id: 'Reference'
    // },
}

export const KushkiCash = (props: any) => {
    const {
        credentials,
        setCredentials,
        handleChangeInput,
        setAddCardOpen,
        paymethod
    } = props

    const [validationFields] = useValidationFields()
    const [, t] = useLanguage()
    const theme = useTheme()
    const [{ user }] = useSession()
    const { control, handleSubmit, clearErrors, errors, register, unregister, setValue } = useForm();

    const nameRef = useRef<any>(null);
    const lastnameRef = useRef<any>(null);
    const emailRef = useRef<any>(null);
    const ccRef = useRef<any>(null);
    const identificationRef = useRef<any>(null);
    const descriptionRef = useRef<any>(null);

    const documentTypesList = [
        { label: t('CITIZENSHIP_CARD', "Cédula de ciudadania"), value: "CC" },
        { label: t("NIT", 'NIT'), value: "NIT" },
        { label: t('FOREIGNER_ID', "Cédula de extranjería"), value: "CE" },
        { label: t('IDENTITY_CARD', "Tarjeta de identidad"), value: "TI" },
        { label: t('PASSPORT', "PP"), value: "Pasaporte" }
    ]

    const userTypesList = [
        { label: "Natural", value: "1" },
        { label: "Juridica", value: "2" }
    ]

    const inputs = paymethod === 'kushki_cash'
        ? ['name', 'lastname', 'document_type', 'document_number', 'email']
        : ['name', 'lastname', 'user_type', 'document_type', 'document_number', 'email']

    const selectTypes = ['document_type', 'user_type']

    const onSubmit = (values: any) => {
        setCredentials(values)
        setAddCardOpen(false)
    }

    const getInputRules = (field: any) => {
        const rules: any = {
            required: t(
                `VALIDATION_ERROR_${field.code.toUpperCase()}_REQUIRED`,
                `${field.name} is required`,
            ).replace('_attribute_', t(field.name, field.code))
        };
        if (field.code && field.code === 'email') {
            rules.pattern = {
                value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                message: t('INVALID_ERROR_EMAIL', 'Invalid email address').replace(
                    '_attribute_',
                    t('EMAIL', 'Email'),
                ),
            };
        }
        return rules;
    };

    const handleRefs = (ref: any, code: string) => {
        switch (code) {
            case 'name': {
                nameRef.current = ref;
                break;
            }
            case 'lastname': {
                lastnameRef.current = ref;
                break;
            }
            case 'email': {
                emailRef.current = ref;
                break;
            }
            case 'document_type': {
                ccRef.current = ref;
                break;
            }
            case 'document_number': {
                identificationRef.current = ref;
                break;
            }
            case 'description': {
                descriptionRef.current = ref;
                break;
            }
        }
    };

    const handleFocusRef = (code: string) => {
        switch (code) {
            case 'name': {
                nameRef?.current?.focus();
                break;
            }
            case 'lastname': {
                lastnameRef?.current?.focus();
                break;
            }
            case 'email': {
                emailRef?.current?.focus();
                break;
            }
            case 'document_type': {
                ccRef?.current?.focus();
                break;
            }
            case 'document_number': {
                identificationRef?.current?.focus();
                break;
            }
            case 'description': {
                descriptionRef?.current?.focus();
                break;
            }
        }
    };

    const getNextFieldCode = (index: number) => {
        const fields = sortInputFields({
            values: {
                ...validationFields?.fields?.checkout,
                ...additionalInputsField
            },
        })?.filter(
            (field: any) =>
                !notValidationFields.includes(field.code)
        );
        return fields[index + 1]?.code;
    };


    const style = StyleSheet.create({
        inputStyle: {
            marginBottom: 20,
            borderWidth: 1,
            borderRadius: 7.6,
        },
        container: {
            padding: 20,
        },

    });

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

    return (
        <View style={style.container}>
            {sortInputFields({
                fields: inputs,
                values: {
                    ...validationFields?.fields?.checkout,
                    ...additionalInputsField
                },
            }).map(
                (field: any, i: number) =>
                    !notValidationFields.includes(field.code) && (
                        <React.Fragment key={`${field.id}_${i}`}>
                            {errors?.[`${field.code}`] && (
                                <OText
                                    size={14}
                                    color={theme.colors.danger5}
                                    weight={'normal'}>
                                    {errors?.[`${field.code}`]?.message} {errors?.[`${field.code}`]?.type === 'required' && '*'}
                                </OText>
                            )}
                            <Controller
                                control={control}
                                render={!selectTypes.includes(field.code) ? () => (
                                    <OInput
                                        placeholder={
                                            field.name === 'dream'
                                                ? t('WHAT_IS_YOUR_NEXT_DREAM', 'What is your next dream?')
                                                : t(field.name)
                                        }
                                        style={style.inputStyle}
                                        icon={
                                            field.code === 'email'
                                                ? theme.images.general.email
                                                : theme.images.general.user
                                        }
                                        value={credentials?.[field?.code] ?? (user && user?.[field?.code]) ?? ''}
                                        defaultValue={credentials?.[field?.code] ?? (user && user[field?.code]) ?? ''}
                                        onChange={(val: any) => {
                                            field.code !== 'email'
                                                ? setValue(field.code, val)
                                                : setValue(
                                                    field.code,
                                                    val
                                                        .toLowerCase()
                                                        .replace(
                                                            /[&,()%";:ç?<>{}\\[\]\s]/g,
                                                            '',
                                                        ),
                                                );
                                            field.code !== 'email'
                                                ? handleChangeInput({
                                                    target: {
                                                        name: field.code,
                                                        value: val
                                                    }
                                                })
                                                : handleChangeInput({
                                                    target: {
                                                        name: 'email',
                                                        value: val
                                                            .toLowerCase()
                                                            .replace(
                                                                /[&,()%";:ç?<>{}\\[\]\s]/g,
                                                                '',
                                                            ),
                                                    },
                                                });
                                        }}
                                        autoCapitalize={
                                            field.code === 'email' ? 'none' : 'sentences'
                                        }
                                        autoCorrect={field.code === 'email' && false}
                                        type={
                                            field.code === 'email' ? 'email-address' : 'default'
                                        }
                                        autoCompleteType={
                                            field.code === 'email' ? 'email' : 'off'
                                        }
                                        returnKeyType="next"
                                        blurOnSubmit={false}
                                        forwardRef={(ref: any) => handleRefs(ref, field.code)}
                                        onSubmitEditing={() =>
                                            field.code === 'email'
                                                ? descriptionRef?.current?.focus?.()
                                                : handleFocusRef(getNextFieldCode(i))
                                        }
                                        borderColor={errors?.[`${field.code}`] ? theme.colors.danger5 : theme.colors.border}
                                    />
                                ) : () => (
                                    <Picker
                                        value={credentials?.[field?.code] || (user && user?.[field?.code])}
                                        onValueChange={(value) => {
                                            handleChangeInput({
                                                target: {
                                                    name: field.code,
                                                    value
                                                },
                                            })
                                            setValue(field.code, value)
                                        }}
                                        style={_pickerStyle}
                                        placeholder={{
                                            label: field?.code === 'document_type' ? t('SELECT_YOUR_DOCUMENT_TYPE', 'Select your document type') : t('SELECT_YOUR_USER_TYPE', 'Select your user type'),
                                            value: null,
                                            color: theme.colors.disabled,
                                        }}
                                        items={field?.code === 'document_type' ? documentTypesList : userTypesList}
                                        Icon={() => <View style={_pickerStyle.icon}><OIcon src={theme.images.general.arrow_down} color={theme.colors.black} style={{ width: '100%', top: 2 }} /></View>}
                                    />
                                )}
                                name={field.code}
                                rules={getInputRules(field)}
                                defaultValue={credentials?.[field?.code] ?? (user && user[field.code]) ?? ''}
                            />
                        </React.Fragment>
                    ),
            )}

            <OButton
                onClick={handleSubmit(onSubmit)}
                text={t('SAVE', 'Save')}
                bgColor={theme.colors.primary}
                borderColor={theme.colors.primary}
                textStyle={{ color: 'white' }}
                imgRightSrc={null}
                isDisabled={validationFields.loading}
                style={{ borderRadius: 7.6, marginTop: 6, shadowOpacity: 0 }}
            />
        </View>
    )
}
