import React, { Fragment, useState, useEffect } from 'react';
import session from '~/Utils/session';
import { Util } from '~/Utils/utils';
import { PopupLayout, useLayoutAction } from '~/Components/Layouts/PopupLayout';
import { PrimaryButton, DefaultButton } from '~/Components/Listing/Search';
import { DefaultAction } from '~/Components/UIControls/Popup/Context';
import { View, Text, TouchableOpacity } from 'react-native';
import SearchList, { SearchListContainer } from '~/Components/Listing/SearchList';
import Theme from '~/Themes';
import EmptyView from '~/Components/Listing/EmptyView';

const numColumns = 5;
const itemHeight = Math.floor(Util.getScreenWidth() / numColumns);

const Item = ({item, index, onPress=(item)=>{}}) => {

    const SvgIcon = item.Svg;

    return (
        <View style={{flex:1, height:itemHeight, alignItems:'center', justifyContent:'center'}}>
            {SvgIcon && (
                <TouchableOpacity style={{
                    width:'85%', height:'85%', 
                    borderWidth:1, borderColor:Theme.COLORS.READONLY_BORDER, borderRadius:5,
                    alignItems:'center', justifyContent:'center'
                }} onPress={() => { onPress(item) }}>
                    <SvgIcon width={'70%'} height={'70%'} />
                </TouchableOpacity>
            )}
        </View>
    )
}

export default Screen = ({popup=DefaultAction}) => {
    const [loading, setLoading] = useState(false);
    const [list] = useState(Util.convertGridData([...Util.svg('/icons/gray', '[]'), ...Util.svg('/icons/color', '[]')], numColumns));

    // mount
    useEffect(() => {
        load();
    }, []);

    // search
    const load = async () => {
        setLoading(true);
        await session.load();
        setLoading(false);
    }

    // header action handler
    const actionHandler = (action, parameter = {}) => {
        const actions = {
            onClose: () => {
                popup.close();
            },
            onSelect: () => {
            },
        }
        actions[action]();
    }

    return ( 
        <PopupLayout title="아이콘 선택" header={Header} actionHandler={actionHandler}>
            <SearchListContainer style={{padding:10}}>
                <SearchList data={list} refreshing={loading} numColumns={numColumns}
                    renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onPress={() => {
                                popup.select({...item});
                            }} />
                        )
                    }}
                />
            </SearchListContainer>
        </PopupLayout>
    );
};

const Header = () => {
    const { callAction } = useLayoutAction();

    return (
        <Fragment>
            <DefaultButton onPress={() => { callAction('onClose') }}>닫기</DefaultButton>
        </Fragment>
    )
}
