import React, { useState, useEffect, Fragment } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import { useToast } from '~/Components/UIControls/Message';
import { PopupLayout, useLayoutAction } from '~/Components/Layouts/PopupLayout';
import { DefaultButton, ListStyle } from '~/Components/Listing/Search';
import { DefaultAction } from '~/Components/UIControls/Popup/Context';

export default Screen = ({ popup = DefaultAction }) => {
    const [hasPermission, setHasPermission] = useState(null);
    const { showMessage } = useToast();

    useEffect(() => {
        (async () => {
            const { status } = await BarCodeScanner.requestPermissionsAsync();
            setHasPermission(status === 'granted');
        })();
    }, []);

    const handleBarCodeScanned = ({ type, data }) => {
        popup.select(data);
    };

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

    let message = '';
    if (hasPermission === null) {
        message = '카메라 접근권한을 허용해 주세요.';
    }
    if (hasPermission === false) {
        message = '카메라 접근권한이 없습니다.';
    }

    return (
        <EmptyLayout title="QR코드 스캔" header={Header} headerProps={{ callAction: actionHandler }} style={{}}>
            {hasPermission ? (
                <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'flex-end' }}>
                    <BarCodeScanner onBarCodeScanned={handleBarCodeScanned} style={StyleSheet.absoluteFillObject} />
                </View>
            ) : (
                <View style={{ width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center' }}>
                    <Text style={[ListStyle.textMediumLarge, { fontSize: 25, lineHeight: 35 }]}>{message}</Text>
                </View>
            )}
        </EmptyLayout>
    );
};

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