import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Platform, Keyboard } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import Icon from 'react-native-vector-icons/FontAwesome';
import Ionicons from 'react-native-vector-icons/Ionicons';
import mockDataFlat1 from '../data.json';
import * as RNFS from 'react-native-fs';
import moment from 'moment';
import CustomHeader from '../../../../components/CustomHeader';
import IMAGES from '../../../../constants/Images';
import CustomButton from '../../../../components/CustomButton';
import { styles } from './style';
import { GlobalTheme } from '../../../../theme';
import db, { getAllFromTable } from '../../../../constants/database';
import { UploadData2, UploadImagesWithoutWait } from '../../../../constants/uploadData';
import { getAllFileForAFolder, getDownloadJson } from '../../../../constants/function';
import { common_ImagePath, FeedbackImagesFolderPath } from '../../../../constants/constant';
import { toastError } from '../../../../constants/Toast';
import { SafeAreaView } from 'react-native-safe-area-context';
import Loader from '../../../../constants/Loader';
import { ConfirmSaveAlert } from '../../../../components/Alert';
import { useSelector } from 'react-redux';

// image upload url 
const imageUploadURL = "https://di1.parinaam.in/webservice/Imageupload.asmx/Uploadimages";

const FeedbackCategories = ({ navigation, route }) => {

  let user_exist_data = useSelector(state => state?.user);

  const userId = user_exist_data.UserId || '';

  const storeData = route?.params?.storeData;

  console.log("user_exist_data===", (user_exist_data.UserId, storeData?.StoreId));

  const [completedCategories, setCompletedCategories] = useState([]);
  const [uniqueCategories, setUniqueCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const [loadingdownload, setLoadingDownload] = useState(false);
  const [loadingupload, setLoadingUpload] = useState(false);
  const [showAlert, setShowAlert] = useState(false);


  // get data 

  // Insert fallback mock data if empty
  const insertMasterSurveyQuestion = (data_arr = []) => {
    return new Promise((resolve, reject) => {
      if (!Array.isArray(data_arr) || data_arr.length === 0) {
        resolve(true);
        return;
      }

      const escape = str => (str || '').toString().replace(/'/g, "''");

      const values = data_arr.map(item => {
        const {
          MenuId, SurveyId, SurveyName, CategoryId, Category, CategorySequence,
          QuestionId, Question, QuestionType, QuestionImageAllow, QEnable,
          LengthValidation, MinLength, MaxLength, OTP, DateRange, QuestionSequence,
          AnswerId, Answer, ImageAllow1, ImageAllow2, Image1Mandatory, Image2Mandatory,
          QuestionImageMandatory, EnableQuestion, DisableQuestion, AnswerSequence,
          ShowCat, SubCategoryId, SubCategory, SubCategorySequence,
          QuestionTypeNew, CalFormula, RefImage, QuestionRefImage
        } = item;

        return `(
         '${MenuId}', '${SurveyId}', '${escape(SurveyName)}', '${CategoryId}', '${escape(Category)}',
         '${CategorySequence}', '${QuestionId}', '${escape(Question)}', '${escape(QuestionType)}',
         '${QuestionImageAllow ? 1 : 0}', '${QEnable ? 1 : 0}', '${LengthValidation ? 1 : 0}',
         '${MinLength}', '${MaxLength}', '${OTP ? 1 : 0}', '${escape(DateRange)}',
         '${QuestionSequence}', '${AnswerId}', '${escape(Answer)}',
         '${ImageAllow1 ? 1 : 0}', '${ImageAllow2 ? 1 : 0}', '${Image1Mandatory ? 1 : 0}',
         '${Image2Mandatory ? 1 : 0}', '${QuestionImageMandatory ? 1 : 0}',
         '${escape(EnableQuestion)}', '${escape(DisableQuestion)}', '${AnswerSequence}',
         '${ShowCat ? 1 : 0}', '${SubCategoryId}', '${escape(SubCategory)}',
         '${SubCategorySequence}', '${escape(QuestionTypeNew)}', '${escape(CalFormula)}',
         '${escape(RefImage)}', '${escape(QuestionRefImage)}'
       )`;
      });

      const sql = `
       INSERT INTO FeedbackCategory (
         MenuId, SurveyId, SurveyName, CategoryId, Category, CategorySequence,
         QuestionId, Question, QuestionType, QuestionImageAllow, QEnable,
         LengthValidation, MinLength, MaxLength, OTP, DateRange, QuestionSequence,
         AnswerId, Answer, ImageAllow1, ImageAllow2, Image1Mandatory, Image2Mandatory,
         QuestionImageMandatory, EnableQuestion, DisableQuestion, AnswerSequence,
         ShowCat, SubCategoryId, SubCategory, SubCategorySequence,
         QuestionTypeNew, CalFormula, RefImage,QuestionRefImage
       ) VALUES ${values.join(',')}
     `;

      db.transaction(tx => {
        tx.executeSql(`DELETE FROM FeedbackCategory`, [], () => {
          tx.executeSql(sql, [], () => {
            console.log('FeedbackCategory inserted successfully');
            resolve(true);
          }, (err) => {
            console.log('Insert error in FeedbackCategory:', err);
            reject(err);
          });
        }, (err) => {
          console.log('Delete error before insert FeedbackCategory:', err);
          reject(err);
        });
      });
    });
  };

  async function getData() {
    setLoadingDownload(true);
    try {
      const data1 = {
        Downloadtype: "Master_SurveyQuestion_storeDNA",
        Param1: storeData?.StoreId || '',
        Param2: "",
        username: user_exist_data?.UserId || '',
      };

      const url = "https://di1.parinaam.in/Webservice/GenericService.svc/DownloadJson";
      console.log("Downloading from:", url, data1);

      const res = await getDownloadJson(url, data1);
      console.log('Response:', res);

      if (res?.Master_SurveyQuestion_storeDNA?.length) {
        const data = res.Master_SurveyQuestion_storeDNA || [];
        console.log("Inserting downloaded data into FeedbackCategory...");
        const all = await getAllFromTable('FeedbackCategory');
        // if (all?.length === 0) {
        console.log("Table empty. Inserting fallback mock data...");
        await insertMasterSurveyQuestion(data);
        setLoadingDownload(false);
        // } else {
        //   console.log("FeedbackCategory table already has data."); 
        //   setLoadingDownload(false);
        // }
      } else {
        console.log("No Master_SurveyQuestion_storeDNA data found in response");
        setLoadingDownload(false);
      }
    } catch (err) {
      console.log("Dashboard feedback survey download error:", err);
      setLoadingDownload(false);
    }
  }

  // download data

  // 1. Initial load → download and populate local DB and categories
  useEffect(() => {
    const init = async () => {
      await getData();                  // Download and insert
      await loadCompleted();            // Load completion info
      const data = await getUniqueCategoriesFromDB();  // Load categories
      setUniqueCategories(data);        // Update UI
    };
    init();
  }, []);

  // 2. Every time screen is focused → recheck completed categories and ticks
  useEffect(() => {
    const loadOnFocus = async () => {
      await loadCompleted();
      const data = await getUniqueCategoriesFromDB();
      setUniqueCategories(data);
    };

    const unsubscribe = navigation.addListener('focus', loadOnFocus);
    return unsubscribe;
  }, [navigation]);



  // useEffect(() => {
  //   const init = async () => {
  //     await getData();  // fetch and insert data
  //     await loadCompleted();  // ← added
  //     const data = await getUniqueCategoriesFromDB(); // ← added
  //     setUniqueCategories(data); // ← added
  //   };
  //   init();
  //   //   const unsubscribe = navigation.addListener('focus', loadOnFocus);
  //   // return unsubscribe;

  // }, [navigation]);

  // end download data.

  const isCompleted = (cat) => {
    return completedCategories.find(
      c => c?.CategoryId === cat?.CategoryId && c?.SurveyId === cat?.SurveyId
    );
  };

  const loadCompleted = async () => {
    const d2 = moment().format('MM/DD/YYYY');
    console.log("loaddddd", `SELECT DISTINCT CATEGORY_ID, SURVEY_ID , IFNULL(STATUS , '') AS STATUS FROM FeedBackLocalTable WHERE STORE_ID='${storeData?.StoreId}' AND VISIT_DATE='${d2}'`)
    return new Promise((resolve, reject) => {
      db.transaction(tx => {
        tx.executeSql(
          `SELECT DISTINCT CATEGORY_ID, SURVEY_ID , IFNULL(STATUS , '') AS STATUS FROM FeedBackLocalTable WHERE STORE_ID='${storeData?.StoreId}' AND VISIT_DATE='${d2}'`,
          [],
          (tx, results) => {
            const completed = [];
            for (let i = 0; i < results.rows.length; i++) {
              const row = results.rows.item(i);
              completed.push({
                CategoryId: row.CATEGORY_ID,
                SurveyId: row.SURVEY_ID,
                Status: row.STATUS
              });
            }
            setCompletedCategories(completed);
            // console.log('Completed categories from table:', completed);
            resolve();
          },
          (tx, error) => {
            console.log('DB error loading completed:', error);
            reject(error);
          }
        );
      });
    });
  };

  const getUniqueCategoriesFromDB = () => {
    return new Promise((resolve, reject) => {
      db.transaction(tx => {
        tx.executeSql(
          `SELECT CategoryId, Category, SurveyId, MIN(QuestionSequence) AS minSeq 
           FROM FeedbackCategory 
           GROUP BY CategoryId, Category, SurveyId 
           ORDER BY minSeq ASC`,
          [],
          (tx, results) => {
            const unique = [];
            for (let i = 0; i < results.rows.length; i++) {
              const row = results.rows.item(i);
              unique.push({
                CategoryId: row.CategoryId,
                Category: row.Category,
                SurveyId: row.SurveyId
              });
            }
            resolve(unique);
          },
          (tx, error) => {
            console.log('Error fetching distinct categories:', error);
            reject(error);
          }
        );
      });
    });
  };

  // upload data

  async function Upload_Data() {
    // await saveData("P");
    setLoadingUpload(true);
    const UserId = userId;
    const UploadKeyName = 'Sales_DNA_FeedBack';
    const MID = 0;
    let postData = {};
    let allChilds = [];

    const d2 = moment().format('MM/DD/YYYY');

    await new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        let query = `SELECT * FROM FeedBackLocalTable WHERE STORE_ID='${storeData?.StoreId}' AND VISIT_DATE='${d2}'`;

        console.log("query=====", query)
        await txn.executeSql(
          query,
          [],
          async (txn2, txnres2) => {
            // console.log("Records found:", txnres2.rows.length);

            if (txnres2.rows.length > 0) {
              for (let i = 0; i < txnres2.rows.length; i++) {
                let data = txnres2.rows.item(i);

                let {
                  SURVEY_ID, CATEGORY_ID, MaxLength, MinLength, QuestionImageAllow, QUESTION,
                  QUESTION_ID, QUESTION_TYPE, OTP, ANSWER, ANSWER_ID, IMAGE_ALLOW1, IMAGE1,
                  IMAGE_ALLOW2, IMAGE2, MULTI_OPTIONS_IDS, IS_DISABLED, IS_ENABLED
                } = data;

                let renamedObj = {
                  SurveyId: SURVEY_ID,
                  CategoryId: CATEGORY_ID,
                  QuestionId: QUESTION_ID,
                  QuestionType: QUESTION_TYPE,
                  Answer: ANSWER,
                  AnswerId: ANSWER_ID,
                  MultiOptionsIds: MULTI_OPTIONS_IDS,
                  Image1: IMAGE1,
                  Image2: IMAGE2,
                  ImageAllow1: IMAGE_ALLOW1,
                  ImageAllow2: IMAGE_ALLOW2
                };

                // Fix: IS_DISABLED is expected to be 0 or 1
                let isQtnEnabled = JSON.parse(IS_DISABLED)[QUESTION_ID]
                let obj = {};
                if (isQtnEnabled) {
                  obj['MID'] = 0;
                  obj['UserId'] = userId;
                  // obj['Store_Id'] = '';
                  // obj['MenuId'] = '';
                  obj['SurveyId'] = renamedObj?.SurveyId;
                  obj['CategoryId'] = renamedObj?.CategoryId;
                  obj['QuestionId'] = renamedObj?.QuestionId;
                  obj['QuestionType'] = renamedObj?.QuestionType;
                  obj['Answer'] = renamedObj?.Answer;
                  obj['AnswerId'] = renamedObj?.AnswerId;
                  obj['MultiAnswerId'] = (renamedObj?.MultiOptionsIds != null && renamedObj?.MultiOptionsIds != 'undefined') ? renamedObj?.MultiOptionsIds : '';
                  obj['AnswerImage1'] = renamedObj?.Image1;
                  obj['AnswerImage2'] = renamedObj?.Image2;

                  allChilds.push(obj);
                }
              }

              postData['MID'] = MID;
              postData['Keys'] = UploadKeyName || 'Sales_DNA_FeedBack';
              postData['JsonData'] = JSON.stringify(allChilds);
              postData['UserId'] = UserId;

              resolve({ PostData: postData });
            } else {
              resolve({ PostData: postData });
            }
          },
          (txnE, txnerr) => {
            // console.log('Query error:', txnerr);
            resolve({ PostData: postData });
          }
        );
      });
    }).catch((err) => {
      console.log("Transaction error:", err);
    });

    // console.log("Preparing to upload data...");
    const url = 'https://di1.parinaam.in/Webservice/GenericService.svc/UploadJson';
    console.log("URL:", url);
    console.log("PostData:", postData);

    let allFilesToUpload = await getAllFileForAFolder(FeedbackImagesFolderPath, "Store_DNA");
    console.log('All files to upload:', allFilesToUpload);

    await uploadImagesFormFiles12(allFilesToUpload);

    await UploadData2(url, postData)
      .then(async (res) => {
        // console.log('Upload Response:', res);
        if (res?.UploadJsonResult === "Success") {
          // console.log("Upload successful.");
          try {
            await updateAllUploadStatuses(d2);
            await loadCompleted(); // Refresh the UI with updated STATUS
          } catch (err) {
            console.log("Failed to update status after upload:", err);
          }
          setLoadingUpload(false);
          setShowAlert(false);
        } else {
          console.log("Upload failed.");
          setLoadingUpload(false);

        }
      })
      .catch((err) => {
        console.log("Upload error:", err);
        setLoadingUpload(false);

      });
  }

  async function uploadImagesFormFiles12(allfiles = []) {

    // console.log("allfiles===========", allfiles);
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let uploadCount = 0;
    const url = imageUploadURL;

    var isAllUploaded = false;
    return await Promise.all(
      allfiles.map(async (file, i) => {
        let index = i;
        let actualfilepath = 'file://' + file.uri;
        // console.log("actualfilepath==", actualfilepath);
        let isExists = await RNFS.exists(actualfilepath).then((res) => { return res; });
        console.log('isExists file', isExists, file.uri, file);
        let isImageUploaded = false;
        // isExists==false
        if (isExists) {
          let postData = new FormData();
          postData.append('file', {
            uri: actualfilepath,
            type: file.type,
            name: file.name,
          });

          postData.append('Foldername', "AddNewStoreImages");
          postData.append('Path', d2);

          isImageUploaded = await UploadImagesWithoutWait(postData, url);
          if (isImageUploaded == true) {
            // console.log('isExists file uploaded', isExists, uploadCount, index, allfiles.length - 1);
            await RNFS.unlink(actualfilepath);
            uploadCount++;
            // UpdateUploadCountLocal(uploadCount+1)
            if (uploadCount == allfiles.length) {
              isAllUploaded = true;
            }

          } else {
            console.log('file not uploaded:', isExists, actualfilepath);
          }

        }
        else {//file does not exists 
          uploadCount++;
          // UpdateUploadCountLocal(uploadCount+1)
          if (uploadCount == allfiles.length) {
            isAllUploaded = true;
          }
        }
        return isImageUploaded;
      })
    ).then((val) => {
      console.log(val);
      return isAllUploaded;
    })
      .catch((err) => {
        console.log(err);
        return false;
      })
  }
  // end upload image 
  const areAllCategoriesCompleted = () => {
    return uniqueCategories?.every(cat => isCompleted(cat));
  };

  const areAllCategoriesUploaded = () => {
    return uniqueCategories?.every(cat => {
      const completed = isCompleted(cat);
      return completed?.Status === 'U';
    });
  };

  async function onSubmitData() {
    // let isvalid = await validate();
    if (areAllCategoriesCompleted()) {
      Keyboard.dismiss();
      setShowAlert(true);
    } else {
      toastError("Alert", "Please fill all categories.");
    }
  }

  function onSaveCancel() {
    setShowAlert(false);
  }

  // update status of uploading data 
  const updateFeedbackStatusToUploaded = async (visitDate) => {
    return new Promise((resolve, reject) => {
      db.transaction(tx => {
        tx.executeSql(
          `UPDATE FeedBackLocalTable SET STATUS = 'U' WHERE STORE_ID=? and VISIT_DATE = ?`,
          [storeData?.StoreId, visitDate],
          (_, result) => {
            // console.log("Local STATUS updated to 'U' after upload.");
            resolve(result);
          },
          (tx, error) => {
            console.log("Error updating STATUS locally:", error);
            reject(error);
          }
        );
      });
    });
  };




  const updateUploadStatusForStores = (visitDate) => {
    return new Promise((resolve, reject) => {
      db.transaction(tx => {
        // First: Set uploaded stores to 'U' for the given visit date
        tx.executeSql(
          `
        UPDATE StoreInfoDNALocal
        SET UPLOAD_STATUS = 'U'
        WHERE EXISTS (
          SELECT 1
          FROM FeedBackLocalTable
          WHERE FeedBackLocalTable.STORE_ID = StoreInfoDNALocal.StoreId
            AND FeedBackLocalTable.STATUS = 'U'
            AND FeedBackLocalTable.VISIT_DATE = ?
        )
        AND EXISTS (
          SELECT 1
          FROM FeedBackLocalTable
          WHERE FeedBackLocalTable.STORE_ID = StoreInfoDNALocal.StoreId
            AND FeedBackLocalTable.VISIT_DATE = ?
        )
        `,
          [visitDate, visitDate],
          () => {
            console.log('Uploaded stores marked as U');


            // Second: Set non-uploaded stores to 'P' for the given visit date
            tx.executeSql(
              `
            UPDATE StoreInfoDNALocal
            SET UPLOAD_STATUS = 'P'
            WHERE EXISTS (
              SELECT 1
              FROM FeedBackLocalTable
              WHERE FeedBackLocalTable.STORE_ID = StoreInfoDNALocal.StoreId
                AND FeedBackLocalTable.VISIT_DATE = ?
            )
            AND NOT EXISTS (
              SELECT 1
              FROM FeedBackLocalTable
              WHERE FeedBackLocalTable.STORE_ID = StoreInfoDNALocal.StoreId
                AND FeedBackLocalTable.STATUS = 'U'
                AND FeedBackLocalTable.VISIT_DATE = ?
            )
            `,
              [visitDate, visitDate],
              () => {
                console.log('Pending stores marked as P');
                resolve(true);
              },
              (tx, error) => {
                console.log('Error updating pending stores:', error);
                reject(error);
              }
            );
          },
          (tx, error) => {
            console.log('Error updating uploaded stores:', error);
            reject(error);
          }
        );
      });
    });
  };




  const updateAllUploadStatuses = async (visitDate) => {
    try {
      await updateFeedbackStatusToUploaded(visitDate);
      await updateUploadStatusForStores(visitDate);
      console.log('All upload statuses updated successfully');
    } catch (error) {
      console.log('Error in updating upload statuses:', error);
    }
  };


  return (
    <KeyboardAwareScrollView style={{ flex: 1 }} contentContainerStyle={{ justifyContent: 'center', flex: 1 }}>
      <SafeAreaView style={{ flex: 1, backgroundColor: GlobalTheme.colors.primary }}>
        <View style={{ flex: 1, backgroundColor: GlobalTheme.colors.white }}>
          <CustomHeader
            title="Feedback Categories"
            // rightIcon={IMAGES.menuIcon}
            // onRightPress={() => navigation.navigate('Dashboard')}
            onLeftPress={() => navigation.goBack()}
            leftIcon={IMAGES.backIcon}
          />
          <Loader visible={loading} loadingtext={'Loading ...'} />
          <Loader visible={loadingdownload} loadingtext={'data downloading ...'} />
          <Loader visible={loadingupload} loadingtext={'Uploading Data...'} />
          <ScrollView style={{ flex: 1 }} contentContainerStyle={{ paddingBottom: 10 }}>
            <View style={styles.container}>
              {uniqueCategories?.map((cat, index) => {
                const completedEntry = isCompleted(cat);
                {/* console.log("completedEntry", completedEntry); */ }
                const isUploaded = completedEntry?.Status === 'U';

                {/* console.log("isUploaded", isUploaded); */ }

                return (
                  <TouchableOpacity
                    key={index}
                    disabled={isUploaded} // 👈 disable if already uploaded
                    style={[styles.cardview, styles.categoryItem]} // 👈 visually indicate disabled
                    onPress={() => {
                      if (!isUploaded) {
                        navigation.navigate('Feedback', {
                          CategoryId: cat?.CategoryId,
                          SurveyId: cat?.SurveyId,
                          CategoryName: cat?.Category,
                          storeData: storeData
                        });
                      }
                    }}
                  >
                    <View style={styles.circleIcon}>
                      <Text style={styles.circleText}>{cat.Category?.charAt(0)}</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                      <Text style={styles.categoryName}>{cat.Category}</Text>
                    </View>
                    {isUploaded ? (
                      <Ionicons name="checkmark-done" size={22} color="green" />
                    ) : completedEntry ? (
                      <Icon name="check-circle" size={22} color="green" />
                    ) : null}
                  </TouchableOpacity>
                );
              })}

              {!loading && uniqueCategories.length === 0 && (
                <Text style={{ textAlign: 'center', marginTop: 20 }}>No categories available.</Text>
              )}
            </View>
          </ScrollView>
          <CustomButton
            onPress={() => {
              if (areAllCategoriesUploaded()) return;
              onSubmitData();
            }}
            title={areAllCategoriesUploaded() ? 'Data Uploaded' : 'Upload & Save'}
            style={areAllCategoriesUploaded() ? styles.btnbg1 : styles.btnbg}
            textstyle={areAllCategoriesUploaded() ? styles.btntext1 : styles.btntext}
            disabled={areAllCategoriesUploaded()}
          />

          <ConfirmSaveAlert
            showAlert={showAlert}
            onCancelCallBack={onSaveCancel}
            onYesCallBack={Upload_Data}
            msg="Do you really want to upload data?"
          />

        </View>
      </SafeAreaView>
    </KeyboardAwareScrollView>
  );
};

export default FeedbackCategories;
