import React, { useRef, useState, useEffect } from "react";
import { Dimensions, Image, Platform, ScrollView, StatusBar, Text, TouchableOpacity, View } from "react-native";
import { customCamera, customStyles, GetPageTheme, HP, WP } 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 } from "./icons";
import { useOrientation, useOrientation2 } from "../controller/functions";
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { launchCamera, launchImageLibrary, CameraOptions } from 'react-native-image-picker';
// import Orientation from 'react-native-orientation';
import Orientation from 'react-native-orientation-locker';
import { OrientationLocker, PORTRAIT, LANDSCAPE } from "react-native-orientation-locker";
import moment from "moment";
import * as RNFS from 'react-native-fs';
import ViewShot from "react-native-view-shot";
import { AllKpiImg } from "../../src(Camera&img)/constants/constants";
import CustomModal from "./CustomModal";

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 viewShort = useRef();
    const devices = useCameraDevices('wide-angle-camera');
    const device = props.cameraType == 'front' ? devices.front : devices.back;
    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 [currentOr, setCurrentOr] = useState("");
    const [showCameraForScreen, setShowCameraForScreen] = useState(true);
    const [gridEnable, setGridEnable] = useState(false);
    const [showCapLandsImgAlert, setShowCapLandsImgAlert] = useState(false);
    

  
    // useEffect(()=>{
    //     if(device != null && (temp_imgurl != null && temp_imgurl != '') && isPhotoTaken){
    //         console.log('take screenshot now2!!',photoObj.or_Mode,photoObj);
    //         screenShort();
    //     }
    // },[isPhotoTaken])

    function screenShort(){
        setTimeout(function (){
            console.log('after 10 sec');
        },20*1000)
    }

    async function screenShort2(){
        console.log('in screenShort2');
        let test = await viewShort.current.capture()
            let FileName = 'abc146.png';
            let tst = RNFS.PicturesDirectoryPath+"/Telegram"+FileName
            console.log("album--",tst, " --",test)
    
            await RNFS.copyFile(test, tst).then(res=>console.log("passssedd"))
            setCurrentOr("")
    }

    useEffect(() => {
        let showGrid = props.gridEnable != null ? (props.gridEnable) : false;

        console.log("props.gridEnable-----------",props.gridEnable, " ---",showGrid)
        setGridEnable(showGrid);
    },[props.gridEnable])


    useEffect(() => {
        
        console.log('CameraGallery in camera :', props.CameraGallery, 'for screen:', props.enableGallerForScreen);
        let showScreenCam = props.enableGallerForScreen != null ? (props.enableGallerForScreen) : true;
        setShowCameraForScreen(showScreenCam);
        hasCameraPermission();
        
        
        // Dimensions.addEventListener('change', ({window:{width,height}})=>{
        //     let or=useOrientation(width,height);
        //     setOrientation(or);
        // });
        // const initial = Orientation.getInitialOrientation();
        // console.log('initial:',initial);
        Orientation.addDeviceOrientationListener((orientation) => {
            let or = useOrientation2(orientation)
            // console.log("or ------")
            setOrientation(or);

        });

        return () => {
            Orientation.removeOrientationListener((orientation) => {
                console.log('orientation: listener removed:', orientation);
            });
            Orientation.removeAllListeners();
        }

    }, []);

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

    function showCamera() {
        console.log('showCamera customcamera');
        if(props.cameraType != 'front' ){
            setShowCapLandsImgAlert(true);
            setTimeout(() => {
                setShowCapLandsImgAlert(false);
            }, 3000);
        }
        
        setIsCameraActive(true);
        setisActive(true);
    }

    async function hideCamera() {

        if(temp_imgurl!=null && temp_imgurl!='')
        {
            await RNFS.unlink(temp_imgurl);
        }
        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() {
        // let test = await viewShort.current.capture()
        //     let FileName = 'abc143.png';
        //     let tst = RNFS.PicturesDirectoryPath+"/Telegram"+FileName
        //     console.log("album--",tst, " --",test)
    
        //     await RNFS.copyFile(test, tst).then(res=>console.log("passssedd"))
        if (camera.current != null && typeof camera.current === 'object') {
            console.log("orientation---------------current--",orientation)
            // setCurrentOr(orientation)
            const photo = await camera.current.takePhoto({
                // flash: 'on',      
            })
            
            // console.log("file://------1",photo)
            if (photo != null) {
                let path = 'file://' + photo.path;

                console.log(path);
                let obj = { uri: path, width: photo.width, height: photo.height,or_Mode:orientation };
                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() {
        await RNFS.unlink(temp_imgurl);
        setTemp_imgurl('');
        setIsPhotoTaken(false);
        setshowImage(false);
        setIsCameraActive(true);
        setisActive(true);
    }
    async function onCameraImgOk() {
        let test = await viewShort.current.capture()
        let obj = photoObj;
        if( gridEnable){
            obj.uri = test;
        }else{
            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 pickGalleryImage(img) {
        console.log('pickGalleryImage:', img, typeof img.assets);
        if (img != null && img.assets != null && typeof img.assets == 'object' && img.assets.length > 0 && img.assets[0].uri != null) {
            let photo = img.assets[0];
            let path = photo.uri;
            console.log(path);
            let times = photo.timestamp != null && photo.timestamp != '' ? photo.timestamp : new Date();
            let obj = { uri: path, width: photo.width, height: photo.height, 'fromGallery': true, 'datetime': times };
            setPhotoObj(obj);
            setTemp_imgurl(path)
            setIsPhotoTaken(true);
        }
        else {
            notify('Something went wrong! Cannot take picture.');
            setisActive(false);
        }
    }

    function getImageFromGallery() {
        launchImageLibrary({ mediaType: 'photo', selectionLimit: 1, includeExtra: true, cameraType: 'front' }, pickGalleryImage)
    }

    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 _renderGalleryBtn() {
        return (
            <TouchableOpacity style={cameraStyle.customCamera_Gallerybtn} onPress={() => { getImageFromGallery() }}>
                <View style={cameraStyle.customCamera_Gallerybtn_Outer}>
                    <View style={cameraStyle.customCamera_Gallerybtn_Inner}>
                        <Entypo name='images' size={32} color={PageTheme.$text_color} style={cameraStyle.customCamera_Gallerybtn_Icon} />
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    function _renderBottomControls() {
        return (
            <View style={cameraStyle.customCamera_bottomBar}>
                {_renderCaptureBtn()}
                {props.CameraGallery == true && showCameraForScreen == true &&
                    _renderGalleryBtn()
                }
            </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 _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>
        )
    }

    function _renderSideControls() {
        return (
            <View style={cameraStyle.sideControls}>
                <View style={cameraStyle.sideControlsInner}>
                    {_renderFlashBtn('on')}
                    {_renderFlashBtn('off')}
                </View>
            </View>
        )
    }

    function _renderSCreenSHotView(){
        let imgSIze=(photoObj.or_Mode!=null && photoObj.or_Mode!='' ?(photoObj.or_Mode==='LANDSCAPE'?{width:'100%'}:{height:'100%'}):{});
        let vieshotStyle={}; 
        let itemW=photoObj.width,itemH=photoObj.height;
        if(photoObj.or_Mode==='LANDSCAPE'){
            if(photoObj.or_Mode===orientation){
                vieshotStyle ={width:'100%',height:'100%'};
            }
            else{
                let hR=(itemH/itemW )*100;
                let screenWidth=WP('100%');
                let ht=screenWidth*(hR/100);
                vieshotStyle ={width:'100%',height:ht};
            }
            
        }
        else{
            if(photoObj.or_Mode===orientation){
                vieshotStyle ={width:'100%',height:'100%'};
            }
            else{
                let wR=(itemW/itemH )*100;
                let screenHt=WP('100%');
                let wd=screenHt*(wR/100);
                vieshotStyle ={width:wd,height:'100%'};
            }
        }

        console.log('vieshotStyle',vieshotStyle);

        return(
            <View style={[cameraStyle.customCamera_Wrap,{justifyContent:'center',alignItems:'center'}]}>
                    <ViewShot ref={viewShort} style={[vieshotStyle,]} >
                        {console.log('image is showing :')}
                        <Image source={{ uri: temp_imgurl }} style={[imgSIze,cameraStyle.cameraImgCaptured, (props.cameraType == 'front' && Platform.OS == 'ios' ? { transform: [{ scaleX: -1 }] } : {})]}  resizeMode={(photoObj.or_Mode===orientation?'cover':'contain')}/>
                        {
                            gridEnable && 
                        <View style={[vieshotStyle]}>
                        <View style={[{ width:"100%", height:'100%'},(orientation =="LANDSCAPE" ?  {alignItems:"center"}:{justifyContent:"center"} )]}>
                            <View style={[vieshotStyle,{borderColor:'#B69367',borderWidth:1}]} >
                            <View style={{height:'33%',borderBottomColor:'#B69367',width:'100%',borderBottomWidth:1}}></View>
                            <View style={{height:'33%',borderBottomColor:'#B69367',width:'100%',borderBottomWidth:1}}></View>
                            <View style={{flexDirection:'row',position:'absolute',top:0,left:0,width:'100%',height:'100%'}}>
                                <View style={{height:'100%',borderRightColor:'#B69367',width:'33%',borderRightWidth:1}}></View>
                                <View style={{height:'100%',borderRightColor:'#B69367',width:'33%',borderRightWidth:1}}></View>
                            </View>     
                            </View>
                            </View>
                        </View>
                        }
                        </ViewShot>
                        {_renderImageControls()}
                    </View>
        )
    }

    function _render_AutoAlertModal(){
        console.log('_render_AutoAlertModal2',showCapLandsImgAlert);
        return (
          <CustomModal
            style={customStyle.storelVisitM_Style}
            title={"Please click image in Landscape mode!"}
            titleStyle={customStyle.storelVisitM_titleStyle}
            showModal={showCapLandsImgAlert}
          >
            <View></View>
          </CustomModal>
        )
    }

    if (props.showCamera == true && isActive == true) {
        
        return (
            <View style={cameraStyle.scrollMain}>
                <OrientationLocker
                    orientation={currentOr !=""? (currentOr):(orientation == 'LANDSCAPE' ? LANDSCAPE : PORTRAIT)}
                    onChange={orientation => console.log('onChange', orientation)}
                    onDeviceChange={orientation => console.log('onDeviceChange', orientation)}
                />
                <StatusBar translucent={true} hidden={true} />
                
                {Platform.OS == 'ios' && <View style={cameraStyle.IOS_StatusBar}></View>}
                {device != null && isActive &&
                    <View style={cameraStyle.customCamera_Wrap}>
                        {_render_AutoAlertModal()}
                        {console.log('activeFlashMode:', activeFlashMode)}
                        <Camera
                            ref={camera}
                            style={[cameraStyle.customCamera, (orientation == 'LANDSCAPE' || props.cameraType == 'front' ? cameraStyle.customCameraLS : {})]} //(props.cameraType!='front'?{}:cameraStyle.customCameraTop)
                            device={device}
                            isActive={isCameraActive}
                            photo={true}
                            focusable={true}
                            torch={activeFlashMode}
                            // enableZoomGesture={true}
                            fps={60}
                        />
                        {
                            gridEnable &&
                        <View style={[{ width:"100%",marginBottom:100},(orientation==='LANDSCAPE'?{height:'100%'}:{})]}>
                            <View style={[{ width:"100%", height:'100%'},(orientation =="LANDSCAPE" ?  {alignItems:"center"}:{justifyContent:"center"} )]}>
                                <View style={[{ width:"100%", height:'100%',borderColor:'#B69367',borderWidth:1}]} >
                                    <View style={{height:'33%',borderBottomColor:'#B69367',width:'100%',borderBottomWidth:1}}></View>
                                    <View style={{height:'33%',borderBottomColor:'#B69367',width:'100%',borderBottomWidth:1}}></View>
                                    <View style={{flexDirection:'row',position:'absolute',top:0,left:0,width:'100%',height:'100%'}}>
                                        <View style={{height:'100%',borderRightColor:'#B69367',width:'33%',borderRightWidth:1}}></View>
                                        <View style={{height:'100%',borderRightColor:'#B69367',width:'33%',borderRightWidth:1}}></View>
                                    </View>
                                </View>
                                
                            </View>
                            
                        </View>
                        }
                        
                        {_renderBottomControls()}
                        {props.cameraType != 'front' && _renderSideControls()}
                    </View>
                }
                {device != null && (temp_imgurl != null && temp_imgurl != '') && isPhotoTaken &&
                _renderSCreenSHotView()
                }
            </View>
        );
    }
    else {
        return (<View></View>)
    }

};

export default connect(mapStateToProps, mapDispatchToProps)(CustomCamera);

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