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 Header from '~/Components/Layouts/Header';
import { Search, SearchIcon, Line, TextInput, checkFilter, filterValue, ListStyle, DetailIcon, RightArrow, IconContainerCircleSmall, CreateButton } 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, confirm } from '~/Components/UIControls/Message';
import { DateTimePicker } from '~/Components/UIControls/DateTimePicker';
import Input from '~/Components/UIControls/Input';
import { Util } from '~/Utils/utils';
import PictureSvg from '~/Assets/Svgs/picture.svg';
import Icon from '~/Components/UIControls/Icon';
import produce from 'immer';
import { fetchDelete } from '~/Utils/fetch';
import EmptyLayout from '~/Components/Layouts/EmptyLayout';
import { useAuth } from '~/Components/Hooks';
import UploadFile from '~/Components/UIControls/UploadFile';

// list item
const Item = ({item, index, auth, onDelete=()=>{}, onPress=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    return (
        <View style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <View style={{...ListStyle.vertical, flex:1}}>
                <View style={{...ListStyle.horizon, width:'100%', justifyContent:'space-between', paddingRight:15}}>
                    <Text style={{...ListStyle.textMedium}}>{item.UpdateUserName}</Text>
                    <Text style={{...ListStyle.textLightGray}}>{Util.toDateString(item.UpdatedDate)}</Text>
                </View>
                <View style={{...ListStyle.horizon, flex:1, justifyContent:'space-between', marginTop:5, paddingRight:15}}>
                    <UploadFile defaultFile={item.CmFile} editable={false} 
                        style={{paddingRight:20}} 
                        textContainerStyle={{borderWidth:0, paddingLeft:0}}
                        fileContainerStyle={{borderWidth:0, borderRadius:0, paddingLeft:0, backgroundColor:'white' }}
                        imageContainerStyle={{borderWidth:0, borderRadius:0}} />
                    <TouchableOpacity onPress={() => {onPress(item)}}>
                        <DetailIcon />
                    </TouchableOpacity>
                    {auth.Delete && (
                        <TouchableOpacity onPress={() => {onDelete(item)}}>
                            <Icon iconFamily="AntDesign" iconName="closecircle" color="#9aa3ac" size={40} />
                        </TouchableOpacity>
                    )}
                </View>
            </View>
        </View>
    )
}

// list and search
const Screen = ({navigation, siteId, drawingId}) => {
    const [filters, setFilters] = useState({});
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const { auth, userinfo } = useAuth(navigation);
    const pages = useRef(10);
    const { showMessage } = useToast();

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

    const onDelete = (item) => {
        let newList = [...list];
        let index = newList.indexOf(item);
        if(index != -1) {
            confirm('삭제','삭제하시겠습니까?', async () => {
                try {
                    await fetchDelete(`api/DrawingHistory/${item.SiteId}/${item.DrawingId}/${item.HistoryId}`);

                    newList.splice(index, 1);
                    setList(newList);
                    showMessage('삭제되었습니다.');
                } catch(error) {
                    console.log(error.message);
                    showMessage(error.message);
                }
            });
        }
    }

    const refreshList = () => {
        setPage('refresh-' + Math.random());
    }

    return (
        <EmptyLayout>
            <SearchListContainer>
                <SearchList page={page} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onDelete={onDelete} auth={auth} onPress={() => {
                                navigation.navigate('HistoryForm', {
                                    refreshList: refreshList,
                                    action: Form.VIEW, 
                                    siteId: item.SiteId, 
                                    drawingId: item.DrawingId, 
                                    historyId: item.HistoryId, 
                                    auth: auth,
                                    userinfo: userinfo,
                                });
                            }}/>
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (
                    <CreateButton onPress={() => {
                        navigation.navigate('HistoryForm', {
                            refreshList: refreshList,
                            action: Form.CREATE, 
                            siteId: siteId, 
                            drawingId: drawingId,
                            historyId: 0,
                            auth: auth,
                            userinfo: userinfo,
                        });
                    }} />
                )}
            </SearchListContainer>

            <Search id="drawing-history" api={`api/DrawingHistory?siteId=${siteId}&drawingId=${drawingId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'RevisionNo', order:'asc'}}
                    onStart={start} onSuccess={success} onFailure={fail} />
        </EmptyLayout> 
    );
};

export default Screen;