/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable react-native/no-inline-styles */
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, TouchableOpacity, Image } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import HeaderComponent from 'app/components/HeaderComponent';
import { scale, verticalScale, moderateScale } from 'react-native-size-matters';
import { Icon } from 'react-native-elements';
import * as giohangAction from '../actions';
import apitaoyeucauthanhtoanMoMo from 'app/api/methods/taoyeucauthanhtoanMoMo';
import apixacnhangiaodichMoMo from 'app/api/methods/xacnhangiaodichMoMo';

import { Platform, DeviceEventEmitter, NativeModules, NativeEventEmitter } from 'react-native';
import RNMomosdk from 'react-native-momosdk';
const RNMomosdkModule = NativeModules.RNMomosdk;
const EventEmitter = new NativeEventEmitter(RNMomosdkModule);
const orderID = 1401;
// const orderID = new Date().getTime();
const amount = 12345;

export default function GioHang() {
  const dispatch = useDispatch();
  // console.log(dispatch);
  const { t, i18n } = useTranslation();
  const data_giohang = useSelector((state: any) => state.giohangReducer.infoCartGet);
  const isLoad = useSelector((state: any) => state.giohangReducer.isLoad);
  // console.log(data_giohang);

  let soluonghang: number;
  soluonghang = 0;

  for (let i = 0; i < data_giohang.length; i++) {
    soluonghang += data_giohang[i].cart_total;
  }
  let total: number;
  total = 0;
  for (let i = 0; i < data_giohang.length; i++) {
    for (let j = 0; j < data_giohang[i].giohangchitiet.length; j++) {
      total += parseInt(data_giohang[i].giohangchitiet[j].thanhtien, 10);
    }
  }
  // console.log(total);

  function onPress(id_giohangchitiet: number) {
    dispatch(giohangAction.idGioHangChiTietDelete(id_giohangchitiet));
  }

  function renderItemm({ item }: any) {
    return (
      <>
        <View style={{ backgroundColor: 'white', paddingVertical: moderateScale(20), paddingHorizontal: moderateScale(30), borderWidth: 1, borderColor: '#E8E8E8', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
          <View>
            <Text style={{}}>ID Hàng: {item.id ? item.id : ''}</Text>
            <Text style={{}}>ID Loại Khám: {item.loaikham_id ? item.loaikham_id : ''}</Text>
            <Text style={{}}>Thành tiền: {item.thanhtien ? item.thanhtien : ''}</Text>
          </View>
          <View>
            <TouchableOpacity onPress={() => onPress(item.id)}>
              <Text style={{ textDecorationLine: 'underline' }}>Xóa</Text>
            </TouchableOpacity>
          </View>
        </View>
      </>
    )
  }
  function renderItem({ item }: any) {
    // console.log(item.giohangchitiet);

    return (
      <>
        <View style={{}}>
          <Text style={{ backgroundColor: 'white', paddingVertical: moderateScale(20), paddingHorizontal: moderateScale(20), fontWeight: 'bold', borderWidth: 5, borderColor: '#E8E8E8' }}>ID Giỏ hàng: {item.id ? item.id : ''}</Text>
          <FlatList
            horizontal={false}
            data={item.giohangchitiet}
            renderItem={renderItemm}
            keyExtractor={(itemm, index) => index.toString() + itemm.id}
          />
        </View>
      </>
    )
  }
  function format_money(n: number, currency: string) {
    return n.toFixed(2).replace(/./g, function (c, i, a) {
      return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
    }) + currency;
  }
  let height: number = 8;
  console.log(height);
  
  async function thanhtoan() {
    const jsonData = {enviroment: string};
    jsonData.enviroment = "0"; //SANBOX OR PRODUCTION
    jsonData.action = "gettoken"; //DO NOT EDIT
    jsonData.merchantname = "Family Hospital"; //edit your merchantname here
    jsonData.merchantcode = "MOMOQRIN20201112"; //edit your merchantcode here
    jsonData.merchantnamelabel = "Nhà cung cấp";
    jsonData.description = "Thanh toán dịch vụ khám chữa bệnh tại Family";;
    jsonData.amount = amount;//order total amount
    jsonData.orderId = orderID;
    jsonData.orderLabel = "Ma don hang";
    jsonData.appScheme = "momocgv20170101";// iOS App Only , match with Schemes Indentify from your  Info.plist > key URL types > URL Schemes
    // console.log("data_request_payment " + JSON.stringify(jsonData));
    if (Platform.OS === 'android') {
      let dataPayment = await RNMomosdk.requestPayment(jsonData);
      momoHandleResponse(dataPayment, 0);
    } else {
      RNMomosdk.requestPayment(jsonData);
    }
  }
  async function momoHandleResponse(response, status) {
    try {
      if (response && response.status == status) {
        console.log(response.data);
        const {phonenumber} = response;
        const momoToken = response.data;
        const fetchData_taoyeucauthanhtoan = async () => {
          const response_taoyeucauthanhtoanMoMo = await apitaoyeucauthanhtoanMoMo(
            {
              customerNumber: phonenumber,
              appData: momoToken,
              partnerRefId: orderID,
              amount: amount,
              storeName : 'App',
              storeId : 'App',
            }
          );
          console.log(response_taoyeucauthanhtoanMoMo);
          if (response_taoyeucauthanhtoanMoMo.message === 'Thành công'){
            console.log('Tạo yêu cầu thanh toán thành công!');
            // const fetchData_xacnhangiaodich = async () => {
            //   const response_xacnhangiaodichMoMo = await apixacnhangiaodichMoMo(
            //     {
            //       partnerRefId: orderID,
            //       requestType: 'revertAuthorize', // Xac nhan: capture || Huy bo: revertAuthorize
            //       requestId: orderID,
            //       momoTransId: response_taoyeucauthanhtoanMoMo.transid,
            //       customerNumber: '0938023110',
            //     }
            //   );
            //   if (response_xacnhangiaodichMoMo.message === 'Thành công') {
            //     console.log('Xác nhận giao dịch thành công!');
            //   }
            // };
            // fetchData_xacnhangiaodich();
          }
        };
        fetchData_taoyeucauthanhtoan();
        // dispatch(giohangAction.infoThongTinThanhToanSend({
        //   FromApp: fromapp,
        //   Token: momoToken,
        //   PhoneNumber: phonenumber,
        //   OrderId: message,
        //   Message: orderId,
        // }));
      } else {
        //let message = response.message;
        //Has Error: show message here
      }
    } catch (ex) { }
  }
  useEffect(() => {
    EventEmitter.addListener('RCTMoMoNoficationCenterRequestTokenReceived', (response) => {
      momoHandleResponse(dataPayment, 1);
    });
    //OPTIONAL
    EventEmitter.addListener('RCTMoMoNoficationCenterRequestTokenState', (response) => {
      console.log("<MoMoPay>Listen.RequestTokenState:: " + response.status);
      // status = 1: Parameters valid & ready to open MoMo app.
      // status = 2: canOpenURL failed for URL MoMo app 
      // status = 3: Parameters invalid
    })
  }, []);
  return (
    <>
      <HeaderComponent />
      {isLoad ? <Text style={{ fontStyle: 'italic', marginLeft: moderateScale(10), position: 'relative', top: moderateScale(10) }}>Đang xóa đơn hàng ...</Text> : <Text></Text>}
      <View style={{ flex: 1, marginVertical: moderateScale(15), paddingHorizontal: moderateScale(10) }}>
        <Text style={{ textAlign: 'center', fontWeight: 'bold', transform: [{ scale: 1.2 }], marginBottom: moderateScale(15) }}>GIỎ HÀNG</Text>
        <FlatList
          horizontal={false}
          data={data_giohang}
          renderItem={renderItem}
          // ItemSeparatorComponent={renderSeparator}
          keyExtractor={(item, index) => index.toString() + item.id}
        />
        <View style={{ backgroundColor: 'white', paddingVertical: moderateScale(20), paddingHorizontal: moderateScale(20), borderWidth: 1, borderColor: '#E8E8E8', marginTop: moderateScale(10), flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text style={{ fontWeight: 'bold' }}>Tổng ({soluonghang}):</Text>
          <Text style={{ fontWeight: 'bold' }}>{format_money(total, ' VNĐ')}</Text>
          <TouchableOpacity onPress={() => thanhtoan()}>
            <Text style={{ textDecorationLine: 'underline' }}>Thanh toán</Text>
          </TouchableOpacity>
        </View>
      </View>
    </>
  );
}
