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 session from '~/Utils/session';
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';

// 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={{
                ...ListStyle.itemContainer, 
                borderTopWidth: 0, 
                backgroundColor: (zebra?'#fdfdfd':'#fff'),
            }}>
                <View style={{...ListStyle.vertical}}>
                    <Text style={{...ListStyle.text}}>{item.Name}</Text>
                    <Text style={{...ListStyle.textLight}}>{item.BusinessFieldName}</Text>
                    <Text style={{...ListStyle.textRobotoLight}}>{item.FloorName}</Text>
                    <Text style={{...ListStyle.textRobotoLight}}>{item.ZoneName}</Text>
                </View>
                <DetailIcon />
            </TouchableOpacity>
        )
    }
}

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const [ready, setReady] = useState(false);
    const [filters, setFilters] = useState({ 'Material.IsUse_eq': { field: 'Material.IsUse', op: 'eq', value: true } });
    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 [rfid, setRfid] = useState({
        checked: false,
        value: '',
    });
    const [searchForm, setSearchForm] = useState({
        FirstClassId: '',
        SecondClassId: '',
        ThirdClassId: '',
        BusinessFieldId: '',
    });
    const isUseItems = useRef([
        { label: '사용', value: true },
        { label: '미사용', value: false },
    ]);

    const apiUrl = `api/MaterialWarehouse?siteId=${session.getSiteId()}&businessAuth=${auth.Business}`;

    // load session when mount...
    useEffect(() => {
        (async () => {
            await session.load();
            setReady(true);
        })();
    }, []);

    // search events...
    const start = () => {
        setRefreshing(true);
    };
    const success = (data, append) => {
        pages.current = data.pages;
        //console.log(data);

        if (append && page > 1) {
            setList(list.concat(data.list));
        } else {
            setList(data.list);
        }
        setRefreshing(false);
    };
    const fail = (e) => {
        showMessage(e.message);
        setRefreshing(false);
    };

    const refreshList = () => {
        setPage('refresh-' + Math.random());
    };

    return ready ? (
        <BottomTabBarLayout>
            <SearchListContainer>
                <SearchList
                    page={page}
                    pages={pages.current}
                    setPage={setPage}
                    refreshing={refreshing}
                    data={list}
                    style={{ backgroundColor: '#f5f5f5' }}
                    renderItem={({ item, index }) => {
                        return (
                            <Item
                                item={item}
                                index={index}
                                onPress={() => {
                                    navigation.navigate('Form', {
                                        refreshList: refreshList,
                                        action: Form.VIEW, 
                                        siteId: session.getSiteId(), 
                                        id: [item.SiteId, item.WarehouseId], 
                                        auth: auth,
                                        userinfo: userinfo,
                                    });
                                    }}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (
                    <CreateButton
                        onPress={() => {
                            navigation.navigate('Form', {
                                refreshList: refreshList,
                                action: Form.CREATE,
                                siteId: session.getSiteId(),
                                auth: auth,
                                userinfo: userinfo,
                                config: config,
                            });
                        }}
                    />
                )}
            </SearchListContainer>

            <Search
                id="material-warehouse"
                api={apiUrl}
                page={page}
                setPage={setPage}
                limit={50}
                filters={filters}
                sort={{ field: 'WarehouseId', order: 'desc' }}
                onStart={start}
                onSuccess={success}
                onFailure={fail}
            >
                <>
                    <SearchTitle title="업무분야" />
                    <EntitySelect
                        style={{ marginBottom: 20 }}
                        entity="CmBusinessField"
                        defaultLabel="업무분야"
                        useCheck={true}
                        auth={auth}
                        onChange={(item) => {
                            setSearchForm({
                                ...searchForm,
                                BusinessFieldId: item.value,
                            });
                            filterValue([filters, setFilters], 'Material.BusinessFieldId', item.value, 'eq');
                        }}
                        auth={auth}
                    />


                    <SearchTitle title="창고명칭" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="창고명칭"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Name', value, 'cn')}
                    />

                    <SearchTitle title="사용여부" />
                    <Selectbox
                        style={{ marginBottom: 20 }}
                        initialValue={true}
                        defaultLabel="사용여부"
                        items={isUseItems.current}
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'IsUse', item.value, 'eq');
                        }}
                    />
                </>
            </Search>
        </BottomTabBarLayout>
    ) : null;
};

// header
Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="보관 창고 관리" buttons={<SearchIcon id="material-warehouse" />} />,
    };
};

export default Screen;
