// @ts-nocheck
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import {
  Alert,
  Clipboard,
  Dimensions,
  Image,
  Platform,
  ScrollView,
  StatusBar,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import {
  CloseIcon,
  IconBack,
  IconCopy,
  IconDownload,
  TimaSmall,
} from '../../assets/icons';
import { MText } from '../../components/MText';
import { useNavigation } from '@react-navigation/native';
import { Api } from '../../services/api';
import Loading from '../../components/Loading';
import { CameraRoll } from '@react-native-camera-roll/camera-roll';
import ReactNativeBlobUtil from 'react-native-blob-util';
import { formatMoney } from '../../utils';
import MHeader from '../../components/MHeader';
import ReactNativeModal from 'react-native-modal';
import LinearGradient from 'react-native-linear-gradient';
import moment from 'moment';
import {
  TourGuideProvider, // Main provider
  TourGuideZone, // Main wrapper of highlight component
  useTourGuideController, // hook to start, etc.
} from 'rn-tourguide';
import { load, save } from '../../utils/storage';

export const ShowQrCode = observer(function ShowQrCode(props: any) {
  return (
    <TourGuideProvider
      borderRadius={8}
      maskOffset={4}
      tooltipComponent={TransferContentTooltip}
      tooltipStyle={$tourTooltipPosition}
      backdropColor="rgba(0, 0, 0, 0.35)"
      androidStatusBarVisible={true}
      verticalOffset={
        Platform.OS === 'android' ? StatusBar.currentHeight - 25 : 0
      }
    >
      <ShowQrCodeContent {...props} />
    </TourGuideProvider>
  );
});

const TransferContentTooltip = ({ currentStep, handleStop }: any) => {
  return (
    <View style={$tourTooltip}>
      <MText style={$tourTooltipText}>{currentStep?.text}</MText>
      <TouchableOpacity onPress={handleStop} style={$tourTooltipButton}>
        <MText style={$tourTooltipButtonText}>Đồng ý</MText>
      </TouchableOpacity>
      <View style={$tourTooltipArrow} />
    </View>
  );
};

const ShowQrCodeContent = observer(function ShowQrCodeContent(props: any) {
  const navigation = useNavigation();
  const scrollViewRef = useRef<ScrollView>(null);
  const transferContentRef = useRef<View>(null);
  const transferContentY = useRef(0);
  const transferContentHeight = useRef(0);
  const scrollViewHeight = useRef(0);
  const scrollContentHeight = useRef(0);
  const startGuideTimeout = useRef<NodeJS.Timeout>();
  const [linkImage, setLinkImage] = useState<string>();
  const [isLoading, setIsLoading] = useState(false);
  const [showGuide, setShowGuide] = useState(false);
  const [shouldStartGuide, setShouldStartGuide] = useState(false);
  const [isGuideRunning, setIsGuideRunning] = useState(false);
  const {
    canStart, // a boolean indicate if you can start tour guide
    start, // a function to start the tourguide
    eventEmitter,
  } = useTourGuideController();

  const getData = () => {
    setIsLoading(true);
    Api.getInstance()
      .getQrPayment({
        LoanBriefId: props?.route?.params?.id,
        TypeCloseLoan: props?.route?.params?.isFullPayment ? 1 : 0, // đóng tiền kỳ
        Money: props?.route?.params?.isFullPayment
          ? props?.route?.params?.totalMoney
          : props?.route?.params?.item?.payMoney,
      })
      .then((response) => {
        setIsLoading(false);
        if (response.kind === 'ok') {
          if (response.data.meta.errorCode === 200) {
            setLinkImage(response.data?.data?.fullPath);
            if (props?.route?.params?.isFullPayment) {
              setTimeout(() => {
                setShowGuide(true);
              }, 300);
            } else {
              setShouldStartGuide(true);
            }
          } else {
            Alert.alert('Thông báo', response?.data?.meta?.errorMessage);
          }
        } else {
          Alert.alert('Thông báo', 'Có lỗi xảy ra. Vui lòng thử lại sau');
        }
      })
      .catch((err) => {
        Alert.alert('Thông báo', 'Có lỗi xảy ra. Vui lòng thử lại sau');
        setIsLoading(false);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  useEffect(() => {
    getData();
  }, []);

  useEffect(() => {
    const handleStartGuide = () => setIsGuideRunning(true);
    const handleStopGuide = () => setIsGuideRunning(false);
    eventEmitter?.on('start', handleStartGuide);
    eventEmitter?.on('stop', handleStopGuide);
    return () => {
      eventEmitter?.off('start', handleStartGuide);
      eventEmitter?.off('stop', handleStopGuide);
    };
  }, [eventEmitter]);

  const scrollToTransferContent = () => {
    const scrollToY = (
      y: number,
      targetHeight = transferContentHeight.current
    ) => {
      const viewportHeight =
        scrollViewHeight.current || Dimensions.get('window').height;
      const contentHeight = scrollContentHeight.current || viewportHeight;
      const maxScrollY = Math.max(contentHeight - viewportHeight, 0);
      const minTopForTooltip = 120;
      const bottomGap = 80;
      const preferredTargetTop = Math.min(
        Math.max(viewportHeight * 0.42, minTopForTooltip),
        Math.max(viewportHeight - targetHeight - bottomGap, minTopForTooltip)
      );
      const nextScrollY = Math.min(
        Math.max(y - preferredTargetTop, 0),
        maxScrollY
      );

      scrollViewRef.current?.scrollTo({
        y: nextScrollY,
        animated: true,
      });
    };

    const innerViewNode = scrollViewRef.current?.getInnerViewNode?.();

    if (innerViewNode && transferContentRef.current?.measureLayout) {
      transferContentRef.current.measureLayout(
        innerViewNode,
        (_x, y, _width, height) => scrollToY(y, height),
        () => scrollToY(transferContentY.current)
      );
    } else {
      scrollToY(transferContentY.current);
    }
  };

  const startGuide = async () => {
    const guide = await load('show_guide_qr_code');
    if (!guide) {
      scrollToTransferContent();
      startGuideTimeout.current = setTimeout(() => {
        start(1);
        setShouldStartGuide(false);
        save('show_guide_qr_code', 'true');
      }, 450);
    } else {
      setShouldStartGuide(false);
    }
  };

  useEffect(() => {
    if (!props?.route?.params?.isFullPayment && shouldStartGuide && canStart) {
      startGuide();
    }

    return () => {
      if (startGuideTimeout.current) {
        clearTimeout(startGuideTimeout.current);
      }
    };
  }, [canStart, shouldStartGuide, start]);

  return (
    <View style={{ flex: 1, backgroundColor: 'rgba(244, 244, 244, 1)' }}>
      <MHeader title={`Vay trực tuyến 24/7`} />
      <View style={{ flex: 1 }}>
        <View style={$header}>
          <TouchableOpacity
            style={$backButton}
            onPress={() => navigation.goBack()}
          >
            <IconBack />
          </TouchableOpacity>
          <MText
            style={{
              fontSize: 16,
              fontWeight: '600',
              fontFamily: 'BeVietnamPro-SemiBold',
            }}
          >
            {props?.route?.params?.isFullPayment
              ? 'TẤT TOÁN HỢP ĐỒNG'
              : 'THANH TOÁN KỲ'}
          </MText>
        </View>
        <ScrollView
          ref={scrollViewRef}
          scrollEnabled={!isGuideRunning}
          onLayout={(event) => {
            scrollViewHeight.current = event.nativeEvent.layout.height;
          }}
          onContentSizeChange={(_width, height) => {
            scrollContentHeight.current = height;
          }}
        >
          <View
            style={{
              backgroundColor: 'white',
              marginHorizontal: 16,
              borderRadius: 16,
              padding: 16,
            }}
          >
            <MText
              style={{
                textAlign: 'center',
                fontSize: 12,
                fontWeight: '300',
              }}
            >
              Để thanh toán hợp đồng, vui lòng chuyển khoản tới
            </MText>
            <MText
              style={{
                textAlign: 'center',
                fontSize: 12,
                fontWeight: '600',
                color: 'rgba(51, 51, 51, 1)',
                marginTop: 4,
              }}
            >
              {props?.route?.params?.data?.bankName}
            </MText>

            <View
              style={{
                height: 1,
                backgroundColor: 'rgba(224, 224, 224, 1)',
                marginVertical: 10,
              }}
            />
            <View
              style={{
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <Image
                source={{
                  uri: linkImage,
                }}
                style={{
                  width: Dimensions.get('window').width - 100,
                  height: Dimensions.get('window').width - 100,
                  resizeMode: 'contain',
                }}
              />
              <TouchableOpacity
                style={{
                  marginTop: 10,
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 5,
                  backgroundColor: '#FFF7F0',
                  borderWidth: 1,
                  borderColor: '#EF592E',
                  borderRadius: 4,
                  paddingHorizontal: 8,
                  paddingVertical: 4,
                }}
                onPress={async () => {
                  ReactNativeBlobUtil.config({
                    fileCache: true,
                    appendExt: 'png',
                  })
                    .fetch('GET', linkImage) //GET request to URL which has your file
                    .then((res) => {
                      console.log(res);
                      CameraRoll.saveAsset(res.data, { type: 'photo' })
                        .then(() => {
                          Alert.alert('Thông báo', 'Tải mã QR thành công');
                        })
                        .catch((error) => {
                          Alert.alert(
                            'Thông báo',
                            'Có lỗi xảy ra. Vui lòng thử lại sau'
                          );
                          console.log(error);
                        });
                    })
                    .catch((error) => {
                      console.log(error);
                      Alert.alert(
                        'Thông báo',
                        'Có lỗi xảy ra. Vui lòng thử lại sau'
                      );
                    });
                }}
              >
                <IconDownload />
                <MText
                  style={{
                    color: 'rgba(51, 51, 51, 1)',
                    fontSize: 12,
                  }}
                >
                  Tải mã QR
                </MText>
              </TouchableOpacity>
            </View>
            <View
              style={{
                height: 1,
                backgroundColor: 'rgba(224, 224, 224, 1)',
                marginVertical: 10,
              }}
            />
            <View>
              <MText
                style={{
                  fontSize: 12,
                  color: 'rgba(51, 51, 51, 1)',
                  fontWeight: '300',
                  marginTop: 16,
                }}
              >
                Số tài khoản
              </MText>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}
              >
                <MText
                  style={{
                    color: 'rgba(61, 61, 61, 1)',
                    fontWeight: '600',
                    fontSize: 16,
                    fontFamily: 'BeVietnamPro-SemiBold',
                  }}
                >
                  {props.route.params?.data?.accountNumber}
                </MText>
                <TouchableOpacity
                  onPress={() =>
                    Clipboard.setString(props.route.params?.data?.accountNumber)
                  }
                >
                  <IconCopy />
                </TouchableOpacity>
              </View>
              <MText
                style={{
                  fontSize: 12,
                  color: 'rgba(51, 51, 51, 1)',
                  fontWeight: '300',
                  marginTop: 16,
                }}
              >
                Tên tài khoản thụ hưởng
              </MText>
              <MText
                style={{
                  color: 'rgba(61, 61, 61, 1)',
                  fontWeight: '600',
                  fontSize: 16,
                  fontFamily: 'BeVietnamPro-SemiBold',
                }}
              >
                {props.route.params?.data?.accountName}
              </MText>

              <View>
                <MText
                  style={{
                    fontSize: 12,
                    color: 'rgba(51, 51, 51, 1)',
                    fontWeight: '300',
                    marginTop: 16,
                  }}
                >
                  Số tiền phải trả
                </MText>
                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  }}
                >
                  <MText
                    style={{
                      fontSize: 16,
                      fontWeight: '600',
                      fontFamily: 'BeVietnamPro-SemiBold',
                    }}
                  >
                    {formatMoney(
                      props?.route?.params?.isFullPayment
                        ? props?.route?.params?.totalMoney
                        : props?.route?.params?.item?.payMoney
                    )}{' '}
                    đ
                  </MText>
                  <TouchableOpacity
                    onPress={() =>
                      Clipboard.setString(
                        props?.route?.params?.isFullPayment
                          ? props?.route?.params?.totalMoney
                          : props?.route?.params?.item?.payMoney
                      )
                    }
                  >
                    <IconCopy />
                  </TouchableOpacity>
                </View>
                <MText
                  style={{
                    color: '#828282',
                    fontSize: 10,
                    fontStyle: 'italic',
                  }}
                >
                  Số tiền được tính đến ngày {moment().format('DD/MM/YYYY')}
                </MText>
              </View>
              <TourGuideZone
                zone={1}
                text={
                  'Để hệ thống ghi nhận chính xác khoản thanh toán, bạn đừng quên sao chép đúng nội dung chuyển khoản nhé!'
                }
                tooltipBottomOffset={-45}
                style={$transferGuideZone}
              >
                <View>
                  <MText
                    style={{
                      fontSize: 12,
                      color: 'rgba(51, 51, 51, 1)',
                      fontWeight: '300',
                    }}
                  >
                    Nội dung chuyển khoản{' '}
                    <MText
                      style={{
                        fontSize: 12,
                        color: '#EB5757',
                        fontWeight: '300',
                      }}
                    >
                      (Bắt buộc)
                    </MText>
                  </MText>
                  <View
                    ref={transferContentRef}
                    onLayout={(event) => {
                      transferContentY.current = event.nativeEvent.layout.y;
                      transferContentHeight.current =
                        event.nativeEvent.layout.height;
                    }}
                    style={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                    }}
                  >
                    <MText
                      style={{
                        color: 'rgba(61, 61, 61, 1)',
                        fontWeight: '600',
                        fontSize: 16,
                        fontFamily: 'BeVietnamPro-SemiBold',
                      }}
                    >
                      {props?.route?.params?.isFullPayment
                        ? `Tat toan TC${props.route.params?.data?.codeId}`
                        : `TC${props.route.params?.data?.codeId}`}
                    </MText>
                    <TouchableOpacity
                      onPress={() =>
                        Clipboard.setString(
                          props?.route?.params?.isFullPayment
                            ? `Tat toan TC${props.route.params?.data?.codeId}`
                            : `TC${props.route.params?.data?.codeId}`
                        )
                      }
                    >
                      <IconCopy />
                    </TouchableOpacity>
                  </View>
                </View>
              </TourGuideZone>
            </View>
            <View
              style={{
                backgroundColor: '#FFF2F2',
                padding: 10,
                borderRadius: 8,
                marginTop: 16,
              }}
            >
              <MText
                style={{
                  color: '#EB5757',
                  fontSize: 12,
                  fontWeight: '600',
                  fontFamily: 'BeVietnamPro-SemiBold',
                }}
              >
                *Lưu ý:
              </MText>
              <MText
                style={{
                  fontSize: 12,
                }}
              >
                - Vui lòng sao chép đúng và đầy đủ nội dung thanh toán để hệ
                thống ghi nhận giao dịch
              </MText>
              <MText
                style={{
                  fontSize: 12,
                }}
              >
                - Thông tin tài khoản dịch vụ hỗ trợ thu hộ cung cấp bởi GPay.
                Tài khoản chuyên dụng này chỉ dành cho mục đích trả nợ của bên
                đi vay.
              </MText>
            </View>
          </View>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              padding: 16,
              marginBottom: 16,
            }}
          >
            <MText>Hướng dẫn chuyển tiền</MText>
            <TouchableOpacity
              onPress={() => {
                if (props?.route?.params?.isFullPayment) {
                  setShowGuide(true);
                } else {
                  navigation.push('GuideTransferBank');
                }
              }}
            >
              <MText
                style={{ color: '#2F80ED', textDecorationLine: 'underline' }}
              >
                Xem chi tiết
              </MText>
            </TouchableOpacity>
          </View>
        </ScrollView>
        {props?.route?.params?.isFullPayment && (
          <TouchableOpacity
            style={{ margin: 16 }}
            onPress={() => {
              Alert.alert(
                'Xác nhận tất toán',
                'Bạn có chắc muốn gửi YÊU CẦU TẤT TOÁN hợp đồng không?',
                [
                  {
                    text: 'Có',
                    onPress: async () => {
                      const response =
                        await Api.getInstance().confirm_final_settlement({
                          loanBriefId: props?.route?.params?.id,
                        });
                      if (
                        response.kind === 'ok' &&
                        response.data?.meta?.errorCode === 200
                      ) {
                        Alert.alert(
                          'GỬI YÊU CẦU THÀNH CÔNG!',
                          'Yêu cầu tất toán đang được Tima xử lý, vui lòng chờ trong ít phút.',
                          [
                            {
                              text: 'Đồng ý',
                              onPress: () => {
                                navigation.navigate('Main');
                              },
                            },
                          ]
                        );
                      } else {
                        Alert.alert(
                          'Thông báo',
                          response?.data?.meta?.errorMessage ||
                            'Có lỗi xảy ra. Vui lòng thử lại sau'
                        );
                      }
                    },
                  },
                  {
                    text: 'Không',
                  },
                ]
              );
            }}
          >
            <LinearGradient
              colors={['#FF7A00', '#EF4123']}
              style={{
                alignItems: 'center',
                borderRadius: 30,
                height: 40,
                justifyContent: 'center',
              }}
            >
              <MText
                style={{
                  color: 'white',
                }}
              >
                Xác nhận tất toán
              </MText>
            </LinearGradient>
          </TouchableOpacity>
        )}
      </View>
      <Loading isLoading={isLoading} />
      <ReactNativeModal
        isVisible={showGuide}
        onBackdropPress={() => setShowGuide(false)}
        style={{ justifyContent: 'flex-end', margin: 0 }}
      >
        <View
          style={{
            backgroundColor: 'white',
            borderTopLeftRadius: 30,
            borderTopRightRadius: 30,
          }}
        >
          <LinearGradient
            colors={['#FF8E4F', '#EF592E']}
            style={{
              borderTopLeftRadius: 30,
              borderTopRightRadius: 30,
              paddingBottom: 24,
            }}
          >
            <View style={{ padding: 16, alignItems: 'center', gap: 4 }}>
              <MText
                style={{
                  fontSize: 16,
                  fontWeight: '600',
                  color: 'white',
                  fontFamily: 'BeVietnamPro-SemiBold',
                }}
              >
                CÁC BƯỚC TẤT TOÁN
              </MText>
              <MText
                style={{
                  fontSize: 12,
                  color: 'white',
                }}
              >
                Có 2 bước, vui lòng đọc kĩ thông tin
              </MText>
            </View>
          </LinearGradient>
          <View
            style={{
              backgroundColor: 'white',
              borderTopLeftRadius: 30,
              borderTopRightRadius: 30,
              top: -24,
              padding: 16,
            }}
          >
            <MText
              style={{
                fontWeight: '600',
                fontFamily: 'BeVietnamPro-SemiBold',
                color: '#EF592E',
              }}
            >
              BƯỚC 1: CHUYỂN KHOẢN
            </MText>
            <MText
              style={{
                fontWeight: '600',
                fontFamily: 'BeVietnamPro-SemiBold',
                marginTop: 8,
              }}
            >
              Cách 1: Thanh toán bằng QR (Khuyến nghị)
            </MText>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 8,
                marginTop: 8,
              }}
            >
              <TimaSmall />
              <MText style={{ flex: 1, fontSize: 12 }}>
                Lưu hoặc quét mã QR
              </MText>
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 8,
                marginTop: 8,
              }}
            >
              <TimaSmall />
              <MText style={{ flex: 1, fontSize: 12 }}>
                Mở app ngân hàng và thanh toán
              </MText>
            </View>
            <View
              style={{
                height: 1,
                backgroundColor: 'rgba(224, 224, 224, 1)',
                marginVertical: 10,
              }}
            />
            <MText
              style={{
                fontWeight: '600',
                fontFamily: 'BeVietnamPro-SemiBold',
              }}
            >
              Cách 2: Chuyển khoản thủ công
            </MText>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 8,
                marginTop: 8,
              }}
            >
              <TimaSmall />
              <MText style={{ flex: 1, fontSize: 12 }}>
                Copy thông tin tài khoản (Số TK, Ngân hàng, Số tiền)
              </MText>
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 8,
                marginTop: 8,
              }}
            >
              <TimaSmall />
              <MText style={{ flex: 1, fontSize: 12 }}>
                <MText
                  style={{
                    color: '#EB5757',
                    fontSize: 12,
                    fontWeight: '600',
                    fontFamily: 'BeVietnamPro-SemiBold',
                  }}
                >
                  BẮT BUỘC:
                </MText>{' '}
                Copy đúng “Nội dung chuyển khoản”
              </MText>
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 8,
                marginTop: 8,
              }}
            >
              <TimaSmall />
              <MText style={{ flex: 1, fontSize: 12 }}>
                Mở app ngân hàng và thanh toán
              </MText>
            </View>
            <View
              style={{
                height: 12,
                backgroundColor: '#FFF3E9',
                marginVertical: 10,
                marginHorizontal: -16,
              }}
            />
            <MText
              style={{
                fontWeight: '600',
                fontFamily: 'BeVietnamPro-SemiBold',
                color: '#EF592E',
              }}
            >
              BƯỚC 2:
            </MText>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 8,
                marginTop: 8,
              }}
            >
              <TimaSmall />
              <MText style={{ flex: 1, fontSize: 12 }}>
                Chọn “Xác nhận tất toán” để gửi yêu cầu tới Tima thực hiện “Tất
                toán hợp đồng”
              </MText>
            </View>
          </View>
          <TouchableOpacity
            style={{ position: 'absolute', left: 16, top: 16 }}
            onPress={() => setShowGuide(false)}
          >
            <CloseIcon />
          </TouchableOpacity>
        </View>
      </ReactNativeModal>
    </View>
  );
});
const $backButton: ViewStyle = {
  position: 'absolute',
  left: 16,
};

