import React, { Fragment, useState, useEffect, useCallback, createRef, useRef, PureComponent } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity, TouchableOpacityBase, TouchableNativeFeedback } 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 { Tab, TabItem, TabTitleGroup, TabHeader, TabContent, TabTitle } from '~/Components/UIControls/Tab';
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 { initialState } from '~/GlobalReducers/prompt';
import { useAuth } from '~/Components/Hooks';

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: 63,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: '#0b83e6',
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerBadgeText: { color: '#0b83e6', fontSize: 14, textAlign: 'center', fontFamily: Theme.Fonts.RobotoRegular },
    headerCategory: { fontSize: 16, color: '#9aa3ac', display:'none' },
    headerName: { fontSize: 16, color: '#000' },
    headerDetail: { marginLeft: 15, flexDirection: 'column', flex: 1 },
    headerExtraContainer: { flexDirection: 'row', alignItems: 'center' },
    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 },
    detail: { padding: 15, flexDirection: 'row', justifyContent: 'space-between' },
    detailBadge: {
        width: 70,
        height: 35,
        borderRadius: 70,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: '#9aa3ac',
        alignItems: 'center',
        justifyContent: 'center',
    },
    detailBadgeText: { color: '#000', fontSize: 22, textAlign: 'center', fontFamily: Theme.Fonts.RobotoRegular },
    detailBadgeLabel: { textAlign: 'center', marginTop: 5 },
    detailLabel: { fontFamily: Theme.Fonts.RobotoRegular },
});

// list item
class Item extends React.PureComponent {
    render() {
        const { item, index } = this.props;
        const zebra = index % 2 == 0 ? true : false;
        if (item.Month) {
            item.Date = item.Year + '.' + item.Month;
        } else {
            item.Date = Util.toDateString(item.Date, '', '.');
        }
        return (
            <TouchableOpacity
                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.Name}</Text>
                            </View>
                            <Text style={style.headerCategory}>
                                {[item.FirstClassName, item.SecondClassName, item.ThirdClassName].filter((e) => e).join(' > ')}
                            </Text>
                            <View style={style.headerExtraContainer}>
                                <Text style={{ ...style.headerExtra, marginRight: 'auto' }}>
                                    {[item.Standard, item.Unit].filter((e) => e).join('/')}
                                </Text>
                                <Text style={{ ...style.headerExtra, marginLeft: 'auto' }}>{item.Date}</Text>
                            </View>
                        </View>
                    </View>
                    <View style={style.stock}>
                        <Text style={{ ...style.stockLabel, marginRight: 9 }}>재고수량</Text>
                        <Text style={{ ...style.stockValue, marginRight: 'auto' }}>{Util.toPrice(item.StockCount)}</Text>
                        <Text style={{ ...style.stockLabel, marginLeft: 'auto' }}>재고금액</Text>
                        <Text style={{ ...style.stockValue, marginLeft: 9 }}>{Util.toPrice(item.StockAmount)}</Text>
                    </View>
                    <View style={style.detail}>
                        <View>
                            <View style={style.detailBadge}>
                                <Text style={style.detailBadgeText}>{item.StoredCount}</Text>
                            </View>
                            <Text style={style.detailBadgeLabel}>입고</Text>
                        </View>
                        <View>
                            <View style={style.detailBadge}>
                                <Text style={style.detailBadgeText}>{item.ReleaseCount}</Text>
                            </View>
                            <Text style={style.detailBadgeLabel}>출고</Text>
                        </View>
                        <View>
                            <View style={style.detailBadge}>
                                <Text style={style.detailBadgeText}>{item.ReleaseLossCount}</Text>
                            </View>
                            <Text style={style.detailBadgeLabel}>조정손실</Text>
                        </View>
                        <View>
                            <View style={style.detailBadge}>
                                <Text style={style.detailBadgeText}>{item.ReleaseReturnCount}</Text>
                            </View>
                            <Text style={style.detailBadgeLabel}>조정반납</Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }
}

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const [ready, setReady] = 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 { showMessage } = useToast();
    const { auth, userinfo } = useAuth(navigation);

    const [searchForm, setSearchForm] = useState({
        FirstClassId: '',
        SecondClassId: '',
        ThirdClassId: '',
        BusinessFieldId: '',
    });

    // 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}
                    initialNumToRender={3}
                    refreshing={refreshing}
                    data={list}
                    style={{ backgroundColor: '#f5f5f5' }}
                    renderItem={({ item, index }) => {
                        return <Item item={item} index={index} />;
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search
                id="material_dailystock"
                api={`api/MaterialDailyStock?siteId=${session.getSiteId()}&businessAuth=${auth.Business}`}
                page={page}
                setPage={setPage}
                limit={50}
                filters={filters}
                sort={{ field: 'SDate', order: 'asc' }}
                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="FmsMaterialWarehouse"
                        siteId={userinfo.SiteId}
                        id="WarehouseId"
                        name="Name"
                        defaultLabel="창고"
                        emptyLabel="전체"
                        useCheck={true}
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'Material.WarehouseId', item.value, 'eq');
                        }}
                        auth={auth}
                    />

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

                    <SearchTitle title="규격" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="규격"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Material.Standard', value, 'cn')}
                    />

                    <SearchTitle title="단위" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="단위"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Material.Unit', value, 'cn')}
                    />

                    <SearchTitle title="날짜" />
                    <DateTimePicker
                        style={{ marginBottom: 5 }}
                        placeholder="시작일"
                        useClear={true}
                        onChange={(newDate) => {
                            filterValue([filters, setFilters], 'Date', Util.toDateString(newDate) + ' 00:00:00', 'ge');
                        }}
                    />
                    <DateTimePicker
                        style={{ marginBottom: 20 }}
                        placeholder="종료일"
                        useClear={true}
                        onChange={(newDate) => {
                            filterValue([filters, setFilters], 'Date', Util.toDateString(newDate) + ' 23:59:59.998', 'le');
                        }}
                    />
                </>
            </Search>
        </BottomTabBarLayout>
    ) : null;
};

// header
Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="일별 입출고 현황" buttons={<SearchIcon id="material_dailystock" />} />,
    };
};

export default Screen;
