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 from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { useLayoutAction, PopupLayout } from '~/Components/Layouts/PopupLayout';
import Icon from '~/Components/UIControls/Icon';
import { Util } from '~/Utils/utils';

// 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, 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <View style={{ ...ListStyle.vertical, width:'100%' }}>
                <View style={{ ...ListStyle.horizon,width:'100%',justifyContent:"space-between"}}>
                    <Text style={{ ...ListStyle.text,color:"#0b83e6" }}>
                        {Util.get(item, "AccidentTypeName")}
                    </Text>
                    <Text style={{ ...ListStyle.text,paddingLeft:10,flex:1 }}>
                        {Util.get(item, "Name")}
                    </Text>
                </View>
                <View style={{ ...ListStyle.horizon, width:'100%' }}>
                    <View style={{ ...ListStyle.vertical, flex:1 }}>
                        <View style={{ ...ListStyle.horizon,width:'100%',marginTop:10, justifyContent:"space-between"}}>
                            <Text style={{ ...ListStyle.textGray, lineHeight: 18 }}>
                                {'사고발생일'}
                            </Text>
                            <Text style={{ ...ListStyle.textGray, textAlign: "left", paddingRight:15, lineHeight: 18  }}>
                                {Util.get(item, "Dates.StartDate")}
                            </Text>
                        </View>
                        <View style={{ ...ListStyle.horizon,width:'100%',marginTop:5, justifyContent:"space-between"}}>
                            <Text style={{ ...ListStyle.textGray, lineHeight: 18 }}>
                                {'조치완료일'}
                            </Text>
                            <Text style={{ ...ListStyle.textGray, textAlign: "left", paddingRight:15, lineHeight: 18  }}>
                                {Util.get(item, "Dates.EndDate")}
                            </Text>
                        </View>
                    </View>
                    <View style={{marginRight:15}}>
                        {checked ? (
                            <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-marked" size={35} color="#3b86ff" />
                        ): (
                            <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-blank-outline" size={35} color="#3b86ff" />
                        )}
                    </View>
                </View>
            </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();

    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;
                }
                console.log('사고추가 : ', checkedItems.current);
                popup.select(checkedItems.current);
            }
        }
        actions[action]();
    }

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

    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="accident-popup" api={`api/app/Accident?siteId=${siteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'AccidentId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>

                <SearchTitle title="사고유형" />
                <EntitySelect style={{ marginBottom:5 }} entity="FmsAccidentCodeType"  id="AccidentTypeId" defaultLabel="사고유형" emptyLabel="전체" useCheck={true}
                    onChange={(item) => { 
                        filterValue([filters, setFilters], 'AccidentTypeId', item.value, 'eq');
                    }} />

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

                <SearchTitle title="사고발생일" />
                <DateTimePicker style={{ marginBottom:10 }} placeholder="시작일" useClear={true} onChange={(newDate) => {
                            filterValue([filters, setFilters], 'StartDate', Util.toDateString(newDate) + ' 00:00:00.000', 'ge');}} />
                <DateTimePicker style={{ marginBottom:10 }} placeholder="종료일" useClear={true} onChange={(newDate) => {
                            filterValue([filters, setFilters], 'StartDate', Util.toDateString(newDate) + ' 23:59:59.998', 'le');}} />

                <SearchTitle title="조치완료일" />
                <DateTimePicker style={{ marginBottom:10 }} placeholder="시작일" useClear={true} onChange={(newDate) => {
                            filterValue([filters, setFilters], 'EndDate', Util.toDateString(newDate) + ' 00:00:00.000', 'ge');}} />
                <DateTimePicker style={{ marginBottom:10 }} placeholder="종료일" useClear={true} onChange={(newDate) => {
                            filterValue([filters, setFilters], 'EndDate', Util.toDateString(newDate) + ' 23:59:59.998', 'le');}} />

                </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="accident-popup" />
        </Fragment>
    )
}
