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, CreateButton } from '~/Components/Listing/Search';
import { View, TouchableOpacity, Text } from 'react-native';
import session from '~/Utils/session';
import { useToast, confirm } from '~/Components/UIControls/Message';
import { Util } from '~/Utils/utils';
import { usePopup } from '~/Components/UIControls/Popup';
import Icon from '~/Components/UIControls/Icon';
import Input, { InputFilters } from '~/Components/UIControls/Input';
import { usePrevious } from '~/Components/Hooks';

const Item = ({item, index, editable, onDelete=(item)=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    const [defaultQty] = useState(item.MaterialCount);

    return (
        <View 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, "FmsMaterial.Standard")}
                </Text>
                <Text style={{...ListStyle.textLightGray}}>
                    재고수량 : {item.StockCount}
                </Text>
                <View>
                    <Input defaultValue={defaultQty} style={{height:25, borderRadius:2, paddingLeft:5, paddingRight:5, minWidth:50}} autosize={false}
                        onChangeText={(text) => {
                            const qty = InputFilters.maxNumber(text+'', item.StockCount);
                            item.MaterialCode = qty;
                            console.log('change qty : ', qty);
                        }} keyboardType="decimal-pad" editable={editable} />
                </View>
            </View>
            {editable ? (
                <TouchableOpacity onPress={() => {onDelete(item)}} style={{marginRight:15}}>
                    <Icon iconFamily="AntDesign" iconName="closecircle" color="#9aa3ac" size={40} />
                </TouchableOpacity>
            ) : null}
        </View>
    )
}

export default Materials = ({siteId, workRequestId, materials, setMaterials, editable}) => {
    const [defaultMaterials, setDefaultMaterials] = useState([...materials]);
    const [refreshing, setRefreshing] = useState(false);
    const { openPopup } = usePopup();

    const prevEditable = usePrevious(editable);
    useEffect(() => {
        if(typeof prevEditable !== 'undefined' && !editable) {
            setMaterials([...defaultMaterials]);
        }
    }, [editable]);

    const prevMaterials = usePrevious(materials);
    useEffect(() => {
        if(typeof prevMaterials !== 'undefined' && prevMaterials.length == 0 && materials.length > 0) {
            setDefaultMaterials([...materials]);
        }
    }, [materials]);
    
    const removeItem = (remove) => {
        confirm('제거', '해당 자재사용내역을 목록에서 제거하시겠습니까?', () => {
            const found = materials.find(item => item.MaterialId == remove.MaterialId);
            const index = materials.indexOf(found);
            if(index != -1) materials.splice(index, 1);
            setMaterials([...materials]);
        });
    }

    return (
        <EmptyLayout>
            <SearchListContainer>
                <SearchList data={materials} refreshing={refreshing} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} editable={editable} onDelete={removeItem} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={materials} />}
                />
                {editable && (
                    <CreateButton onPress={() => {
                        openPopup('/Popup/Material/Index', {
                            siteId: siteId,
                        }, (results) => {
                            console.log('material selected...', results);
                            let appendList = [];
                            for(let item of results) {
                                if(materials.find(mat => mat.MaterialId == item.MaterialId)) continue;
                                
                                appendList.push({
                                    SiteId: siteId,
                                    workRequestId: workRequestId,
                                    MaterialId: item.MaterialId,
                                    MaterialCount: item.Qty,
                                    MaterialCode: item.MaterialCode,
                                    StockCount: item.StockCount,
                                    Name: item.Name,
                                    FmsMaterial: item,
                                });
                            }
                            setMaterials([...materials, ...appendList]);
                        });
                    }} />
                )}
            </SearchListContainer>
        </EmptyLayout> 
    )
}