// components/PDFGenerator.js

import React, { useContext, useState } from 'react';
import {
  StyleSheet,
  View,
  Button,
  Alert,
  TouchableOpacity,
  Text,
  ActivityIndicator,
  Platform,
} from 'react-native';
import * as Print from 'expo-print';
import * as FileSystem from 'expo-file-system';
import { StorageAccessFramework } from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import { MediaContext } from '../context/MediaContext';
import { Ionicons } from '@expo/vector-icons';

const PDFGenerator = () => {
  const { media } = useContext(MediaContext);
  const [pdfUri, setPdfUri] = useState(null); // State to store PDF URI
  const [isGenerating, setIsGenerating] = useState(false); // State for Activity Indicator

  const generatePDF = async () => {
    setIsGenerating(true); // Start Activity Indicator

    // Create HTML content for PDF
    let mediaHtml = '';

    if (media.photo) {
      mediaHtml += `<h2>Captured Photo</h2><img src="${media.photo}" style="width:100%; height:auto;" />`;
    }

    if (media.video) {
      // Note: Embedding video in PDF is not widely supported
      mediaHtml += `<h2>Recorded Video</h2>
                    <p>Video recorded at: <a href="${media.video}">Download Video</a></p>`;
    }

    if (media.audio) {
      // Note: Embedding audio in PDF is not widely supported
      mediaHtml += `<h2>Recorded Voice</h2>
                    <p>Audio recorded at: <a href="${media.audio}">Download Audio</a></p>`;
    }

    const htmlContent = `
      <html>
        <head>
          <style>
            body { font-family: Arial, sans-serif; padding: 20px; }
            h1 { text-align: center; }
            img { max-width: 100%; height: auto; }
            a { color: blue; text-decoration: none; }
          </style>
        </head>
        <body>
          <h1>Consent Document</h1>
          <p>${legalText}</p>
          ${mediaHtml}
        </body>
      </html>
    `;

    try {
      // Generate PDF from HTML
      const { uri } = await Print.printToFileAsync({ html: htmlContent });
      console.log('PDF generated at:', uri);

      let destinationUri = '';

      if (Platform.OS === 'android') {
        // Use StorageAccessFramework to request directory permissions
        const permissions = await StorageAccessFramework.requestDirectoryPermissionsAsync();

        if (!permissions.granted) {
          Alert.alert(
            'Permission Required',
            'Storage permission is needed to save the PDF.'
          );
          setIsGenerating(false);
          return;
        }

        // Define the filename
        const filename = `ConsentDocument_${Date.now()}.pdf`;

        try {
          // Create a new file in the selected directory
          const fileUri = await StorageAccessFramework.createFileAsync(
            permissions.directoryUri,
            filename,
            'application/pdf'
          );
          console.log('File created at:', fileUri);

          // Read the generated PDF file
          const pdfData = await FileSystem.readAsStringAsync(uri, {
            encoding: FileSystem.EncodingType.Base64,
          });

          // Write the PDF data to the new file
          await FileSystem.writeAsStringAsync(fileUri, pdfData, {
            encoding: FileSystem.EncodingType.Base64,
          });

          destinationUri = fileUri;
          setPdfUri(destinationUri);

          Alert.alert(
            'Success',
            'PDF has been saved successfully!'
          );
        } catch (e) {
          console.error('Error saving PDF:', e);
          Alert.alert('Error', 'Failed to save PDF: ' + e.message);
        }
      } else {
        // For iOS and other platforms, use Sharing
        const filename = `ConsentDocument_${Date.now()}.pdf`;
        const destinationPath = `${FileSystem.documentDirectory}${filename}`;
        console.log('Destination Path:', destinationPath);

        // Move the PDF to the desired location
        await FileSystem.moveAsync({
          from: uri,
          to: destinationPath,
        });

        destinationUri = destinationPath;
        setPdfUri(destinationUri);

        if (await Sharing.isAvailableAsync()) {
          await Sharing.shareAsync(destinationUri);
        } else {
          Alert.alert(
            'Success',
            'PDF has been saved to your Documents directory.'
          );
        }
      }
    } catch (error) {
      Alert.alert('Error', 'Failed to generate PDF: ' + error.message);
      console.error('Error generating PDF:', error);
    }

    setIsGenerating(false); // Stop Activity Indicator
  };

  const openDownloadLocation = async () => {
    if (!pdfUri) {
      Alert.alert('No PDF', 'Please generate the PDF first.');
      return;
    }

    try {
      if (Platform.OS === 'android') {
        // Inform the user to check the selected directory
        Alert.alert(
          'Download Complete',
          'The PDF has been saved successfully. You can access it using any file manager app.'
        );
      } else if (Platform.OS === 'ios') {
        // Use the sharing sheet to open the PDF
        if (await Sharing.isAvailableAsync()) {
          await Sharing.shareAsync(pdfUri);
        } else {
          Alert.alert(
            'Sharing Not Available',
            'Cannot share the PDF on this device.'
          );
        }
      } else {
        Alert.alert('Unsupported Platform', 'This feature is not supported on your device.');
      }
    } catch (error) {
      Alert.alert('Error', 'Cannot open the PDF. Please try again.');
      console.error('Error opening PDF:', error);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.section}>
        <Button title="Download PDF" onPress={generatePDF} disabled={isGenerating} />
      </View>
      {isGenerating && <ActivityIndicator size="large" color="#0000ff" />}
      {pdfUri && (
        <TouchableOpacity style={styles.iconContainer} onPress={openDownloadLocation}>
          <Ionicons name="folder-open" size={40} color="#4CAF50" />
          <Text style={styles.iconText}>Open Download Location</Text>
        </TouchableOpacity>
      )}
    </View>
  );
};

// --- Legal Text (Should be imported or passed as a prop) ---
const legalText = `YOUR LEGAL TEXT GOES HERE...

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.`;

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  section: {
    marginBottom: 30,
    backgroundColor: '#ffffff',
    padding: 15,
    borderRadius: 10,
    elevation: 2, // For Android
    shadowColor: '#000', // For iOS
    shadowOffset: { width: 0, height: 2 }, // For iOS
    shadowOpacity: 0.25, // For iOS
    shadowRadius: 3.84, // For iOS
    alignItems: 'center',
  },
  iconContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 10,
    padding: 10,
    backgroundColor: '#e0f7fa',
    borderRadius: 10,
  },
  iconText: {
    marginLeft: 10,
    fontSize: 16,
    color: '#00796b',
  },
});

export default PDFGenerator;

update it to use the text from 

// components/LegalText.js

import React from 'react';
import { ScrollView, Text, StyleSheet } from 'react-native';

const LegalText = () => {
  return (
    <ScrollView style={styles.container}>
      <Text style={styles.text}>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.
      </Text>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  text: {
    fontSize: 16,
    lineHeight: 22, // Added for better readability
  },
});

export default LegalText;