import React, { useRef,useState,useEffect, useMemo, useCallback } from "react";
import { Dimensions, Image, Platform, ScrollView, StatusBar, Text, TouchableOpacity, View } from "react-native";
import { customCamera,customStyles,GetPageTheme } from "../styles/Global";
import { customCamera_LS} from "../styles/Global_LS";
import { useRoute } from '@react-navigation/native';
import { Camera,useCameraDevices} from 'react-native-vision-camera';
import PropTypes from 'prop-types'; 
import { notify } from "./notify";
import { hasCameraPermission } from "./geolocation";
import { Entypo, MaterialCommunityIcons, MaterialIcons } from "./icons";

import { useOrientation } from "../controller/functions";

function CustomCamera(props){
    const route = useRoute();
    const PageTheme=GetPageTheme(props.DarkTheme,route.name);
    const cameraStyle=customCamera(props.DarkMode,route.name);
    // const [cameraStyle, setCameraStyle] = useState(customCamera(props.DarkMode,route.name));
    const customStyle=customStyles(props.DarkMode,route.name);
    const camera = useRef(null)
    const devices=useCameraDevices();
    const dim=Dimensions.get("window");
    // const [camera,setcamera]=useState(null);
    const [showImage,setshowImage]=useState(false);
    const [imgurl,setimgurl]=useState('');
    const [temp_imgurl,setTemp_imgurl]=useState('');
    const [photoObj,setPhotoObj]=useState({});
    const [isActive,setisActive]=useState(false);
    const [isPhotoTaken,setIsPhotoTaken]=useState(false);
    const [isCameraActive,setIsCameraActive]=useState(false);
    const [activeFlashMode,setActiveFlashMode]=useState('off');
    const [orientation, setOrientation] = useState(useOrientation(dim.width,dim.height));
    const supportsCameraFlipping = useMemo(() => devices.back != null && devices.front != null, [devices.back, devices.front]);
    const [cameraPosition, setCameraPosition] = useState((props.cameraType == 'front'?'front':'back'));
    const device = devices[cameraPosition];


    useEffect(()=>{
        hasCameraPermission();
        Dimensions.addEventListener('change', ({window:{width,height}})=>{
            let or=useOrientation(width,height);
            setOrientation(or);
        });
    },[]);

    useEffect(()=>{
        console.log('showCamera changed:',props.showCamera);
        if(props.showCamera==true){
            showCamera();
        }
        else{
            hideCamera();
        }
    },[props.showCamera]);

    function showCamera() {
        console.log('showCamera customcamera');
        setIsCameraActive(true);
        setisActive(true);
    }

    function hideCamera() {
        setIsCameraActive(false);
        setisActive(false);
        setPhotoObj({});
        setimgurl('');
        setIsPhotoTaken(false);
        setshowImage(true);
        setTemp_imgurl('');
        if(props.onHideCamera!=null && typeof props.onHideCamera=='function')
        {
            props.onHideCamera();
        }
    }

    function closeCamera() {
        setIsCameraActive(false);
    }

    async function takePhoto(){
        if(camera.current!=null && typeof camera.current==='object'){
            const photo = await camera.current.takePhoto({
                // flash: 'on',      
            })
            
            if(photo!=null){
                let path='file://'+photo.path;
                console.log(path);
                let obj={uri:path,width:photo.width,height:photo.height};
                setPhotoObj(obj);
                setTemp_imgurl(path)
                setIsPhotoTaken(true);
            }
            else{
                notify('Something went wrong! Cannot take picture.');
                setisActive(false);
            }
        }
        else{
            notify('Camera not found!.');
            setisActive(false);
        }
        closeCamera();
    }

    async function onRetake(){
        setTemp_imgurl('');
        setIsPhotoTaken(false);
        setshowImage(false);
        setIsCameraActive(true);
        setisActive(true);
    }
    async function onCameraImgOk(){
        let obj=photoObj;
        obj.uri=temp_imgurl;
        setPhotoObj(obj);
        setimgurl(temp_imgurl);
        setisActive(false);
        setIsPhotoTaken(false);
        setshowImage(true);
        setTemp_imgurl('');
        
        if(props.onImageCaptured!=null && typeof props.onImageCaptured=='function'){
            console.log('call onImageCaptured');
            props.onImageCaptured(obj);
        }
        hideCamera();
    }

    function flashOnOff(type=''){
        console.log('setflashmode:',type);
        if(type!='' && type!=null){
            setActiveFlashMode(type);
            if(type=='on'){

            }
            else if(type=='off'){

            }
            else if(type=='auto'){

            }
        }
    }



    function _renderCaptureBtn(){
        return(
        <TouchableOpacity style={cameraStyle.customCamera_capbtn} onPress={()=>{takePhoto();}}>
            <View style={cameraStyle.customCamera_capbtn_Outer}><View style={cameraStyle.customCamera_capbtn_Inner}></View></View>
        </TouchableOpacity>
        )
    }
    function _renderBottomControls(){
        return(
        <View style={cameraStyle.customCamera_bottomBar}>
            {_renderCaptureBtn()}
        </View>
        )
    }

    function _renderCancelBtn(){
        return(
        <TouchableOpacity style={cameraStyle.imgControls_btnCon} onPress={()=>{hideCamera()}}>
            <View style={cameraStyle.imgControls_btn}>
                <MaterialCommunityIcons name='cancel' color={'#fff'} size={18}/>
                <Text style={[cameraStyle.imgControls_btnText,cameraStyle.icbtTop]}>Cancel</Text>
            </View>
        </TouchableOpacity>
        )
    }

    function _renderRetakeBtn(){
        return(
        <TouchableOpacity style={cameraStyle.imgControls_centerBtn} onPress={()=>{onRetake()}}>
            <View style={cameraStyle.imgControls_btn}>  
                <View style={cameraStyle.imgControls_retakeBtn}>
                    <MaterialCommunityIcons name='camera-retake' color={'#000'} size={30}/>
                </View>
                <Text style={[cameraStyle.imgControls_btnText,cameraStyle.icbtTop]}>Retake</Text>
            </View>
        </TouchableOpacity>
        )
    }

    

    function _renderSaveImgBtn(){
        return(
        <TouchableOpacity style={cameraStyle.imgControls_btnCon} onPress={()=>{onCameraImgOk()}}>
            <View style={cameraStyle.imgControls_btn}>
                <MaterialCommunityIcons name='check' color={'#fff'} size={18}/>
                <Text style={[cameraStyle.imgControls_btnText,cameraStyle.icbtTop]}>Ok</Text>
            </View>
        </TouchableOpacity>
        )
    }


    
    function _renderCameraSwapMode() {
        return (
            <TouchableOpacity style={cameraStyle.flashBtn} onPress={() => { onFlipCameraPressed() }}>
                {cameraPosition == 'front' && <MaterialIcons name='flip-camera-ios' color={'#ffe600'} size={24} />}
                {cameraPosition == 'back' && <MaterialIcons name='flip-camera-android' color={'#fff'} size={24} />}
            </TouchableOpacity>
        )
    }

    

    function _renderImageControls(){
        return(
        <View style={cameraStyle.customCamera_bottomBar2}>
            <View style={cameraStyle.imgControls}>
            {_renderCancelBtn()}
            {_renderRetakeBtn()}
            {_renderSaveImgBtn()}
            </View>
        </View>
        )
    }

    function _renderFlashBtn(type='on'){
        return(
        <TouchableOpacity style={cameraStyle.flashBtn} onPress={()=>{flashOnOff(type)}}>
            {type=='on' && <MaterialCommunityIcons name='flash' color={(activeFlashMode=='on'?'#ffe600':'#fff')} size={24}/>}
            {type=='off' && <MaterialCommunityIcons name='flash-off' color={(activeFlashMode=='off'?'#ffe600':'#fff')} size={24}/>}
            {type=='auto' && <MaterialCommunityIcons name='flash-auto' color={(activeFlashMode=='auto'?'#ffe600':'#fff')} size={24}/>}
        </TouchableOpacity>
        )
    }

    function _renderTopControls(){
        return(
            <View style={cameraStyle.topControls}>
                <View style={cameraStyle.topControlsInner}>
                    {_renderFlashBtn('on')}
                    {_renderFlashBtn('off')}
                </View>
            </View>
        )
    }

    const onFlipCameraPressed = useCallback(() => {
        setCameraPosition((p) => (p === 'back' ? 'front' : 'back'));
    }, []);

    function _renderSideControls() {
        
        let enableCameraFlip = props.enableCameraFlip != null ? (props.enableCameraFlip) : false;
        return (
            <View style={(orientation == 'PORTRAIT'? cameraStyle.sideControls:cameraStyle.sideControl)}>
                <View style={cameraStyle.sideControlsInner}>
                    {_renderFlashBtn('on')}
                    {_renderFlashBtn('off')}
                    {supportsCameraFlipping && enableCameraFlip==true &&
                    _renderCameraSwapMode()
                    }
                </View>
            </View>
        )
    }

 

    if(props.showCamera==true && isActive==true){
        return (  
            <View style={cameraStyle.scrollMain}>
            <StatusBar translucent={true} hidden={true}/>
            {
                Platform.OS=='ios' &&
                <View style={cameraStyle.IOS_StatusBar}>
                </View>
            }
            {device!=null && isActive &&
                <View style={cameraStyle.customCamera_Wrap}>
                {console.log('activeFlashMode:',activeFlashMode)}
                <Camera
                    ref={camera}
                    style={[cameraStyle.customCamera,]} //(props.cameraType!='front'?{}:cameraStyle.customCameraTop)
                    device={device}
                    isActive={isCameraActive}
                    photo={true}
                    torch={activeFlashMode}
                    fps={60}
                    
                />          
                {_renderBottomControls()}   
                {props.cameraType!='front' && _renderSideControls()}       
                </View> 
            }
            {device!=null && (temp_imgurl!=null && temp_imgurl!='') && isPhotoTaken &&
                <View style={cameraStyle.customCamera_Wrap}>
                <Image source={{uri:temp_imgurl}} style={[cameraStyle.cameraImgCaptured,(props.cameraType=='front' && Platform.OS=='ios' ?{transform:[{scaleX:-1}]}:{}) ]}/>      
                
                {_renderImageControls()}          
                </View> 
            }
            </View>       
        );
    }
    else{
        return (<View></View>)
    }
    
};

export default CustomCamera;

CustomCamera.propTypes = { 
    cameraType: PropTypes.oneOf(['front', 'back']),
    showCamera:PropTypes.bool,
    onImageCaptured: PropTypes.func,
    onHideCamera:PropTypes.func,
};   