import React, { useState, useEffect, Fragment, useRef } from 'react';
import Styled from 'styled-components/native';
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';
import Theme from '~/Themes';
import Form from '~/Components/Form';
import { Svg } from '~/Components/UIControls/Svg';
import { Util } from '~/Utils/utils';
import session from '~/Utils/session';
import EmptyLayout from '~/Components/Layouts/EmptyLayout';

const MenuBackground = Styled.View`
    position: absolute;
    left:0; top:0; right:0; bottom:0;
    background-color: white;
    opacity: 0.5;
`;
const MenuOuterContainer = Styled.View`
    position: absolute;
    left:0; top:0; right:0; bottom:0;
    align-items: center;
    justify-content: center;
`;
const MenuContainer = Styled.View`
    width: 220px;
    border-radius: 9px;
    background-color: #000419;
    opacity: 0.8;
    overflow: hidden;
`;
const MenuHeader = Styled.View`
    width: 100%;
    height: 40px;
    flex-direction: column;
    justify-content: center;
    padding-left: 15px;
    border-bottom-width: 1px;
    border-color: #ffb801;
`;
const MenuTitle = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    font-size: 12;
    line-height: 17;
    color: white;
`;
const MenuContent = Styled.ScrollView`
    width: 100%;
    max-height: 400px;
`;
const ItemContainer = Styled.View`
    width: 100%;
    align-items: center;
    justify-content: center;
    padding-top:40px;
    padding-bottom:40px;
`;
const Item = Styled.TouchableOpacity`
    width: 72px;
    height: 72px;
    border: 1px solid white;
    border-radius: 6px;
    margin-bottom: 8px;
    overflow: hidden;
    align-items: center;
    justify-content: center;
`;
const ItemText = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    font-size: 10;
    line-height: 14;
    color: white;
`;

const Screen = (props) => {
    const navigation = props.navigation;
    const [hasPermission, setHasPermission] = useState(null);
    const [qrcode, setQRCode] = useState({ scanned: false, qrcode: '' });
    const { showMessage } = useToast();

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

    const handleBarCodeScanned = ({ type, data }) => {
        if (!qrcode.scanned) {
            setQRCode({ scanned: true, qrcode: data });
        }
    };

    const actionHandler = (action) => {
        const actions = {
            close: () => {
                console.log('close qrscan...');
                navigation.navigate('Dashboard');
            },
        };
        actions[action]();
    };

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

    return (
        <EmptyLayout>
            <Form.Container style={{ display: 'none' }} onAction={actionHandler} />
            {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>
            )}
            {qrcode.scanned ? (
                <Fragment>
                    <MenuBackground />
                    <MenuOuterContainer>
                        <MenuContainer>
                            <MenuHeader>
                                <MenuTitle>QR:{qrcode.qrcode}</MenuTitle>
                            </MenuHeader>
                            <MenuContent>
                                <ItemContainer>
                                    <Item
                                        onPress={() => {
                                            Util.navigate(navigation, session.getMenu('/Facility/Facility'), null, {
                                                qrcode: qrcode.qrcode,
                                            });
                                        }}
                                    >
                                        <Svg path="/qrscan/facility" width={25} height={25} />
                                        <ItemText>설비조회</ItemText>
                                    </Item>
                                    <Item
                                        onPress={() => {
                                            Util.navigate(navigation, session.getMenu('/Energy/ManualMeter'), null, {
                                                qrcode: qrcode.qrcode,
                                            });
                                        }}
                                    >
                                        <Svg path="/qrscan/manual_meter" width={25} height={25} />
                                        <ItemText>수검침 등록</ItemText>
                                    </Item>
                                </ItemContainer>
                            </MenuContent>
                        </MenuContainer>
                    </MenuOuterContainer>
                </Fragment>
            ) : null}
        </EmptyLayout>
    );
};

// header
Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => (
            <Header
                navigation={navigation}
                title="QR코드"
                buttons={<Form.ActionButton navigation={navigation} type="primary" action="close" title="닫기" />}
            />
        ),
    };
};

export default Screen;
