import React, { useState, useEffect, useRef, useCallback } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Image, BackHandler, Alert } from 'react-native';
import { mapDispatchToProps, mapStateToProps } from '../../reducers/contextProvider';
import { connect } from 'react-redux';
import { customStyles, GetPageTheme, globalStyles } from '../../styles/Global';
import { useFocusEffect, useRoute } from '@react-navigation/native';
import { AntDesign } from '../../components/icons';
import Mic from '../../assets/image/MICWithCircle.svg';

import { db, GyanCastURL } from '../../constants/constants';
import { notify } from '../../components/notify';
import CustomLoader from '../../components/CustomLoader';
import { getMethodName, METHODS } from '../../constants/methodNames';
import { get_item, set_item } from '../../components/localStorage';
import moment from 'moment';
import { getDownloadJson1, UploadData2 } from '../../controller/functions';
import CompletionModal from '../../components/CompletionModal';

const QUESTION = {
  question: "What does a 'planogram' help with in merchandising?",
  options: [
    'Managing attendance of merchandisers',
    'Arranging products on the shelf as per brand guidelines',
    'Placing posters inside the store',
    'Counting stock in the warehouse',
  ],
  correct: 1,
};

const QuestionnaireScreen = (props) => {
  const [selected, setSelected] = useState(null);
  const [Wrong, setWrong] = useState(false);
  const [RightAns, setRight] = useState(false);
  const [SelectedObj, setSelectedObj] = useState({});
  const [timer, setTimer] = useState(60); // 1:13 in seconds
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkTheme, route.name);
  const globalStyle = globalStyles(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);
  const [PlayerObj, setPlayerObj] = useState({});
  const [TrainingOrg, setTrainingOrg] = useState([]);
  const [Step, setNextStep] = useState(0);
  const [processing, setProcessing] = useState(false);
  const [visible, setVisible] = useState(false);
  const [result, setResult] = useState({});
  let params = props.route.params ? props.route.params : {};
  const backPressStatusRef = useRef(false);


  useEffect(() => {
    let params = props.route.params ? props.route.params : {};
    let PlayerDetail = params.PlayerObj || {};
    let PlayTime = params.PlayTime || {};
    setPlayerObj(PlayerDetail);
    getData(PlayerDetail);
  }, [])

  ///prevent hardware backhandler
  useFocusEffect(
    useCallback(() => {
      const onBackPress = () => {
        if (!backPressStatusRef.current) {
          // ❌ block hardware back
          return true;
        }
        // ✅ allow back
        props.navigation.goBack();
        return true;
      };

      const backHandler = BackHandler.addEventListener(
        'hardwareBackPress',
        onBackPress
      );

      return () => {
        backHandler.remove(); // ✅ RN 0.81 way
      };
    }, [])
  );

  async function getData(PlayerDetail) {
    try {
      let List = [];
      await db.transaction(async function (txn) {
        let q = `Select DISTINCT QuestionId,Question,QuestionType from Gyancast_TrainingContentQuestion where (TrainingId='${PlayerDetail?.TrainingId}' or TrainingId= ${PlayerDetail?.TrainingId})`;
        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);
                let Answers = await getAnswers(data)
                data.options = Answers?.["Answers"] || []
                List.push(data);
              }
              setTrainingOrg(List);
            }
          },
          function (txnE, txnerr) {
            console.log(txnerr);
          }
        );
      });
    } catch (err) {
      console.log(err);
    }
  }

  async function getAnswers(qtn) {
    return new Promise((resolve, reject) => {
      db.transaction(async function (txn) {
        // get inserted audit
        let selectlist = ` DISTINCT T.Answer,T.AnswerId,T.RightAnswer`;
        let q2 = `Select ${selectlist} FROM Gyancast_TrainingContentQuestion T WHERE (T.QuestionId='${qtn.QuestionId}' or T.QuestionId=${qtn.QuestionId}) `;
        await txn.executeSql(q2, [], async function (txn2, txnres) {
          console.log('answers len', txnres.rows.length);
          if (txnres.rows.length > 0) {
            let arr = [];
            for (var i = 0; i < txnres.rows.length; i++) {
              let data = txnres.rows.item(i);
              arr.push(data);
              if (i == txnres.rows.length - 1) {
                resolve(arr);
              }
            }
          }
          else {
            resolve([]);
          }
        }, function (txnE, txnerr) { console.log(txnerr); resolve([]); },);

      });
    }).then((val) => {
      return { 'Answers': val, 'Success': true };
    }).catch((err) => {
      console.log(err);
      return { 'Success': false, 'Error': err }
    });
  }

  useEffect(() => {
    if (timer > 0) {
      const interval = setInterval(() => setTimer(t => t - 1), 1000);
      return () => clearInterval(interval);
    }
  }, [timer]);

  const formatTime = (sec) => {
    const m = Math.floor(sec / 60).toString().padStart(2, '0');
    const s = Math.floor(sec % 60).toString().padStart(2, '0');
    return `${m}:${s}`;
  };

  const goBack = () => {
    // props.navigation.goBack();
  }

  function Submit() {
    if (selected === null || selected === undefined) {
      notify("Please select your answer", 'SHORT');
      return;
    }
    const updatedQuestions = [...TrainingOrg];
    const currentQuestion = { ...updatedQuestions[Step], selected: SelectedObj };
    updatedQuestions[Step] = currentQuestion;
    if (Step === TrainingOrg.length - 1) {
      submitAnswer(updatedQuestions);
    } else {
      console.log("SelectedObj----", SelectedObj, SelectedObj?.RightAnswer)
      if (SelectedObj?.RightAnswer == "false" || SelectedObj?.RightAnswer == false || !SelectedObj?.RightAnswer || SelectedObj?.RightAnswer == 0 || SelectedObj?.RightAnswer == '0') {
        console.log("SelectedObj----11", SelectedObj)
        setWrong(true)
      } else if (SelectedObj?.RightAnswer == "true" || SelectedObj?.RightAnswer == true || SelectedObj?.RightAnswer == 1 || SelectedObj?.RightAnswer == '1') {
        setRight(true)
      }
      setSelectedObj((prev) => prev);
      setTrainingOrg(updatedQuestions);
      setTimeout(() => {
        setTimer(60);
        setNextStep(Step + 1);
        setSelected(null);
        setSelectedObj({});
        setWrong(null)
        setRight(false)
        setWrong(false)
      }, 1000)
    }
  }

  async function submitAnswer(OrgObj) {
    setProcessing(true);
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    let projectInfo = await get_item('projectInfo');
    const projectDetails = JSON.parse(projectInfo);
    const { TrainingId, TrainingContentId } = PlayerObj
    const { ProjectCode, projectName } = projectDetails
    const { Designation, UserId, EmpId, EmployeeName } = loginDetails
    console.log("loginDetails", loginDetails)

    var user_answers = [];
    for (const item of OrgObj) {
      const { QuestionId, selected } = item;
      const { AnswerId, Answer, RightAnswer } = selected
      var ans_obj = {
        TrainingId,
        ProjectCode,
        // projectName,
        QuestionId,
        Answer,
        AnswerId,
        RightAnswer: (RightAnswer == "true" || RightAnswer == true || RightAnswer == 1 || RightAnswer == '1') ? 1 : 0,
        TrainingContentId,
        UserId,
        // userName:EmployeeName,
        EmpId,
        // Designation
      }
      console.log("ans_obj---", ans_obj)
      user_answers.push(ans_obj);
    }

    var Training_Obj = {
      TrainingId,
      PlayTime: moment.utc(params?.PlayTime * 1000).format('HH:mm:ss'),
      WatchStatus: "Complete",
      ProjectCode,
      projectName,
      UserId,
      TrainingContentId,
      userName: EmployeeName,
      EmpId,
      Designation
    }
    let Obj = {
      // Training:Training_Obj,
      TrainingId,
      PlayTime: moment.utc(params?.PlayTime * 1000).format('HH:mm:ss'),
      WatchStatus: "Complete",
      ProjectCode,
      projectName,
      UserId,
      TrainingContentId,
      userName: EmployeeName,
      EmpId,
      Designation,
      Question: user_answers
    }

    let post_data = {
      "MID": "0",
      "Keys": "TrainingQuestionnaire",
      "JsonData": JSON.stringify(Obj),
      "UserId": loginDetails.UserId
    }

    const url = GyanCastURL + getMethodName(METHODS.UPLOAD_JSON_DIRECT);
    console.log('OQAD upload ', url, post_data);
    await UploadData2(url, post_data)
      .then(async (res) => {
        setProcessing(false);
        console.log(res);
        if (res?.success == false) {
          return
        }
        const correctCount = OrgObj?.reduce((count, question) => {
          return (question?.selected?.RightAnswer === "true" || question?.selected?.RightAnswer == true || question?.selected?.RightAnswer == 1 || question?.selected?.RightAnswer == '1') ? count + 1 : count;
        }, 0);

        setResult({ correct: correctCount, wrong: TrainingOrg?.length - correctCount })
        setVisible(true)
        DownloadData();
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });

  }


  async function DownloadData() {
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    let projectInfo = await get_item('projectInfo');
    let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
    const data1 = {
      Downloadtype: "Gyancast_TrainingContent",
      Param1: '',
      Param2: projectDetails?.ProjectCode,
      Username: loginDetails.UserId,
    };


    const url = props.baseurl + getMethodName(METHODS.DOWNLOADJSON_METHOD);
    console.log("Downloading from:", url, data1);
    await UploadData2(url, data1)
      .then(async (res) => {
        let jsonObj = res && JSON.parse(res)
        console.log(jsonObj);
        insertData(jsonObj);
        console.log('res of download get', res);
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });

  }

  const insertData = async (res) => {
    if (res != null && typeof res == 'object' && res.Gyancast_TrainingContent != null && res.Gyancast_TrainingContent != '') {
      let data_arr = res.Gyancast_TrainingContent || [];
      var values = [];
      data_arr.map((data_obj) => {
        let { TrainingId, Topic, Description, MediaType, Mandatory, TrainingContentId, Thumnail, TrainingUrl, Duration, LanguageId, Language, DefaultLang, Status, StartTime, PublishDate, ExpiryDate, TrainingNo } = data_obj;
        console.log("json_insert_data", data_obj)
        values.push(` (${TrainingId},'${Topic}','${Description}','${MediaType}',${(Mandatory == true || Mandatory == "true" || Mandatory == 1 || Mandatory == '1') ? 1 : 0},${TrainingContentId},'${Thumnail}','${TrainingUrl}','${Duration}',${LanguageId},'${Language}',${(DefaultLang == "true" || DefaultLang == 1 || DefaultLang == true || DefaultLang == '1') ? 1 : 0},'${Status}','${StartTime}','${PublishDate}','${ExpiryDate}','${TrainingNo}')`);
      });
      var all_vals = values.join(',');
      var sql_stmnt = `INSERT INTO Gyancast_TrainingContent(TrainingId, Topic, Description, MediaType, Mandatory, TrainingContentId, Thumnail, TrainingUrl, Duration, LanguageId, Language, DefaultLang, Status, StartTime, PublishDate, ExpiryDate,TrainingNo) values ${all_vals}`;
      db.transaction(function (txn) {
        // delete all today data
        txn.executeSql(`delete from Gyancast_TrainingContent where 1=1`, [], function (txn1, txnres) {
          // insert or refresh all today data
          txn.executeSql(sql_stmnt, [], function (txn1, txnres) {
            console.log('Gyancast_TrainingContent added');
            setGyanCast()
          }, function (txnE, txnerr) {
            console.log(txnerr);

          });
        }, function (txnE, txnerr) {
          console.log(txnerr);
        });
      });

    }

  }

  const setGyanCast = async () => {
    let d2 = moment().format('MM/DD/YYYY');
    let newData = {
      Show: true,
      visiteDate: d2
    }
    let WindowsStr = JSON.stringify(newData)
    console.log("GyanCast-----", WindowsStr)
    await set_item('GyanCast', WindowsStr);

  }


  return (
    <View style={styles.container}>
      {processing && <CustomLoader />}
      <View style={[styles.header]}>
        <TouchableOpacity
          style={[customStyle.toggleDrawerBtn, customStyle.headerLeftIcon, { width: '10%', marginLeft: "2%" }]} onPress={() => { props.onPress != null ? props.onPress() : goBack() }}>
          <AntDesign color={'gray'} size={22} name='arrowleft' />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Questionnaire</Text>
      </View>
      {/* Progress bar and timer */}
      <View style={styles.progressRow}>
        <View style={styles.progressBarBg}>
          <View style={[styles.progressBarFill, { width: (TrainingOrg?.length > 0 ? (((Step / (TrainingOrg?.length - 1)) * 100) + '%') : '100%') }]} />
          <View style={[styles.progressBarDot, { left: (TrainingOrg?.length > 0 ? (((Step / (TrainingOrg?.length - 1)) * 100) + '%') : '100%') }]} />
        </View>
        <Text style={styles.progressText}>{Step + 1}/{TrainingOrg?.length}</Text>
        <Text style={styles.timerText}>{formatTime(timer)}</Text>
      </View>
      {/* Question card */}
      <View style={styles.card}>
        <View style={styles.cardHeader}>
          <View style={styles.cardIconWrap}>
            <TouchableOpacity style={[globalStyle.toggleDrawerBtn]} >
              <Mic width={45} height={45} />
            </TouchableOpacity>
          </View>
          <Text style={styles.cardQuestion}>
            {(Step + 1) + ". " + TrainingOrg?.[Step]?.Question}
          </Text>
        </View>
        {/* Options */}
        {TrainingOrg?.[Step]?.options?.map((opt, idx) => (
          <TouchableOpacity
            key={idx}
            style={[styles.option, RightAns && (selected === idx) ? styles.rightSelected : ((Wrong && (selected === idx)) ? styles.wrongSelected : (selected === idx && styles.optionSelected))]}
            onPress={() => { setSelected(idx); setSelectedObj(opt); }}
            activeOpacity={0.8}
          >
            <Text style={[styles.optionText, RightAns && (selected === idx) ? styles.rightTextSelected : ((Wrong && (selected === idx)) ? styles.wrongTextSelected : (selected === idx && styles.optionTextSelected))]}>
              {String.fromCharCode(97 + idx)}) {opt?.Answer}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
      {/* Submit button */}
      <TouchableOpacity style={styles.submitBtn} onPress={Submit}>
        <Text style={styles.submitBtnText}>{TrainingOrg?.length - 1 == Step ? 'Submit' : 'Next'}</Text>
      </TouchableOpacity>
      <CompletionModal
        visible={visible}
        onClose={() => { setVisible(false); props.navigation.reset({ index: 1, routes: [{ name: 'NoticeBoard' }, { name: 'Gyancasts', params: { fromReset: true } }] }) }}
        correct={result?.correct || 0}
        wrong={result?.wrong || 0}
        PlayerObj={PlayerObj}
        total={TrainingOrg?.length}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#e6f0fa',
    paddingTop: 40,
    paddingHorizontal: 0,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  headerIcon: {
    position: 'absolute',
    left: 20,
    fontSize: 24,
    top: 0,
  },
  headerTitle: {
    fontSize: 22,
    fontWeight: 'bold',
    color: '#222',
    marginVertical: 10,
    marginLeft: "22%"
  },
  progressRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
    paddingHorizontal: 20,
  },
  progressBarBg: {
    flex: 1,
    height: 8,
    backgroundColor: '#c7d7e6',
    borderRadius: 8,
    marginRight: 10,
    position: 'relative',
    justifyContent: 'center',
  },
  progressBarFill: {
    position: 'absolute',
    left: 0,
    top: 0,
    height: 8,
    width: '50%',
    backgroundColor: '#3498db',
    borderRadius: 8,
  },
  progressBarDot: {
    position: 'absolute',
    left: '50%',
    top: -4,
    width: 16,
    height: 16,
    borderRadius: 8,
    backgroundColor: '#3498db',
    borderWidth: 2,
    borderColor: '#e6f0fa',
    zIndex: 2,
  },
  progressText: {
    marginLeft: 10,
    fontSize: 16,
    color: '#222',
    fontWeight: 'bold',
  },
  timerText: {
    marginLeft: 16,
    fontSize: 16,
    color: '#3498db',
    fontWeight: 'bold',
  },
  card: {
    backgroundColor: '#fff',
    borderRadius: 12,
    margin: 16,
    padding: 16,
    shadowColor: '#000',
    shadowOpacity: 0.05,
    shadowRadius: 4,
    shadowOffset: { width: 0, height: 2 },
    elevation: 2,
  },
  cardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  cardIconWrap: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#e6f0fa',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 12,
  },
  cardQuestion: {
    flex: 1,
    fontSize: 17,
    color: '#222',
    fontWeight: '500',
  },
  option: {
    borderWidth: 1,
    borderColor: '#c7d7e6',
    borderRadius: 10,
    padding: 14,
    marginBottom: 10,
    backgroundColor: '#f6fafd',
  },
  optionSelected: {
    borderColor: '#3498db',
    backgroundColor: '#e6f0fa',
  },
  wrongSelected: {
    borderColor: '#ff4d4d',
    backgroundColor: '#e6f0fa',
  },
  rightSelected: {
    borderColor: '#70db70',
    backgroundColor: '#e6f0fa',
  },
  optionText: {
    fontSize: 16,
    color: '#222',
  },
  optionTextSelected: {
    color: '#3498db',
    fontWeight: 'bold',
  },
  wrongTextSelected: {
    color: '#ff4d4d',
    fontWeight: 'bold',
  },
  rightTextSelected: {
    color: '#70db70',
    fontWeight: 'bold',
  },
  submitBtn: {
    position: 'absolute',
    left: 16,
    right: 16,
    bottom: 30,
    backgroundColor: '#1793d1',
    borderRadius: 14,
    alignItems: 'center',
    paddingVertical: 14,
    shadowColor: '#1793d1',
    shadowOpacity: 0.15,
    shadowRadius: 4,
    shadowOffset: { width: 0, height: 2 },
    elevation: 2,
  },
  submitBtnText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

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