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 },
    headerName: { fontSize: 16, color: '#000' },
    headerDetail: { marginLeft: 15, flexDirection: 'column', flex: 1 },
    headerUnit: { color: '#b9bac4', fontSize: 14 },
    info: { padding: 15, paddingVertical: 0 },
    infoContainer: { flexDirection: 'row', alignItems: 'center' },
    infoLabel: { color: '#b9bac4', fontSize: 16, marginRight: 'auto' },
    infoValue: { color: '#b9bac4', fontSize: 16, marginLeft: 'auto' },
    headerState: { backgroundColor: '#000', borderRadius: 15, width: 66, height: 30, alignItems: 'center', justifyContent: 'center' },
    headerStateText: { color: 'white', fontFamily: Theme.Fonts.Regular, fontSize: 16 },
    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-around' },
    detailBadge: {
        width: 70,
        height: 35,
        borderRadius: 60,
        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 },
});

const stateColor = (state) => {
    const colors = {
        입고: '#0b83e6',
        대여: '#ffb801',
        반납: '#0eb118',
        손실: '#f2335c',
    };
    return colors[state] ? colors[state] : '#000';
};

// list item
class Item extends React.PureComponent {
    render() {
        const { item, index, config } = this.props;
        const zebra = index % 2 == 0 ? true : false;
        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.infoContainer}>
                                <View style={style.headerBadge}>
                                    <Text style={style.headerBadgeText}>{item.EquipmentTypeName}</Text>
                                </View>
                                <Text style={style.headerName}>{item.Name}</Text>
                            </View>
                            <Text style={style.headerUnit}>{[item.Standard, item.Unit].filter((e) => e).join('/')}</Text>
                        </View>
                        <View>
                            <View style={{ ...style.headerBadge}}>
                                <Text style={style.headerBadgeText}>{item.EquipmentStateTypeName}</Text>
                            </View>
                        </View>
                    </View>
                    <View style={style.info}>
                        <View style={style.infoContainer}>
                            <Text style={style.infoLabel}>입고일</Text>
                            <Text style={style.infoValue}>{Util.toDateString(item.AddDate, '', '.')}</Text>
                        </View>
                        {config.UseEquipmentRent && (
                            <Fragment>
                                <View style={style.infoContainer}>
                                    <Text style={style.infoLabel}>대여자</Text>
                                    <Text style={style.infoValue}>{item.RentUserName}</Text>
                                </View>
                                <View style={style.infoContainer}>
                                    <Text style={style.infoLabel}>대여일</Text>
                                    <Text style={style.infoValue}>{Util.toDateString(item.RentDate, '', '.')}</Text>
                                </View>
                                <View style={style.infoContainer}>
                                    <Text style={style.infoLabel}>반납예정일</Text>
                                    <Text style={style.infoValue}>{Util.toDateString(item.ReturnDueDate, '', '.')}</Text>
                                </View>
                                <View style={style.infoContainer}>
                                    <Text style={style.infoLabel}>반납일</Text>
                                    <Text style={style.infoValue}>{Util.toDateString(item.ReturnFixDate, '', '.')}</Text>
                                </View>
                            </Fragment>
                        )}
                    </View>
                    <View style={style.detail}>
                        <View>
                            <View style={style.detailBadge}>
                                <Text style={style.detailBadgeText}>{Util.toPrice(item.StoredCount)}</Text>
                            </View>
                            <Text style={style.detailBadgeLabel}>입고수량</Text>
                        </View>
                        {config.UseEquipmentRent && (
                            <Fragment>
                                <View>
                                    <View style={style.detailBadge}>
                                        <Text style={style.detailBadgeText}>{Util.toPrice(item.RentCount)}</Text>
                                    </View>
                                    <Text style={style.detailBadgeLabel}>대여수량</Text>
                                </View>
                                <View>
                                    <View style={style.detailBadge}>
                                        <Text style={style.detailBadgeText}>{Util.toPrice(item.ReturnCount)}</Text>
                                    </View>
                                    <Text style={style.detailBadgeLabel}>반납수량</Text>
                                </View>
                            </Fragment>
                        )}
                        <View>
                            <View style={style.detailBadge}>
                                <Text style={style.detailBadgeText}>{Util.toPrice(item.LossCount)}</Text>
                            </View>
                            <Text style={style.detailBadgeLabel}>손실수량</Text>
                        </View>
                        {/*
                        <View>
                            <View style={style.detailBadge}>
                                <Text style={style.detailBadgeText}>{Util.toPrice(item.CurrentStockCount)}</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 [api, setApi] = useState(`api/app/MaterialDailyStock?siteId=${session.getSiteId()}`);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const { showMessage } = useToast();
    const { auth, config, userinfo } = useAuth(navigation);

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

    // 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()}`);
        } else {
            setApi(`api/app/MaterialDailyStock?siteId=${session.getSiteId()}`);
        }
    };

    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} />}
                />
            </SearchListContainer>

            <Search
                id="equipment_history"
                api={`api/app/EquipmentHistory?siteId=${session.getSiteId()}`}
                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="FmsEquipmentCodeStateType"
                        id="EquipmentStateTypeId"
                        where={!config.UseEquipmentRent ? 'EquipmentStateTypeId IN(1,5)' : ''}
                        defaultLabel=""
                        emptyLabel="전체"
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'EquipmentStateTypeId', item.value, 'eq');
                        }}
                    />

                    <SearchTitle title="공기구분류" />
                    <EntitySelect
                        style={{ marginBottom: 20 }}
                        entity="FmsEquipmentCodeType"
                        id="EquipmentTypeId"
                        defaultLabel=""
                        emptyLabel="전체"
                        useCheck={true}
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'FmsEquipment.EquipmentTypeId', item.value, 'eq');
                        }}
                    />

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

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

// header
Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="공기구 이력조회" buttons={<SearchIcon id="equipment_history" />} />,
    };
};

export default Screen;
