import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity } from 'react-native';
import { Search, SearchIcon, Line, TextInput, checkFilter, filterValue, ListStyle, DetailIcon, RightArrow, CreateButton,IconContainerCircleSmall } from '~/Components/Listing/Search';
import session from '~/Utils/session';
import SearchList, { SearchListContainer } from '~/Components/Listing/SearchList';
import EmptyView from '~/Components/Listing/EmptyView';
import { useToast, confirm } from '~/Components/UIControls/Message';
import { usePopup } from '~/Components/UIControls/Popup';
import { Util } from '~/Utils/utils';
import PictureSvg from '~/Assets/Svgs/picture.svg';
import Icon from '~/Components/UIControls/Icon';
import { fetchDelete } from '~/Utils/fetch';
import EmptyLayout from '~/Components/Layouts/EmptyLayout';
import { useAuth } from '~/Components/Hooks';
import ManualHistoryForm from './HistoryForm'
// list item
const Item = ({item, index, onPress=()=>{}, onDelete=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    return (
        <TouchableOpacity onPress={() => { onPress(item) }} 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.fillRounded}}>{`Rev.번호 - ${item.RevisionNo}`}</Text>
                    <Text style={{...ListStyle.textMedium,flex:1,paddingLeft:10}}>{item.UpdatedUserId}</Text>
                    <Text style={{...ListStyle.textLightGray}}>{Util.toDateString(item.UpdatedDate)}</Text>
                </View>
                <View style={{...ListStyle.horizon, flex:1, justifyContent:'space-between', marginTop:5, paddingRight:15}}>
                    <PictureSvg width={20} height={16} />
                    <Text style={{...ListStyle.text, flex:1, marginLeft:10}}>{Util.get(item, 'CmFile.Name')}</Text>
                    <TouchableOpacity onPress={() => {onDelete(item)}}>
                        <Icon iconFamily="AntDesign" iconName="closecircle" color="#9aa3ac" size={40} />
                    </TouchableOpacity>
                </View>
            </View>
        </TouchableOpacity>
    )
}

// list and search
const Screen = ({navigation, siteId, manualId}) => {
    const [ready, setReady] = useState(false);
    const [filters, setFilters] = useState({});
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const { auth } = useAuth(navigation);
    const { openPopup } = usePopup();
    const { showMessage } = useToast();
    
    // 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 onDelete = (item) => {
        let newList = [...list];
        let index = newList.indexOf(item);
        if(index != -1) {
            confirm('삭제','삭제하시겠습니까?', async () => {
                try {
                    await fetchDelete(`api/app/ManualHistory/${item.SiteId}/${item.ManualId}/${item.HistoryId}`);

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

    return (
        ready ? 
        <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}  
                            onPress={(item) => {
                                openPopup(ManualHistoryForm, {
                                    refreshList: refreshList,
                                    siteId: siteId, 
                                    manualId: manualId,
                                    historyId : item.HistoryId,
                                    isView : true,
                                    isCreate : false ,
                                    auth:auth,                                  
                                }, (results) => {
                                    setPage('refresh-'+Math.random());
                                });
                            }}/>
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            {auth.Update && <CreateButton onPress={() => {
                console.log(manualId);
                openPopup(ManualHistoryForm, {
                    refreshList: refreshList,
                    siteId: siteId, 
                    manualId: manualId,
                    historyId : 0,
                    isView : false,
                    isCreate : true,
                    auth:auth,
                }, (results) => {
                    setPage('refresh-'+Math.random());
                });
            }} /> }
            </SearchListContainer>

            <Search id="manual-history" api={`api/app/ManualHistory?siteId=${siteId}&manualId=${manualId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'HistoryId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} />
        </EmptyLayout> 
        : null
    );
};

export default Screen;