import React, { useState, useEffect } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme } from '../styles/Global';
import {
  View,
  Text, TouchableOpacity,
  Platform,
  Image,
  FlatList,
  ScrollView,
  Dimensions,
} from 'react-native';
import {
  connect,
} from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import moment from 'moment';
import { get_item } from '../components/localStorage';
import {
  db, TrainingContentFolderPath,
} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import { createContact, openWebBrowser, UploadData2 } from '../controller/functions';
import BadgeModal from '../components/BadgeModal';
import { getMethodName } from '../constants/methodNames';
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 { notify } from '../components/notify';

const Tab = createMaterialTopTabNavigator();
const screenWidth = Dimensions.get("window").width;

function ReportsMenu(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 [processing, setProcessing] = useState(false);
  const [paramsState, setParamsState] = useState({});
  ///Badge
  const [showBadge, setShowBadge] = useState(false);
  const [finalImage, setFinalImage] = useState(null);
  ///trainingsss
  const [TrainingData, setTrainingData] = useState([]);
  const [webviewurlT, setWebviewurlT] = useState('');
  const [show_zoomImage, setShow_zoomImage] = useState(false);



  const d1 = new Date();
  const d2 = moment(d1).format('MM/DD/YYYY');
  const tabData = [
    { id: 1, title: "Banners" },
    { id: 2, title: "Training docs" },
  ];

  useEffect(() => {
    const params = route.params ?? props.route?.params ?? {};
    setParamsState(params?.bannerdetail || []);
    getData()
  }, []);

  async function getData() {
    try {
      let List = [];
      await db.transaction(async function (txn) {
        let q = `Select * from Master_DetailerContent`;
        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)
            }
            console.log("traininnn", List)
            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);
          RNFS.unlink(filePath);
          notify('Sorry! Cannot download file');
        })
      }
    }
  }

  function _renderHeader() {
    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>
    )
  }

  function DynamicScreen({ route }) {
    const handleBannerNavigation = (item, props) => {
      const beforeQuestionMark =
        item?.NoticeLink_FullPage?.split("?")[0] ?? "";
      console.log("banner_item", beforeQuestionMark);
      if (item?.FullPageTarget === "deeplink") {
        if (beforeQuestionMark === "reports") {
          props.navigation.navigate('ReportsMenu');
        } else if (
          (beforeQuestionMark === "gyancast" || beforeQuestionMark === "gyancasts") &&
          (props.Gyancast === 1 || props.Gyancast)
        ) {
          props.navigation.navigate('Gyancasts', { Popup: true });
        } else if (beforeQuestionMark === "gyanbuddy" && props.Chatbot) {
          const hours = new Date().getHours();
          const isWithinTime = hours >= 8 && hours < 20;
          if (isWithinTime) {
            props.navigation.navigate('ChatScreen');
          } else {
            notify("⏰ Gyan Buddy is available between 8:00 AM and 8:00 PM only.");
          }
        } else if (beforeQuestionMark === "training") {
          props.navigation.navigate('TrainingMenu');
        }
      } else if (item?.FullPageTarget === "html-webbrowser") {
        openWebBrowser(item?.NoticeLink_FullPage);
      } else if (item?.FullPageTarget === "frame") {
        NB_RetailDay();
      } else if (item?.FullPageTarget === "contact") {
        createContact(beforeQuestionMark);
      } else {
        props.navigation.navigate('Bannerdetail', { imagedesc: item });
      }
    };

    const renderBanner = ({ item }) => (
      <TouchableOpacity
        onPress={() => handleBannerNavigation(item, props)}
        activeOpacity={0.9}
        style={{
          marginHorizontal: 5,
          marginVertical: 5,
          borderRadius: 14,
          overflow: "hidden",
          backgroundColor: "#fff",
          elevation: 3,
        }}
      >
        <Image
          source={{ uri: item.NoticeLink_Thumbnail }}
          style={{
            width: "100%",
            aspectRatio: 2.3, // keeps banner ratio correct
          }}
          resizeMode="cover"
        />
      </TouchableOpacity>
    );

    if (route.name === "Banners") {
      return (
        <View style={{ backgroundColor: "transparent" }}>
          <FlatList
            data={paramsState}
            keyExtractor={(item) => item.NoticeBoardId.toString()}
            renderItem={renderBanner}
            contentContainerStyle={{ paddingVertical: 10 }}
            showsVerticalScrollIndicator={false}
          />
        </View>

      );
    }

    return (
      <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>
    );
  }

  const handleSaveBadge = async (uri) => {
    setFinalImage(uri);
    setProcessing(true);
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    const today = moment(new Date()).format('MM/DD/YYYY');
    let user_answers = [];
    let ans_obj = { "Visit_Date": today, "UserId": loginDetails.UserId, "Project_code": projectCode };
    user_answers.push(ans_obj);
    let post_data = {
      "MID": "0",
      "Keys": "RetailDay_Data",
      "JsonData": JSON.stringify(user_answers),
      "UserId": loginDetails.UserId
    }
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    console.log('RetailDay upload ', url, post_data);
    await UploadData2(url, post_data)
      .then(async (res) => {
        setProcessing(false);
        console.log(res);
        if (res.success == false) {
          return
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });
  };

  function NB_RetailDay() {
    setShowBadge(true)
  }
  return (
    <>
      <Container
        {...props}
        pt={0}
        avoidSafeArea={Platform.OS == 'ios' ? true : false}>
        {processing && <CustomLoader title={ST.Loading + '...'} />}
        <CustomHeader {...props} showaddstore={true} title={'Banners'} />
        <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 && (
              <Tab.Navigator
                style={[customStyle.pageContentWrapper_bgLight, { marginLeft: 3, marginRight: 3, flex: 1 }]}
                screenOptions={{
                  tabBarItemStyle: { width: screenWidth / 2 }, // each tab = 50%
                  tabBarIndicatorStyle: {
                    backgroundColor: PageTheme.$primary_color,
                    height: 4,
                    width: screenWidth / 2,
                  },
                
                  tabBarScrollEnabled: false,
                  tabBarStyle: {
                    backgroundColor: "white",   // tab bar background
                  },
                  tabBarLabelStyle: {
                    fontWeight: "bold",
                    fontSize: 14
                  },
                }}
              >
                {tabData.map((item) => (
                  <Tab.Screen
                    key={item.id}
                    name={item.title}
                    options={{
                      tabBarLabel: ({ focused }) => (
                        <Text style={{ fontWeight: focused ? "bold" : "normal" }}>
                          {item.title}
                        </Text>
                      )
                    }}
                    component={DynamicScreen}
                    initialParams={{ tabId: item.id }}
                    listeners={{
                      tabPress: () => {
                        console.log("Tab clicked:", item.title);
                      },
                    }}
                  />
                ))}
              </Tab.Navigator>


            )}
          </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>

      <BadgeModal
        visible={showBadge}
        onClose={() => {
          setTimeout(() => {
            setShowBadge(false);
          }, 100);   // 10 seconds
        }}
        onSave={handleSaveBadge}
      />
    </>
  );
}

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