import React, { useState, useEffect, useRef } 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, TrainingContentFolderPath, } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import { FontAwesome, Fontisto, Ionicons, MaterialCommunityIcons } from '../components/icons';
import NoDataComponent from '../components/NoDataComponent';
import WebView from 'react-native-webview';
import { AntDesign, Entypo } from "../components/icons";
import * as RNFS from "react-native-fs";
import FileViewer from "react-native-file-viewer";
import ImageViewer from 'react-native-image-zoom-viewer';
import base64 from 'base-64';
import { updatePartiallyEmittedExpression } from 'typescript';


function Training(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 globalStyle = globalStyles(props.DarkMode, route.name);
  const [processing, setProcessing] = useState(false);
  const [webviewurl, setWebviewurl] = useState('');
  const [TrainingData, setTrainingData] = useState([]);
  const [showwebview, setShowWebview] = useState(false);
  const [webviewurlT, setWebviewurlT] = useState('');
  const [isAdhocScreen, setIsAdhocScreen] = useState(false);
  const [storeData, setStoreData] = useState({});
  const [currentMenu, setCurrentMenu] = useState({});
  const [show_zoomImage, setShow_zoomImage] = useState(false);
  const [contentIdParam, setcontentIdParam] = useState(false);
  const [currentReportMenu, setCurrentReportMenu] = useState({});
  const zoomView = useRef(null);

  useEffect(() => {
    let params = props.route.params ? props.route.params : {};
    let storeData1 = params.storeData || {};
    let menu1 = params.menu || {};
    let contentid = props.route.params.Contentid
    let TrainingData = props.route.params.TrainingData
    // console.log('vcontentid',contentid)
    let isAdhoc = params.isAdhoc || false;
    setCurrentReportMenu(TrainingData)
    setIsAdhocScreen(isAdhoc);
    setStoreData(storeData1);
    setcontentIdParam(contentid);
    setCurrentMenu(menu1);
    getData(contentid);

    const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
    return function cleanup() {
      return unsubscribe;
    };

  }, []);

  useEffect(() => {
    const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
    return unsubscribe;
  }, [show_zoomImage]);

  function onBeforeRemove(e) {
    if (show_zoomImage == true) {
      e.preventDefault();
      setShow_zoomImage(false);
    }
    else {
      return;
    }
  }

  function _renderHeader(currentIndex) {
    return (
      <View style={customStyle.album_ZOOM_topBar}>
        <TouchableOpacity style={customStyle.album_ZOOM_backBtn} onPress={() => { console.log('tsth'); setShow_zoomImage(false) }}>
          <Entypo name='chevron-left' color={'#fff'} size={24} />
        </TouchableOpacity>
      </View>
    )
  }

  async function getData(content_id) {
    try {
      content_id = props.route.params.Contentid
      console.log('params', content_id)
      let List = [];
      await db.transaction(async function (txn) {
        let q = `Select * from Master_DetailerContent where ContentTypeId='${content_id}'`;
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('txnres2.rows.length:', txnres2.rows.length)
          if (txnres2.rows.length > 0) {
            for (let i = 0; i < txnres2.rows.length; i++) {
              let data = txnres2.rows.item(i);
              List.push(data)
            }
            setTrainingData(List)
          }

        }, function (txnE, txnerr) { console.log(txnerr); },);
      });
    } catch (err) {
      console.log(err);
    }
  }

  const DownloadContent = async (item) => {
    let filename = item.FName
    let path = (item && item.MediaType && item.MediaType.toLowerCase() == "pdf") ? "/pdf/" : (item && item.MediaType && item.MediaType.toLowerCase() == "image") ? "/images/" : (item && item.MediaType && item.MediaType.toLowerCase() == "html") ? "html" : "/video/"
    if (path == 'html') {
      let contentURL = item.FilePath ? item.FilePath + item.FName : '';
      props.navigation.navigate('WebViewScreen', { 'url': contentURL, storeData: storeData })
    } else {
      const fileDir = TrainingContentFolderPath + path;
      const filePath = TrainingContentFolderPath + path + filename;
      let contentURL = item.FilePath ? item.FilePath + item.FName : '';
      let contentFileExist = await RNFS.exists(filePath)
      if (contentFileExist) {
        setWebviewurlT(filePath)
        if (path == "/pdf/") {
          FileViewer.open(filePath)
        } else if (path == "/video/") {
          props.navigation.navigate('VideoScreen', { filePath: filePath })
        } else {
          setShow_zoomImage(true)
        }
      } else {
        setProcessing(true)
        let fileExist = await RNFS.exists(fileDir)
        if (fileExist) {
          console.log("file is exists", fileDir)
        } else {
          await RNFS.mkdir(fileDir).then(() => console.log("Dir is created- ", fileDir))
        }

        RNFS.writeFile(filePath, '').then(async (create_res) => {
          console.log('filecreated')
          const download = await RNFS.downloadFile({
            fromUrl: contentURL,
            toFile: filePath,
            progress: (res) => {
              let bytes = res.bytesWritten;
              let dataDownloadedinMB = (bytes / (1024 * 1024)).toFixed(2);
            },
            begin: (res) => {
              console.log('on download begin');
            },

          });

          download.promise.then(async (result) => {
            setProcessing(false);
            setWebviewurlT(filePath)
            if (result.statusCode == 404) {
              notify('Sorry! Cannot download file as file does not exists on server!');
              await RNFS.unlink(filePath);
            } else {
              notify('File is downloaded!');
              if (path == "/pdf/") {
                FileViewer.open(filePath)
              } else if (path == "/video/") {
                props.navigation.navigate('VideoScreen', { filePath: filePath })
              } else {
                setShow_zoomImage(true)
              }
            }
          });
        }).catch((err) => {
          console.log('Error while creating:', err);
          setProcessing(false);
          setDownloading(false);
          RNFS.unlink(filePath);
          notify('Sorry! Cannot download file');
        })
      }
    }
  }

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader title={ST.Loading + ".."} />}
      <CustomHeader {...props} showaddstore={true} title={currentReportMenu?.ContentType || (contentIdParam == 2 ? "Consumer Section" : ST.Training)} projectCode={storeData != null && Object.keys(storeData).length > 0 ? `${storeData.StoreId}: ${storeData.StoreName}` : props.projectCode} />
      <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper, customStyle.roundScrollInner, { paddingTop: 10, paddingHorizontal: 10 }, { alignItems: "center" }]}>
          {!props.isDataDownloaded && <NoDataComponent {...props} />}
          <View style={[customStyle.trainingHdr]}>
            {contentIdParam == 2 ? <Text style={customStyle.trainingHdrText}>Consumer Section Content</Text> :
              <Text style={customStyle.trainingHdrText}>{currentReportMenu?.ContentType || 'Training Content'}</Text>
            }
          </View>
          {!showwebview &&
            <ScrollView
              contentContainerStyle={customStyle.train_scrollViewInner}
              style={customStyle.train_scrollView}
            >
              {TrainingData && TrainingData.map((item, i) => (
                <TouchableOpacity
                  style={[customStyle.trainingl]}
                  onPress={() => DownloadContent(item)}
                  key={i}>

                  <View style={customStyle.trainingView}>
                    <Text style={customStyle.trainingl_card_title}>{item.Topic}</Text>
                    <View style={customStyle.storel_details}>
                      <View style={customStyle.storel_code}>
                        <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr]}>
                          <Text style={customStyle.storel_codeLbl}>Description</Text>
                          <Text style={[customStyle.storel_codeText, customStyle.train_Itext]}>{item.Description}</Text>
                        </View>
                      </View>
                      <View style={[customStyle.storel_code, customStyle.storel_codeBorderTop, customStyle.mt10]}>
                        <View style={[customStyle.storel_codeCon, customStyle.storel_codeConAddr, { alignItems: "center" }]}>
                          <Text style={customStyle.storel_codeLbl}>Content Type</Text>
                          <View style={{ backgroundColor: PageTheme.$secondary_color_light, flexDirection: "row", alignItems: "center", paddingVertical: 5, paddingHorizontal: 10, borderRadius: 5 }}>
                            {
                              item.MediaType != null && item.MediaType.toLowerCase() == "pdf" ? <AntDesign color={PageTheme.$secondary_color_dark} size={24} name='pdffile1' /> : item.MediaType != null && item.MediaType.toLowerCase() == "Image" ?
                                <Entypo color={PageTheme.$secondary_color_dark} size={24} name='image' onClick={() => console.log("click")} /> : item.MediaType != null && item.MediaType.toLowerCase() == "html" ?
                                  <Entypo color={PageTheme.$secondary_color_dark} size={24} name='link' /> :
                                  <Entypo color={PageTheme.$secondary_color_dark} size={24} name='video' />
                            }
                            <Text style={[customStyle.storel_codeText, { marginLeft: 10 }]}>{item.MediaType}</Text>
                          </View>
                        </View>
                      </View>
                    </View>
                  </View>
                </TouchableOpacity>
              ))}
            </ScrollView>
          }
        </View>
      </LinearGradient>
      {show_zoomImage &&
        <View style={customStyle.album_ZOOM_wrap}>
          <ImageViewer ref={zoomView} style={customStyle.album_ZOOM} imageUrls={[{ url: webviewurlT }]}
            renderHeader={_renderHeader} renderIndicator={() => null}
          />
        </View>
      }
    </Container>
  );
}

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