import React, { useState, useEffect } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { globalStyles, customStyles, GetPageTheme } from "../styles/Global";
import { StatusBar, Image, TextInput, View, Text, ScrollView, TouchableOpacity, Platform, PermissionsAndroid, FlatList } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import { notify } from '../components/notify';
import moment from 'moment';
import { getDownloadJson, DownloadData } from '../controller/functions';
import { get_item, set_item, clear_item } from '../components/localStorage';
import { version, sloganline, appname, testurl, db, colors_Arr } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import { Card } from 'react-native-paper';
import { AntDesign } from '../components/icons';
import { WebView } from 'react-native-webview';
import CustomLoader from '../components/CustomLoader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import { SvgXml } from 'react-native-svg';
import grey_bg_image from '../assets/performics/circle_grey.svg';

function TrainingMenu(props) {
    const route = useRoute();
    const ST = props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);

    const [webviewurl, setWebviewurl] = useState(false);
    const [processing, setProcessing] = useState(true);
    const [isDataFound, setisDataFound] = useState(false);
    const [reportData, setReportData] = useState([]);
    const [designation, setDesignation] = useState('');
    const [CardViewEnable, setCardViewEnable] = useState(false);
    const [CardViewConfig, setCardViewConfig] = useState({});

    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');

    useEffect(() => {
        getData();
    }, []);


    async function getData() {
        try {
            let loginInfo = await get_item('loginInfo');
            const loginDetails = JSON.parse(loginInfo);
            let desg = loginDetails.Designation || '';
            setDesignation(desg);
            await db.transaction(async function (txn) {

                let q = `Select distinct ContentTypeId, ContentType, IconPath, Icon, MediaType, DownloadKey, ReportView as ReportType, InnerScreenView from Sup_Master_DetailerContent group by ContentTypeId`;

                await txn.executeSql(q, [], async function (txn2, txnres) {
                    console.log('txnres.rows.length:', txnres.rows.length);
                    if (txnres.rows.length > 0) {
                        let arr = [];
                        let carView = true
                        for (var i = 0; i < txnres.rows.length; i++) {
                            let data = txnres.rows.item(i);
                            console.log('txnres.rows.data:', data);
                            carView = data?.InnerScreenView == "Tile"
                            arr.push(data);
                            if (i == txnres.rows.length - 1) {
                                setCardViewConfig(data)
                                setCardViewEnable(carView)
                                setReportData(arr);
                                setisDataFound(true);
                                setProcessing(false);
                            }
                        }

                    }
                    else {
                        setProcessing(false);
                    }
                }, function (txn2, txnerr) { console.log(txnerr); setProcessing(false); },);

            });
        } catch (err) {
            setProcessing(false);
            console.log(err);
        }
    }

    function gotoTraingPage(item) {
        if (item.MediaType == "DB") {
            props.navigation.navigate('ReportDetail', { 'ReportData': item })
        } else {
            props.navigation.navigate('Training', { 'Contentid': item.ContentTypeId, 'TrainingData': item })
        }
    }


    function _renderLeftMenuItem(index, RowContent) {
        return (
            <View style={customStyle.dialyMenu_Rows} key={index}>
                {RowContent[0]}
            </View>
        )
    }

    function _renderMenuItem(item, index) {
        let newi
        if (index == 1) {
            newi = "2";
        } else {
            newi = index > 2 ? ((index % 3)) : index;
        }

        let firstitem = (index % 2 == 0) ? true : false;

        let arr = ["#bed3ea", "#bed3ea"];
        let unavlbl_bg = ['#bfbfbf', '#bfbfbf'];
        let arr_new = item?.isAvlbl == false ? unavlbl_bg : arr;
        const imgPath = CardViewConfig?.IconPath + CardViewConfig?.Icon;

        let m_bgimage = colors_Arr[newi] ? colors_Arr[newi]?.bgImage : colors_Arr["0"]?.bgImage;
        m_bgimage = item?.isAvlbl == false ? grey_bg_image : m_bgimage;

        let hasSomeData = item?.hasSomeData
        return (
            <TouchableOpacity activeOpacity={(item.isAvlbl == false ? 1 : 0.7)} style={[customStyle.daily_menu_outer, firstitem ? customStyle.daily_menu_first : {}]} key={index} onPress={() => { gotoTraingPage(item) }}>
                <View style={customStyle.daily_menu_tilebgShadow}>
                    <LinearGradient colors={arr_new} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={customStyle.daily_menu}>
                    </LinearGradient>
                    <View style={[customStyle.daily_menu_innerImgCon]}>
                        <SvgXml xml={m_bgimage} width={90} height={90} style={customStyle.daily_menu_bgImg} />
                    </View>
                    <View style={[customStyle.daily_menu_inner2]}>
                        {(imgPath != null && imgPath != '') && <Image source={{ uri: imgPath }} style={customStyle.daily_menu_Icon} />}
                    </View>

                    <Text style={customStyle.daily_menu_title}>{item.ContentType}</Text>
                    {item.isDone == true &&
                        <View style={customStyle.daily_menu_done}><AntDesign color={'green'} size={30} name='checkcircle' /></View>
                    }

                </View>
            </TouchableOpacity>
        )
    }


    function _renderRightMenuItem(item, index, RowContent) {
        return (
            <View style={customStyle.dialyMenu_Rows} key={index}>
                {RowContent[0]}
                {_renderMenuItem(item, index)}
            </View>
        )

    }

    function _renderMenuList() {
        var RowContent = [];
        return (reportData.length > 0 &&
            reportData.map((item, index) => {
                if (CardViewEnable) {
                    let firstitem = (index % 2 == 0) ? true : false;

                    if (firstitem) {
                        var content = _renderMenuItem(item, index);
                        RowContent = [content];
                        if (index == reportData.length - 1) {
                            return _renderLeftMenuItem(index, RowContent);
                        }
                    }
                    else {
                        return _renderRightMenuItem(item, index, RowContent);
                    }

                } else {
                    return (
                        <TouchableOpacity style={[customStyle.reportMenuItem]} key={index} onPress={() => { gotoTraingPage(item) }}>
                            <Text style={customStyle.reportMenuItemText}>{item.ContentType}</Text>
                        </TouchableOpacity>
                    )
                }
            }))

    }




    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader title={ST.Loading + "..."} />}
            <CustomHeader {...props} title={'Misc. Documents'} />
            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>
                    {!props.isDataDownloaded && <NoDataComponent {...props} />}
                    {props.isDataDownloaded == true &&
                        <View>

                            {isDataFound == false &&
                                <View style={customStyle.noDataCon}>
                                    <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
                                </View>
                            }

                            {
                                isDataFound == true &&
                                <ScrollView
                                    contentContainerStyle={customStyle.rp_scrollViewInner}
                                    style={customStyle.rp_scrollView}
                                >
                                    <View style={[customStyle.vlUinfo_Card]}>
                                        <View style={[customStyle.vlUinfo_CardRow, customStyle.vlUinfo_CardBorder]}>
                                            <Text style={customStyle.vlUinfo_lbl}>{ST.Username + ' :'}</Text>
                                            <Text style={customStyle.vlUinfo_text}>{props.UserId}</Text>
                                        </View>
                                        <View style={customStyle.vlUinfo_CardRow}>
                                            <Text style={customStyle.vlUinfo_lbl}>{ST.Designation + ' :'}</Text>
                                            <Text style={customStyle.vlUinfo_text}>{designation}</Text>
                                        </View>
                                    </View>
                                    <View style={customStyle.reportMenuCon}>
                                        {_renderMenuList()}
                                    </View>
                                </ScrollView>
                            }

                        </View>
                    }
                </View>
            </LinearGradient>

        </Container>
    );
}



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