import React, { Fragment, useState, useRef, useEffect, useLayoutEffect } from 'react';
import Styled from 'styled-components/native';
import EmptyLayout from '~/Components/Layouts/EmptyLayout';
import EmptyView from '~/Components/Listing/EmptyView';
import SearchList, { SearchListContainer } from '~/Components/Listing/SearchList';
import { Search, ListStyle } from '~/Components/Listing/Search';
import { View, TouchableOpacity, Text } from 'react-native';
import session from '~/Utils/session';
import { useToast } from '~/Components/UIControls/Message';
import { Util } from '~/Utils/utils';

const Item = ({item, index, onPress=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;

    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff')
        }}>
            <View style={{...ListStyle.vertical, flex:1}}>
                <Text style={{...ListStyle.textMedium}}>
                    {Util.get(item, "Name")}
                </Text>
                <Text style={{...ListStyle.textLightGray}}>
                    {Util.get(item, "Standard")}
                </Text>
            </View>
            <Text style={{...ListStyle.circleLarge, marginRight:15}}>
                수량{"\n"}{Util.get(item, "MaterialCount")}
            </Text>
        </TouchableOpacity>
    )
}

export default Materials = ({siteId, workRequestId}) => {
    const [ready, setReady] = useState(false);
    const [list, setList] = useState(null);
    const [refreshing, setRefreshing] = useState(false);
    const { showMessage } = useToast();

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

    // search events...
    const start = () => {
        setRefreshing(true);
    }
    const success = (data, append) => {
        setList(data);
        setRefreshing(false);
    }
    const fail = (e) => {
        showMessage(e.message);
        setRefreshing(false);
    }
    
    return (
        ready ? 
        <EmptyLayout>
            <SearchListContainer>
                <SearchList data={list} refreshing={refreshing} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search id="work-result-materials" api={`api/app/WorkResult/Materials?siteId=${siteId}&workRequestId=${workRequestId}`} 
                    sort={{field:'OrderDate', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} />
        </EmptyLayout> 
        : null
    )
}