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: 14,
        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.stock}>
                        {this.props.config.UseMaterialReasonableStockCount && (
                            <>
                                <Text style={{ ...style.stockLabel, marginRight: 9 }}>적정재고량</Text>
                                <Text style={{ ...style.stockValue, marginRight: 'auto' }}>{Util.toPrice(item.ReasonableStockCount)}</Text>
                            </>
                        )}
                        {this.props.UseMaterialReasonableStockCount && !this.props.UseMaterialShortStock && (
                            <>
                                <Text style={{ ...style.stockLabel, marginLeft: 'auto' }}>부족수량</Text>
                                <Text style={{ ...style.stockValue, marginLeft: 9 }}>{Util.toPrice(item.InsufficientStock)}</Text>
                            </>
                        )}
                    </View>
                </View>
            </TouchableOpacity>
        );
    }
}

const TabHeaderContainer = Styled.View`
    flex-direction: column;
    padding: 15px;
    background-color: white;
`;

const TabTitleGroupContainer = Styled.View`
    flex-direction: row;
    border: 1px solid #dedede;
`;
const TabTitleContainer = Styled.TouchableOpacity`
    flex: 1;
    height: 45;
    align-items: center;
    justify-content: center;
`;
const TabTitleText = Styled.Text`
    font-family: ${Theme.Fonts.Medium};
    font-size: 18;
    line-height: 24;
    letter-spacing: -1.6;
`;

const ListTab = ({ onClick }) => {
    const [tab, setTab] = useState('daily');

    return <></>;

    return (
        <TabHeaderContainer>
            <TabTitleGroupContainer>
                <TabTitleContainer
                    onPress={() => {
                        setTab('daily');
                        onClick('daily');
                    }}
                    style={{ backgroundColor: tab == 'daily' ? '#9aa3ac' : 'white' }}
                >
                    <TabTitleText style={{ color: tab == 'daily' ? 'white' : '#9aa3ac' }}>일별</TabTitleText>
                </TabTitleContainer>
                <TabTitleContainer
                    onPress={() => {
                        setTab('monthly');
                        onClick('monthly');
                    }}
                    style={{ backgroundColor: tab == 'monthly' ? '#9aa3ac' : 'white' }}
                >
                    <TabTitleText style={{ color: tab == 'monthly' ? 'white' : '#9aa3ac' }}>월별</TabTitleText>
                </TabTitleContainer>
            </TabTitleGroupContainer>
        </TabHeaderContainer>
    );
};

// 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 [api, setApi] = useState(`/api/MaterialStock?siteId=${session.getSiteId()}`);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const { showMessage } = useToast();
    const { auth, userinfo, config } = 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());
    };

    const onListTabClick = (value) => {
        if (value == 'monthly') {
            setApi(`api/app/MaterialMonthlyStock?siteId=${session.getSiteId()}&businessAuth=${auth.Business}`);
        } else {
            setApi(`api/app/MaterialDailyStock?siteId=${session.getSiteId()}&businessAuth=${auth.Business}`);
        }
    };

    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} config={config} />;
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                    ListHeaderComponent={<ListTab onClick={onListTabClick} />}
                />
            </SearchListContainer>

            <Search
                id="material_dailystock"
                api={api}
                page={page}
                setPage={setPage}
                limit={50}
                filters={filters}
                sort={{ field: 'Date', 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: 5 }}
                        entity="FmsMaterialCodeClass"
                        defaultLabel="분류1"
                        emptyLabel="전체"
                        id="MaterialClassId"
                        name="Name"
                        where={`ParentMaterialClassId IS NULL`}
                        useCheck={true}
                        onChange={(item) => {
                            setSearchForm({
                                ...searchForm,
                                'Material.FirstClassId': item.value,
                                'Material.SecondClassId': '',
                                'Material.ThirdClassId': '',
                            });
                            filterValue([filters, setFilters], 'Material.FirstClassId', item.value, 'eq');
                        }}
                    />
                    <EntitySelect
                        style={{ marginBottom: 5 }}
                        entity="FmsMaterialCodeClass"
                        defaultLabel="분류2"
                        emptyLabel="전체"
                        id="MaterialClassId"
                        name="Name"
                        where={`ParentMaterialClassId = '${searchForm.FirstClassId}'`}
                        useCheck={true}
                        onChange={(item) => {
                            setSearchForm({ ...searchForm, 'Material.SecondClassId': item.value, 'Material.ThirdClassId': '' });
                            filterValue([filters, setFilters], 'Material.SecondClassId', item.value, 'eq');
                        }}
                    />
                    <EntitySelect
                        style={{ marginBottom: 20 }}
                        entity="FmsMaterialCodeClass"
                        defaultLabel="분류3"
                        emptyLabel="전체"
                        id="MaterialClassId"
                        name="Name"
                        where={`ParentMaterialClassId = '${searchForm.SecondClassId}'`}
                        useCheck={true}
                        onChange={(item) => {
                            setSearchForm({ ...searchForm, 'Material.ThirdClassId': item.value });
                            filterValue([filters, setFilters], 'Material.ThirdClassId', item.value, 'eq');
                        }}
                    />

                    <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')}
                    />
                </>
            </Search>
        </BottomTabBarLayout>
    ) : null;
};

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

export default Screen;
