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';

const style = StyleSheet.create({
    container: { flexDirection: 'column' },
    header: { padding: 15, paddingLeft:0, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'center' },
    headerBadge: {
        height: 28,
        paddingHorizontal:10,
        marginRight:5,
        borderRadius: 14,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: '#0b83e6',
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerBadgeText: { color: '#0b83e6', fontSize: 14, textAlign: 'center' },
    headerCategory: { fontSize: 16, color: '#9aa3ac' },
    headerName: { fontSize: 16, lineHeight:28, color: '#000' },
    headerDetail: { marginLeft: 15, flexDirection: 'column', flex: 1 },
    headerExtraContainer: { flexDirection: 'row' },
    headerExtra: { color: '#b9bac4', fontSize: 14 },
    stock: { paddingHorizontal: 15, paddingVertical: 8, backgroundColor: '#f8fcff', flexDirection: 'row' },
    stockLabel: { color: '#9aa3ac', fontSize: 16, fontFamily: Theme.Fonts.Regular },
    stockValue: { fontWeight: '500', fontSize: 16, fontFamily: Theme.Fonts.Regular },
});

// 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={{
                    marginBottom: 10,
                    borderTopWidth: 1,
                    borderTopColor: '#e9e9e9',
                    backgroundColor: zebra ? '#fdfdfd' : '#fff',
                }}
            >
                <View style={style.container}>
                    <View style={style.header}>
                        <View style={style.headerDetail}>
                            <View style={style.headerExtraContainer}>
                                <View style={style.headerBadge}>
                                    <Text style={style.headerBadgeText}>{item.BusinessFieldName}</Text>
                                </View>
                                <Text style={style.headerName}>{item.Title}</Text>
                            </View>
                            <Text style={style.headerCategory}>{item.ProgressName}</Text>
                            <View style={style.headerExtraContainer}>
                                <Text style={{ ...style.headerExtra, marginRight: 'auto' }}>{item.OrderUserName}</Text>
                                <Text style={{ ...style.headerExtra, marginLeft: 'auto' }}>
                                    {Util.toDateString(item.OrderDate, '', '.')}
                                </Text>
                            </View>
                        </View>
                    </View>
                    <View style={{ ...style.stock, display: item.StoredDueDate ? 'flex' : 'none' }}>
                        <Text style={{ ...style.stockLabel, marginLeft: 'auto' }}>입고예정일</Text>
                        <Text style={{ ...style.stockValue, marginLeft: 9 }}>{Util.toDateString(item.StoredDueDate)}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }
}

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    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/MaterialPurchaseOrder?siteId=${userinfo.SiteId}&businessAuth=${auth.Business}`;

    // 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 (
        <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: userinfo.SiteId,
                                        id: [item.SiteId, item.PurchaseOrderId],
                                        auth: auth,
                                        userinfo: userinfo,
                                        config: config,
                                    });
                                }}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (
                    <CreateButton
                        onPress={() => {
                            navigation.navigate('Form', {
                                refreshList: refreshList,
                                action: Form.CREATE,
                                siteId: userinfo.SiteId,
                                auth: auth,
                                userinfo: userinfo,
                                config: config,
                            });
                        }}
                    />
                )}
            </SearchListContainer>

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

                    <SearchTitle title="진행상태" />
                    <EntitySelect
                        style={{ marginBottom: 20 }}
                        entity="FmsMaterialCodeProgress"
                        id="ProgressId"
                        defaultLabel="진행상태"
                        emptyLabel="전체" 
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'ProgressId', item.value, 'eq');
                        }}
                    />

                    <SearchTitle title="발주제목" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="발주제목"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Title', value, 'cn')}
                    />

                    <SearchTitle title="발주자명" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="발주자명"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'CmUser.Name', value, 'cn')}
                    />

                    <SearchTitle title="발주일자" />
                    <DateTimePicker
                        style={{ marginBottom: 5 }}
                        placeholder="부터"
                        useClear={true}
                        onChange={(newDate) => {
                            filterValue([filters, setFilters], 'OrderDate', Util.toDateString(newDate), 'ge');
                        }}
                    />
                    <DateTimePicker
                        style={{ marginBottom: 20 }}
                        placeholder="까지"
                        useClear={true}
                        onChange={(newDate) => {
                            filterValue([filters, setFilters], 'OrderDate', Util.toDateString(newDate), 'le');
                        }}
                    />

                </>
            </Search>
        </BottomTabBarLayout>
    );
};

// header
Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="발주등록및 현황" buttons={<SearchIcon id="materialstock" />} />,
    };
};

export default Screen;
