import React, { useState, useEffect, useCallback, useRef, useLayoutEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Styled from 'styled-components/native';
import { Text, View, TouchableOpacity, Modal, Keyboard, BackHandler } from 'react-native';
import { showCameraAction } from '~/GlobalReducers/camera';
import { Camera } from 'expo-camera';
import Theme from 'Themes';
import Icon from './Icon';

const Container = Styled.View`
    flex: 1;
    background-color: black;
`;
const MessageContainer = Styled.View`
    flex: 1;
    align-items: center;
    justify-content: center;
`;
const Message = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    font-size: 20;
    line-height: 25;
    letter-spacing: -1.0;
    color: white;
`;
const Content = Styled.View`
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: flex-end;
    background-color: transparent;
`;
const ButtonContainer = Styled.View`
    height: 200px;
    width: 100%;
    background-color: transparent;
    flex-direction: row;
    align-items: center;
    justify-content: center;
`;
const ButtonBackground = Styled.View`
    position: absolute;
    left: 0; bottom: 0;
    height: 200px;
    width: 100%;
    background-color: black;
    opacity: 0.5;
`;
const TakePictureButton = Styled.TouchableOpacity`
    margin-left: 40px;
    width: 80px;
    height: 80px;
    border-radius: 40px;
    background-color: white;
    overflow: hidden;
    opacity: 0.6;
`;
const FlipButton = Styled.TouchableOpacity`
    width: 80px;
    height: 80px;
    border-radius: 40px;
    background-color: white;
    overflow: hidden;
    justify-content: center;
    align-items: center;
    opacity: 0.6;
`;


export const CameraProvider = () => {
    const camera = useSelector(({GlobalCamera}) => GlobalCamera.camera);
    const dispatch = useDispatch();
    const showCamera = useCallback((payload) => dispatch(showCameraAction(payload)), []);
    const backHandler = useRef(null);

    const [hasPermission, setHasPermission] = useState(null);
    const [type, setType] = useState(Camera.Constants.Type.back);
    const cameraRef = useRef(null);

    if(camera.show) {
        Keyboard.dismiss();
    }

    useEffect(() => {
        if(camera.show) {
            (async () => {
                const { status } = await Camera.requestPermissionsAsync();
                setHasPermission(status === 'granted');
            })();
        }
    }, [camera]);
  
    return (
        <Modal visible={camera.show} animationType="fade" transparent={false} onRequestClose={() => {
            camera.onCancel();
            showCamera({
                show: false,
                onTakePicture: camera.onTakePicture,
                onCancel: camera.onCancel
            });
        }}>
            <Container>
                {hasPermission ? (
                    <Camera style={{ flex: 1 }} type={type} ref={cameraRef} ratio="16:9">
                        <Content>
                            <ButtonBackground />
                            <ButtonContainer>
                                <FlipButton onPress={() => {
                                    setType(
                                        type === Camera.Constants.Type.back
                                        ? Camera.Constants.Type.front
                                        : Camera.Constants.Type.back
                                    );
                                }}>
                                    <Icon iconFamily="AntDesign" iconName="swap" size={60} color="black" />
                                </FlipButton>
                                <TakePictureButton onPress={async () => { 
                                    let picture = await cameraRef.current.takePictureAsync(); 
                                    camera.onTakePicture(picture);
                                    showCamera({
                                        show: false,
                                        onTakePicture: camera.onTakePicture
                                    });
                                }} />
                            </ButtonContainer>
                        </Content>
                    </Camera>
                ) : (
                    <MessageContainer>
                        <Message>카메라 접근권한이 없습니다.</Message>
                        <Message>접근권한을 허용해 주세요.</Message>
                    </MessageContainer>
                )}
            </Container>
        </Modal>
    );
}