import { View, ScrollView, Alert, } from 'react-native'
import React, { useState, useEffect, useRef } from 'react'
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme } from "../styles/Global";
import LinearGradient from 'react-native-linear-gradient';
import { WebView } from 'react-native-webview'
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { connect } from 'react-redux'
import CustomHeader from '../components/customHeader';
import Share from 'react-native-share';
import RNFS from 'react-native-fs';

function Bannerdetail(props) {
  const route = useRoute();
  const [currentItem, setcurrentItem] = useState({});
  const PageTheme = GetPageTheme(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  let showwebview = false;
  const webViewRef = useRef(null);

  useEffect(() => {
    let params = props.route.params != null ? props.route.params : {};
    console.log("params", params);
    let currentitem1 = params.imagedesc != null ? params.imagedesc : {};
    console.log('onrender bannaer ', currentitem1);
    let ext = currentitem1.NoticeLink_FullPage.split('.').pop();
    console.log('ext', ext)
    if (ext == 'html') {
      showwebview = true;
    } else {
      showwebview = false;
    }
    setcurrentItem(currentitem1)
  }, []);

  const injectedJS = `
        // Create global share function
        window.nativeShare = function(options) {
            window.ReactNativeWebView.postMessage(JSON.stringify({
                type: 'SHARE',
                data: options
            }));
        };

        // Helper function to convert image to base64
        window.imageToBase64 = function(img) {
            const canvas = document.createElement('canvas');
            canvas.width = img.naturalWidth || img.width;
            canvas.height = img.naturalHeight || img.height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            return canvas.toDataURL('image/png');
        };

        true; // Required for iOS
    `;

  const handleWebViewMessage = async (event) => {
    try {
      const message = JSON.parse(event.nativeEvent.data);
      console.log("event----------", event)
      if (message.type === 'SHARE') {
        await handleShare(message.data);
      }
    } catch (error) {
      console.error('Error handling message:', error);
    }
  };

  const handleShare = async (shareData) => {
    try {
      const { type, title, message, url, image, images } = shareData;
      let shareOptions = {
        title: title || 'Share',
        message: message || '',
      };
      // Handle different share types
      switch (type) {
        case 'text':
          // Share text and/or URL
          if (url) {
            shareOptions.url = url;
          }
          await Share.open(shareOptions);
          break;

        case 'image':
          // Share single image
          if (image) {
            const base64Data = image.split(',')[1]; // Remove data:image/png;base64, prefix
            const filePath = `${RNFS.CachesDirectoryPath}/share_image_${Date.now()}.png`;
            await RNFS.writeFile(filePath, base64Data, 'base64');
            shareOptions.url = `file://${filePath}`;
            shareOptions.type = 'image/png';
            await Share.open(shareOptions);
            // Cleanup after sharing
            setTimeout(() => {
              RNFS.unlink(filePath).catch(() => { });
            }, 1000);
          }
          break;

        case 'multiple_images':
          // Share multiple images
          if (images && images.length > 0) {
            const filePaths = await Promise.all(
              images.map(async (imageData, index) => {
                const base64Data = imageData.split(',')[1];
                const filePath = `${RNFS.CachesDirectoryPath}/share_image_${Date.now()}_${index}.png`;
                await RNFS.writeFile(filePath, base64Data, 'base64');
                return `file://${filePath}`;
              })
            );

            shareOptions.urls = filePaths;
            shareOptions.type = 'image/png';
            await Share.open(shareOptions);
            // Cleanup
            setTimeout(() => {
              filePaths.forEach(path => {
                const cleanPath = path.replace('file://', '');
                RNFS.unlink(cleanPath).catch(() => { });
              });
            }, 1000);
          }
          break;

        case 'image_with_text':
          // Share image with text/URL
          if (image) {
            const base64Data = image.split(',')[1];
            const filePath = `${RNFS.CachesDirectoryPath}/share_image_${Date.now()}.png`;
            await RNFS.writeFile(filePath, base64Data, 'base64');
            shareOptions.url = `file://${filePath}`;
            shareOptions.type = 'image/png';
            // Add URL as message if provided
            if (url) {
              shareOptions.message = `${message || ''}\n${url}.trim()`;
            }

            await Share.open(shareOptions);
            setTimeout(() => {
              RNFS.unlink(filePath).catch(() => { });
            }, 1000);
          }
          break;

        default:
          // Default text share
          await Share.open(shareOptions);
      }

    } catch (error) {
      console.log('Share cancelled or error:', error);
    }
  };

  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      <CustomHeader {...props} showaddstore={true} title={'Banner Detail'} />
      <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={customStyle.pageContentWrapper}>
          <ScrollView contentContainerStyle={{ width: '100%', flex: 1 }}>
            {
              !showwebview &&
              <WebView
                style={{ height: '97%', width: '95%', borderRadius: 20, marginLeft: 10, marginTop: 10, borderWidth: 1 }}
                source={{ uri: currentItem.NoticeLink_FullPage }}
                ref={webViewRef}
                injectedJavaScript={injectedJS}
                onMessage={handleWebViewMessage}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                allowFileAccess={true}
                cacheEnabled={false}  // Disable cache
                incognito={true}
                onError={(syntheticEvent) => {
                  console.error('WebView error:', syntheticEvent.nativeEvent);
                }}
                onLoadStart={() => console.log('WebView loading...')}
                onLoadEnd={() => console.log('WebView loaded successfully')}
                onLoadProgress={({ nativeEvent }) => {
                  console.log('Load progress:', nativeEvent.progress);
                }}

              />
            }
          </ScrollView>
        </View>

      </LinearGradient>
    </Container>
  )
}
export default connect(mapStateToProps, mapDispatchToProps)(Bannerdetail)