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 { Selectbox } from '~/Components/UIControls/Selectbox';
import Input from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';

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.CompanyName}</Text>
                    <Text style={{ ...ListStyle.textRobotoLight }}>{item.PhoneNo}</Text>
                </View>
                <DetailIcon />
            </TouchableOpacity>
        );
    }
}

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const [ready, setReady] = useState(false);
    const [filters, setFilters] = useState({ IsUse_eq: { field: '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 } = useAuth(navigation);
    const { showMessage } = useToast();
    const isUseItems = useRef([
        { label: '사용', value: true },
        { label: '미사용', value: false },
    ]);

    // 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());
    };

    const apiUrl = `api/Department?siteId=${session.getSiteId()}`;

    return ready ? (
        <BottomTabBarLayout>
            <SearchListContainer>
                <SearchList
                    page={page}
                    pages={pages.current}
                    setPage={setPage}
                    refreshing={refreshing}
                    data={list}
                    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.CompanyId, item.DepartmentId],
                                        auth: auth,
                                        userinfo: userinfo,
                                    });
                                }}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (
                    <CreateButton
                        onPress={() => {
                            navigation.navigate('Form', {
                                refreshList: refreshList,
                                action: Form.CREATE,
                                siteId: session.getSiteId(),
                                id: null,
                                auth: auth,
                                userinfo: userinfo,
                            });
                        }}
                    />
                )}
            </SearchListContainer>

            <Search
                id="department-search"
                api={apiUrl}
                page={page}
                setPage={setPage}
                limit={50}
                filters={filters}
                sort={{ field: 'CompanyId', order: 'desc' }}
                onStart={start}
                onSuccess={success}
                onFailure={fail}
            >
                <Fragment>
                    <SearchTitle title="회사 명칭" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="회사 명칭"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'CmCompany.Name', value, 'cn')}
                    />

                    <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) => {
                            console.log('item', item);
                            filterValue([filters, setFilters], 'IsUse', item.value, 'eq');
                        }}
                    />
                </Fragment>
            </Search>
        </BottomTabBarLayout>
    ) : null;
};

// header
Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="부서정보관리" buttons={<SearchIcon id="department-search" />} />,
    };
};

export default Screen;
