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 Button from '~/Components/UIControls/Button';
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 fetchGet from '~/Utils/fetch';

// list item
class Item extends React.PureComponent {
    render() {
        const { item, index, onSelect, onModify } = this.props;
        const zebra = index % 2 == 0 ? true : false;
        return (
            <TouchableOpacity
                onPress={onSelect}
                style={{
                    ...ListStyle.itemContainer,
                    borderTopWidth: 0,
                    backgroundColor: this.props.selected == item.MaterialClassId ? '#cef' : zebra ? '#fdfdfd' : '#fff',
                }}
            >
                <View>
                    <Text style={{ ...ListStyle.text }}>{item.Name}</Text>
                </View>
                <View style={{ width: 80 }}>
                    <Button iconFamily="AntDesign" iconName="form" onPress={onModify}>
                        수정
                    </Button>
                </View>
            </TouchableOpacity>
        );
    }
}

// list
const ListTable = ({ navigation, depth, parent, load, onSelect }) => {
    const [filters, setFilters] = useState([['IsUse', true]]);
    const [firstRender, setFirstRender] = useState(false);
    const [sort, setSort] = useState({ field: 'MaterialClassId', order: 'desc' });
    const [list, setList] = useState(null);
    const [selected, setSelected] = useState(null);
    const { auth, userinfo, config } = useAuth(navigation);
    const { showMessage } = useToast();

    const apiUrl = `api/MaterialCodeClass?depth=${depth}&siteId=${userinfo.SiteId}&businessAuth=${auth.Business}`;
    //console.log('parent', parent);

    useEffect(() => {
        if (load !== false) {
            refreshList();
        }
        setFirstRender(true);
    }, []);

    useEffect(() => {
        if (parent) {
            applyFilter(['ParentMaterialClassId', parent]);
        }
    }, [parent]);

    useEffect(() => {
        if (firstRender) {
            refreshList();
        }
    }, [filters]);

    const fetch = (params) => {
        fetchGet(apiUrl, params)
            .then((data) => {
                setList(data.list);
            })
            .catch((e) => {
                showMessage(e.message);
            });
    };

    const getFilters = () => {
        return filters.map((item) => simpleFilter(item)).filter((x) => x);
    };
    const simpleFilter = (item) => {
        return typeof item == 'object' && Array.isArray(item)
            ? item.length == 3
                ? { field: item[0], op: item[1], value: item[2] }
                : item.length == 2
                ? { field: item[0], op: 'eq', value: item[1] }
                : null
            : item;
    };
    const applyFilter = (filter) => {
        filter = simpleFilter(filter);
        setFilters([...getFilters().filter((item) => !(item.field == filter.field && item.eq == filter.eq)), filter]);
    };
    const refreshList = () => {
        setSelected(null);
        fetch({
            limit: -1,
            conditions: getFilters(),
            sort: sort,
        });
    };

    return (
        <>
            {depth == 0 || (depth > 0 && parent != null) ? (
                <Button
                    iconFamily="AntDesign"
                    iconName="pluscircle"
                    onPress={() => {
                        navigation.navigate('Form', {
                            refreshList: refreshList,
                            action: Form.CREATE,
                            editable: true,
                            siteId: userinfo.SiteId,
                            depth: depth,
                            parent: parent,
                            auth: auth,
                            userinfo: userinfo,
                            config: config,
                        });
                    }}
                >
                    {depth == 0 ? '대분류 ' : depth == 1 ? '중분류 ' : depth == 2 ? '소분류 ' : ''}
                    등록
                </Button>
            ) : (
                <Button iconFamily="AntDesign" iconName="pluscircle" buttonStyle={{ backgroundColor: '#ccc' }}>
                    {depth == 0 ? '대분류 ' : depth == 1 ? '중분류 ' : depth == 2 ? '소분류 ' : ''}
                    등록
                </Button>
            )}

            <SearchListContainer>
                <FlatList
                    keyExtractor={(item, index) => '' + index}
                    data={list}
                    style={{ backgroundColor: '#f5f5f5' }}
                    renderItem={({ item, index }) => {
                        return (
                            <Item
                                item={item}
                                index={index}
                                selected={selected}
                                onSelect={() => {
                                    onSelect({ id: item.MaterialClassId, name: item.Name });
                                    setSelected(item.MaterialClassId);
                                }}
                                onModify={() => {
                                    navigation.navigate('Form', {
                                        refreshList: refreshList,
                                        action: Form.VIEW,
                                        editable: true,
                                        siteId: userinfo.SiteId,
                                        id: [item.MaterialClassId, item.Depth],
                                        parent: parent,
                                        auth: auth,
                                        userinfo: userinfo,
                                        config: config,
                                    });
                                }}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>
        </>
    );
};

export default ListTable;
