import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator, StyleSheet, View, Text } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchPut, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import Button from '~/Components/UIControls/Button';
import Switch from '~/Components/UIControls/Switch';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import { useForm } from 'react-hook-form';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import { usePopup } from '~/Components/UIControls/Popup';
import { useAuth } from '~/Components/Hooks';
import reducer from '~/GlobalReducers/prompt';

const Screen = ({ navigation }) => {
    const action = navigation.getParam('action', Form.EDIT);
    const editable = navigation.getParam('editable', true);
    const setEditable = (value) => {
        navigation.setParams({ editable: value });
    };
    const refreshList = navigation.getParam('refreshList', () => {});
    const siteId = navigation.getParam('siteId', '');
    const id = navigation.getParam('id', null);
    const { auth, userinfo } = useAuth(navigation);
    const { showMessage } = useToast();

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [priceTypeList, setPriceTypeList] = useState(null);
    const [priceTypeId, setPriceTypeId] = useState(action == Form.EDIT ? id[2] : null);

    console.log('priceTypeId', priceTypeId);

    // mount
    useEffect(() => {
        fetch(false);

        //요금 유형 SelectBox
        setLoading(true);
        fetchGet('/api/SitePrice/GetAllPriceType', { fuelTypeId: id[1] })
            .then((data) => {
                if (data) {
                    setPriceTypeList(data);
                    setLoading(false);
                }
            })
            .catch((e) => {
                setLoading(false);
                showMessage(e.message);
            });
    }, []);

    // change editable
    useEffect(() => {}, [editable]);

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);

    const fetch = async (editable = false) => {
        setLoading(true);
        await session.load();

        if (action != Form.CREATE) {
            try {
                const api = `/api/SitePrice/GetPriceCode?siteId=${id[0]}&fuelTypeId=${id[1]}&priceTypeId=${id[2]}`;
                const result = await fetchGet(api);
                setData(result);
                Form.setFormData(result);
            } catch (error) {
                showMessage(error.message);
            }
        }

        setLoading(false);
    };

    // edit
    const onEdit = async () => {
        setEditable(true);
    };

    // cancel edit
    const onCancelEdit = async () => {
        setEditable(false);
    };

    const onSave = async (form) => {
        if (loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }
        console.log('form', form);
        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);

            try {
                const api = `/api/HolidayCustom/${siteId}/${date}`;

                const submit = { ...form, SiteId: siteId };
                console.log('submit data', submit);
                const result = await fetchPost(api, submit);
                showMessage('저장되었습니다.');

                refreshList();
                navigation.pop();
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    // delete
    const onDelete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제', '삭제하시겠습니까?', async () => {
            setLoading(true);
            const api = type == 'C' ? `api/HolidayCustom/${siteId}/${date}` : `api/Holiday/${siteId}/${date}`;
            try {
                await fetchDelete(api);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    console.log('data', data);

    return (
        <BottomTabBarLayout>
            <Form.Container onSave={handleSubmit(onSave)} onDelete={onDelete} onEdit={onEdit} onCancelEdit={onCancelEdit} loading={loading}>
                <Form.Field>
                    <Form.Require style={{ width: 100 }}>
                        <Form.Label>요금제종류</Form.Label>
                    </Form.Require>
                    <View style={{ flex: 1 }}>
                        {priceTypeList && (
                            <Selectbox
                                defaultLabel={'요금제종류'}
                                selectedValue={priceTypeId}
                                /*selectedText={selectedText}*/
                                emptyLabel={'선택'}
                                onChange={({ label, value }) => {
                                    setPriceTypeId(value);
                                }}
                                items={priceTypeList.map((x) => ({ label: x.PriceTypeIdDesc, value: x.PriceTypeId }))}
                                loading={loading}
                                editable={editable}
                            />
                        )}
                    </View>
                </Form.Field>
                <Form.Regist
                    editable={editable}
                    name="PriceTypeId"
                    rule={{ required: '요금제 종류를 선택해주세요' }}
                    error={errors.PriceTypeId}
                />
                <View style={styles.container}>
                    {data &&
                        data.map((item, index) => (
                            <View style={styles.item}>
                                <Form.Field>
                                    <View style={{ flex: 1 }}>
                                        <Form.Label>{item.PriceCodeDesc}</Form.Label>
                                    </View>
                                    <View style={{ width: 50, paddingRight:10,justifyContent: 'center', borderColor:'red', borderWidth:0 }}>
                                        <Switch initialValue={item.UseYn == 'Y'} editable={editable} />
                                    </View>
                                </Form.Field>
                            </View>
                        ))}
                </View>
            </Form.Container>
        </BottomTabBarLayout>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        flexWrap: 'wrap',
        alignItems: 'flex-start', // if you want to fill rows left to right
        marginBottom:50,
    },
    item: {
        width: '50%', // is 50% of container width
        marginBottom: 5,
    },
});

Screen.navigationOptions = ({ navigation }) => {
    const action = navigation.getParam('action', Form.VIEW); // create, edit, view
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const { auth } = useAuth(navigation);

    return {
        header: () => (
            <Header
                navigation={navigation}
                title={`고지서 설정 상세`}
                main={false}
                buttons={
                    <Fragment>
                        {!editable && auth.Update && (
                            <Fragment>
                                <Form.SaveButton type="primary" />
                                <Form.DeleteButton />
                            </Fragment>
                        )}
                    </Fragment>
                }
            />
        ),
    };
};

export default Screen;
