import React, { Fragment, useState, useRef, useEffect, useLayoutEffect } from 'react';
import Styled from 'styled-components/native';
import SearchList, { SearchListContainer } from '~/Components/Listing/SearchList';
import EmptyView from '~/Components/Listing/EmptyView';
import { ListStyle, Search, CreateButton } from '~/Components/Listing/Search';
import EmptyLayout from '~/Components/Layouts/EmptyLayout';
import { Util } from '~/Utils/utils';
import { View, Text } from 'react-native';
import FileSvg from '~/Assets/Svgs/file_text.svg';
import WorkHistoryForm from './WorkHistoryForm';
import { usePopup } from '~/Components/UIControls/Popup';
import { TouchableOpacity } from 'react-native-gesture-handler';

const Item = ({item, index, onPress=()=>{}}) => {
    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}}>
                <Text style={{...ListStyle.textLightGray}}>
                    {Util.getDateString(item, "CheckDate")}
                </Text>
                <Text style={{...ListStyle.text, marginBottom:10}}>
                    {Util.get(item, "TextResult")}
                </Text>
                {item.CmFile1 != null && (
                    <View style={{...ListStyle.horizon}}>
                        <FileSvg width={10} height={13} />
                        <Text style={{...ListStyle.textLightGray, color:'#0b83e6', marginLeft:10}}>{Util.get(item, "CmFile1.Name")}</Text>
                    </View>
                )}
                {item.CmFile2 != null && (
                    <View style={{...ListStyle.horizon}}>
                        <FileSvg width={10} height={13} />
                        <Text style={{...ListStyle.textLightGray, color:'#0b83e6', marginLeft:10}}>{Util.get(item, "CmFile2.Name")}</Text>
                    </View>
                )}
            </View>
        </TouchableOpacity>
    )
}

export default WorkHistory = ({siteId, workRequestId, startDate, endDate, editable=true, creatable=true, auth, onCallback=(action)=>{}}) => {
    const [list, setList] = useState(null);
    const [refreshing, setRefreshing] = useState(false);
    const [page, setPage] = useState(1);
    const { openPopup } = usePopup();

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

    // search events...
    const start = () => {
        setRefreshing(true);
    }
    const success = (data, append) => {
        setList(data);
        setRefreshing(false);
    }
    const fail = (e) => {
        showMessage(e.message);
        setRefreshing(false);
    }

    const popupCallback = (result) => {
        console.log('popup result - ', result);
        if(result && (result.IsComplete || result.IsHold)) {
            onCallback('close');
        } else {
            onCallback('refresh');
            setPage('refresh-'+Math.random());
        }
    }
    
    return (
        <EmptyLayout>
            <SearchListContainer>
                <SearchList data={list} refreshing={refreshing} page={page} pages={1} setPage={setPage}
                    renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onPress={(item) => {
                                openPopup(WorkHistoryForm, {
                                    siteId: siteId, 
                                    workRequestId: workRequestId,
                                    startDate: startDate,
                                    checkItemId: item.CheckItemId,
                                    readonly: !editable,
                                    auth: auth,
                                }, (result) => {
                                    popupCallback(result);
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && editable && creatable ? (
                    <CreateButton onPress={() => {
                        openPopup(WorkHistoryForm, {
                            siteId: siteId, 
                            workRequestId: workRequestId,
                            startDate: startDate,
                            endDate: endDate,
                            auth: auth,
                        }, (result) => {
                            popupCallback(result);
                        });
                    }} />
                ) : null}
            </SearchListContainer>

            <Search id="work-result-history" api={`api/app/WorkResult/CheckItems?siteId=${siteId}&workRequestId=${workRequestId}`} 
                    page={page} setPage={setPage} sort={{field:'CheckItemId', order:'asc'}} 
                    onStart={start} onSuccess={success} onFailure={fail} />
        </EmptyLayout> 
    )
}