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, Alert } from 'react-native';
import { ReactReduxContext, connect, useSelector, useDispatch } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import { notify } from '../components/notify';
import moment from 'moment';
import { version, sloganline, appname, testurl, db, DBName, dbbackupFolder, URL_IMAGE } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';
import * as RNFS from 'react-native-fs';
import NetInfo from '@react-native-community/netinfo';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { getMethodName, METHODS } from '../constants/methodNames';

function GetDb(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);
  async function showdbfile() {
    const dbbackupFolder = RNFS.DocumentDirectoryPath + '/DbBackup';
    //const dbbackupFolder = RNFS.ExternalDirectoryPath + '/DbBackup'; // Adjust if you're using another path
    const targetPath = dbbackupFolder + '/' + props.projectCode + "_" + props.UserId + "_" + moment(new Date()).format('MMDDYYYY_HHmmss') + "_" + DBName;
    //const backupPath = RNFS.ExternalDirectoryPath + '/' + DBName;
    const backupPath = RNFS.DocumentDirectoryPath + '/' + DBName;
    try {
      setProcessing(true); // ⏳ show loader
      // Check if backup folder exists
      const folderExists = await RNFS.exists(dbbackupFolder);
      console.log("DbBackup folder exists:", folderExists);
      if (!folderExists) {
        console.warn("Backup folder does not exist.");
        return;
      }
      // List files in backup folder
      const files = await RNFS.readDir(dbbackupFolder);
      console.log("Files in backup folder:" + targetPath);
      files.forEach(file => console.log(" -", file.name));
      // Check if DB file exists
      const fileExists = await RNFS.exists(backupPath);
      console.log("DB file exists:", fileExists);
      if (!fileExists) {
        console.warn("Database file not found at path:", backupPath);
        return;
      }
      // Copy file
      await RNFS.copyFile(backupPath, targetPath);
      console.log("files_db", files)
      // Refresh file list after copy
      files = await RNFS.readDir(dbbackupFolder);
      console.log("📂 Files in backup folder:", files.map(f => f.name));

      for (const file of files) {
        if (file.isFile()) {
          console.log("Uploading:", file.path);
          let d1 = new Date();
          let d2 = moment(d1).format('MM/DD/YYYY');
          const formData = new FormData();
          formData.append("file", {
            uri: Platform.OS === "ios" ? file.path : "file://" + file.path,
            type: "application/octet-stream",
            name: file.name,
          });
          formData.append("Foldername", "dbBackup");
          formData.append("Path", d2);

          const requestOptions = {
            method: "POST",
            body: formData,
            redirect: "follow"
          };

          const url = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);

          try {
            const response = await fetch(url, requestOptions);
            // read as text, because it's XML
            const resultText = await response.text();
            if (resultText.includes("Success")) {
              // Delete the file after successful upload
              await RNFS.unlink(file.path);
              console.log("🗑️ Deleted local backup:", file.name);
            } else {
              console.log("⚠️ Upload failed, keeping file:", file.name);
            }
            console.log("Raw upload response:", resultText);
            if (!response.ok) {
              throw new Error("Upload failed: " + resultText);
            }
          } catch (err) {
            console.error("❌ Upload error:", err.message || err);
          }
        }
      }

      notify("Backup exported successfully")
    } catch (err) {
      console.error("❌ Error handling DB file:", err.message || err);
    } finally {
      setProcessing(false); // ✅ hide loader after upload
    }
  }







  return (
    <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
      {processing && <CustomLoader title={ST.Loading + "..."} />}
      <CustomHeader {...props} title={ST.Settings} hideBellIcon={true} hideTimer={true} />
      <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper]}>
          {/* {borderTopLeftRadius:0,borderTopRightRadius:0,} */}
          <View style={customStyle.settingsWrap}>
            <TouchableOpacity
              style={customStyle.settingsBtnNew}
              activeOpacity={0.6}
              onPress={() => {
                Alert.alert(
                  'Confirm Backup',
                  'Are you sure you want to take and upload backup?',
                  [
                    { text: 'Cancel', style: 'cancel' },
                    {
                      text: 'Yes',
                      onPress: () => {
                        NetInfo.fetch().then(state => {
                          if (state.isConnected) {
                            showdbfile();
                          } else {
                            Alert.alert('No Internet', 'Please check your internet connection and try again.');
                          }
                        });
                      },
                    },
                  ],
                  { cancelable: true }
                );
              }}
            >
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Icon name="database-export" size={20} color="#fff" style={{ marginRight: 8 }} />
                <Text style={customStyle.settingsBtnTextNew}>DB Backup</Text>
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </LinearGradient>
    </Container >
  );
}



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