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 { Search, SearchIcon, Line, TextInput, checkFilter, filterValue, ListStyle, DetailIcon, RightArrow, CreateButton, SearchBoxIcon, DefaultButton, PrimaryButton, 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 { DateTimePicker } from '~/Components/UIControls/DateTimePicker';
import Input, { InputFilters } from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { useLayoutAction, PopupLayout } from '~/Components/Layouts/PopupLayout';
import Icon from '~/Components/UIControls/Icon';

// list item
const Item = ({item, index, onChecked=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    const [checked, setChecked] = useState(false);

    return (
        <TouchableOpacity onPress={() => {
            setChecked(!checked);
            onChecked(item, !checked);
        }} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <View style={{...ListStyle.vertical}}>
                <Text style={{...ListStyle.textLightGray}}>
                    <Text>{item.FirstClassName}&nbsp;&nbsp;</Text>
                    {item.SecondClassName && (
                        <Fragment>
                            <RightArrow /><Text>&nbsp;&nbsp;{item.SecondClassName}&nbsp;&nbsp;</Text>
                        </Fragment>
                    )}
                    {item.ThirdClassName && (
                        <Fragment>
                            <RightArrow /><Text>&nbsp;&nbsp;{item.ThirdClassName}</Text>
                        </Fragment>
                    )}
                </Text>
                <View style={{...ListStyle.horizon, marginBottom:10}}>
                    <Text style={{...ListStyle.text}}>{item.Name}</Text>
                    <Text>&nbsp;</Text>
                    {item.Standard ? <Text style={{...ListStyle.text}}>({item.Standard})</Text> : null}
                    {item.Unit ? (
                        <Fragment>
                            <Text style={{...ListStyle.textGray, marginLeft:5, marginRight:5}}>|</Text>
                            <Text style={{...ListStyle.text}}>{item.Unit}</Text>
                        </Fragment>
                    ) : null}
                </View>
                <Text style={{...ListStyle.textLightGray}}>
                    재고수량 : {item.StockCount}
                </Text>
            </View>
            <View style={{marginRight:15}}>
            {checked ? (
                <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-marked" size={25} color="#3b86ff" />
            ): (
                <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-blank-outline" size={25} color="#3b86ff" />
            )}
            </View>
        </TouchableOpacity>
    )
}

// list and search
export default Popup = ({siteId=0, popup=DefaultAction}) => {
    const [filters, setFilters] = useState({});
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const checkedItems = useRef([]);
    const { showMessage } = useToast();

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

    console.log('filters : ', filters);

    // load session when mount...
    useEffect(() => {
    }, []);

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

    // header button handler
    const actionHandler = (action, parameter = {}) => {
        const actions = {
            close: () => {
                console.log('close...');
                popup.close();
            },
            addSelected: () => {
                if(checkedItems.current.length == 0) {
                    Alert.alert("추가할 자재를 선택하세요.");
                    return;
                }
                popup.select(checkedItems.current);
            }
        }
        actions[action]();
    }

    const itemCheckedChange = (item, checked) => {
        if(checked) {
            const findIndex = checkedItems.current.indexOf(item);
            if(findIndex == -1) {
                checkedItems.current.push(item);
            } else {
                checkedItems.current[findIndex] = item;
            }
        } else {
            const index = checkedItems.current.indexOf(item);
            if(index != -1) {
                checkedItems.current.splice(index, 1);
            }
        }
        console.log(checkedItems.current);
    }

    return (
        <PopupLayout title="자재추가" header={Header} actionHandler={actionHandler}>
            <SearchListContainer>
                <SearchList page={page} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onChecked={itemCheckedChange} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search id="material-popup" api={`api/app/Material?siteId=${siteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'Material.MaterialId', order:'asc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="자재분류" />
                    <EntitySelect style={{ marginBottom:5 }} entity="FmsMaterialCodeClass" defaultLabel="분류1" 
                        id="MaterialClassId" name="Name" where={`ParentMaterialClassId IS NULL`} useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                FirstClassId: item.value,
                                SecondClassId: '',
                                ThirdClassId: '',
                            });
                            filterValue([filters, setFilters], 'Material.FirstClassId', item.value, 'eq');
                        }} />
                    <EntitySelect style={{ marginBottom:5 }} entity="FmsMaterialCodeClass" defaultLabel="분류2" 
                        id="MaterialClassId" name="Name" where={`ParentMaterialClassId = '${searchForm.FirstClassId}'`} useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                SecondClassId: item.value,
                                ThirdClassId: '',
                            });
                            filterValue([filters, setFilters], 'Material.SecondClassId', item.value, 'eq');
                        }} />
                    <EntitySelect style={{ marginBottom:20 }} entity="FmsMaterialCodeClass" defaultLabel="분류3" 
                        id="MaterialClassId" name="Name" where={`ParentMaterialClassId = '${searchForm.SecondClassId}'`} useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                ThirdClassId: item.value,
                            });
                            filterValue([filters, setFilters], 'Material.ThirdClassId', item.value, 'eq');
                        }} />

                    <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')} />

                </Fragment>
            </Search>
        </PopupLayout> 
    );
};

const Header = () => {
    const { callAction } = useLayoutAction();

    return (
        <Fragment>
            <PrimaryButton onPress={() => { callAction('addSelected') }}>선택추가</PrimaryButton>
            <DefaultButton onPress={() => { callAction('close') }}>닫기</DefaultButton>
            <SearchBoxIcon style={{marginLeft:5}} id="material-popup" />
        </Fragment>
    )
}
