import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity } from 'react-native';
import Styled from 'styled-components/native';
import Header from '~/Components/Layouts/Header';
import {
    Search,
    SearchIcon,
    Line,
    TextInput,
    checkFilter,
    filterValue,
    ListStyle,
    DetailIcon,
    RightArrow,
    CreateButton,
    SearchTitle,
} from '~/Components/Listing/Search';
import Checkbox from '~/Components/UIControls/Checkbox';
import Theme from '~/Themes';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import SearchList, { SearchListContainer } from '~/Components/Listing/SearchList';
import EmptyView from '~/Components/Listing/EmptyView';
import EntitySelect from '~/Components/EntitySelect';
import { useToast } from '~/Components/UIControls/Message';
import { DateTimePicker } from '~/Components/UIControls/DateTimePicker';
import Input from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import { fetchGet, isCancel } from '~/Utils/fetch';
import Button from '~/Components/UIControls/Button';

const style = StyleSheet.create({
    container: { flexDirection: 'row', alignItems: 'center', padding: 5 },
    text: { paddingLeft: 15, fontSize: 16, color: '#000', flex: 1 },
});

// list item
class Item extends React.PureComponent {
    render() {
        const { item, index, onPress = () => {} } = this.props;
        const zebra = index % 2 == 0 ? true : false;
        return (
            <TouchableOpacity
                onPress={onPress}
                style={{
                    borderTopWidth: 1,
                    borderTopColor: '#e9e9e9',
                    backgroundColor: zebra ? '#fdfdfd' : '#fff',
                }}
            >
                <View style={style.container}>
                    <Text style={style.text}>{item.PriceTypeIdDesc}</Text>
                    <DetailIcon />
                </View>
            </TouchableOpacity>
        );
    }
}

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const [loading, setLoading] = useState(false);
    const [filters, setFilters] = useState({});
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const { auth, userinfo, config } = useAuth(navigation);
    const { showMessage } = useToast();

    const [fuelTypeList, setFuelTypeList] = useState([]);
    const [fuelTypeId, setFuelTypeId] = useState(1);

    const apiUrl = `/api/SitePrice/GetPriceType?siteId=${userinfo.SiteId}&fuelTypeId=${fuelTypeId}`;

    const fetchFuelType = () => {
        fetchGet('/api/SitePrice/GetFuelType')
            .then((data) => {
                if (data) {
                    setFuelTypeList(data);
                }
            })
            .catch((e) => {
                showMessage(e.message);
            });
    };

    useEffect(() => {
        fetchFuelType();
    }, []);

    useEffect(() => {
        fetchTabData(userinfo.SiteId, fuelTypeId);
    }, [fuelTypeId]);

    const fetchTabData = (siteId, fuelTypeId) => {
        setLoading(true);
        fetchGet('/api/SitePrice/GetPriceType', { siteId, fuelTypeId })
            .then((data) => {
                console.log('data', data);
                if (data) {
                    setList(data);
                }
            })
            .catch((e) => {
                setLoading(false);
                showMessage(e.message);
            });
    };

    const refreshList = () => {
        fetchTabData(userinfo.SiteId, fuelTypeId);
    };

    return (
        <BottomTabBarLayout>
            <View style={{ display: 'flex', flexDirection: 'row' }}>
                {fuelTypeList.map((item) => (
                    <Button
                        onPress={() => {
                            setFuelTypeId(item.FuelTypeId);
                        }}
                        style={{ flex: 1 }}
                        color={item.FuelTypeId == fuelTypeId ? 'PRIMARY' : 'GREY'}
                    >
                        {item.Name}
                    </Button>
                ))}
            </View>

            <SearchListContainer>
                <FlatList
                    onEndReachedThreshold={0.5}
                    refreshing={false} 
                    onRefresh={() => {
                        if(refreshing) return;
                        fetchTabData(userinfo.SiteId, fuelTypeId);
                    }}
                    keyExtractor={(item, index) => '' + item.PriceTypeId}
                    data={list}
                    style={{ backgroundColor: '#f5f5f5' }}
                    renderItem={({ item, index }) => {
                        return (
                            <Item
                                item={item}
                                index={index}
                                onPress={() => {
                                    navigation.navigate('Form', {
                                        refreshList: refreshList,
                                        action: Form.EDIT,
                                        siteId: userinfo.SiteId,
                                        id: [userinfo.SiteId, fuelTypeId, item.PriceTypeId],
                                        auth: auth,
                                        userinfo: userinfo,
                                        config: config,
                                    });
                                }}
                            />
                        );
                    }}
                    ListEmptyComponent={
                        <View style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
                            <Text style={{ flex: 1 }}>작성된 요금제가 없습니다</Text>
                        </View>
                    }
                />
                {auth.Update && (
                    <CreateButton
                        onPress={() => {
                            navigation.navigate('Form', {
                                refreshList: refreshList,
                                action: Form.CREATE,
                                siteId: userinfo.SiteId,
                                auth: auth,
                                userinfo: userinfo,
                                config: config,
                            });
                        }}
                    />
                )}
            </SearchListContainer>
        </BottomTabBarLayout>
    );
};

// header
Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="고지서 설정" />,
    };
};

export default Screen;