const $header: ViewStyle = {
  flexDirection: 'row',
  alignItems: 'center',
  paddingVertical: 16,
  justifyContent: 'center',
};

const $tourTooltipPosition: ViewStyle = {
  alignItems: 'flex-end',
  overflow: 'visible',
  paddingHorizontal: 16,
  paddingTop: 0,
  paddingBottom: 0,
  borderRadius: 0,
};

const $tourTooltip: ViewStyle = {
  width: 224,
  minHeight: 84,
  backgroundColor: 'white',
  borderRadius: 8,
  paddingHorizontal: 12,
  paddingTop: 10,
  paddingBottom: 12,
  shadowColor: '#000',
  shadowOffset: { width: 0, height: 2 },
  shadowOpacity: 0.18,
  shadowRadius: 8,
  elevation: 8,
};

const $tourTooltipText = {
  color: '#333333',
  fontSize: 10,
  lineHeight: 16,
  fontWeight: '400',
};

const $tourTooltipButton: ViewStyle = {
  alignSelf: 'flex-end',
  marginTop: 6,
};

const $tourTooltipButtonText = {
  color: '#EF592E',
  fontSize: 10,
  lineHeight: 16,
  textDecorationLine: 'underline',
};

const $tourTooltipArrow: ViewStyle = {
  position: 'absolute',
  right: 18,
  bottom: -10,
  width: 0,
  height: 0,
  borderLeftWidth: 8,
  borderRightWidth: 8,
  borderTopWidth: 10,
  borderLeftColor: 'transparent',
  borderRightColor: 'transparent',
  borderTopColor: 'white',
};

const $transferGuideZone: ViewStyle = {
  backgroundColor: 'white',
  borderRadius: 8,
  borderWidth: 2,
  borderColor: 'white',
  marginTop: 16,
};
