import { RouteProp, useRoute } from '@react-navigation/native';
import { useQuery } from '@tanstack/react-query';
import { authApi } from 'api/auth';
import exchanges_api from 'api/exchanges';
import AppText from 'components/AppText';
import LayoutTwo from 'components/LayoutTwo';
import { formatPrice } from 'helpers/formatPrice';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import {
  Dimensions,
  Image,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Circle, Path } from 'react-native-svg';
import { PaymentStyle } from 'screens/wallet/payment/ui/style';
import ModalCard from 'screens/wallet/paymentMethod/ui/ModalCard';
import ModalPay from 'screens/wallet/paymentMethod/ui/ModalPay';
import ModalSuccess from 'screens/wallet/paymentMethod/ui/ModalSuccess';
import Plane from 'svg/Plane';

const PaymentQrCode = () => {
  const { t } = useTranslation();
  const [selectedId, setSelectedId] = React.useState<'card' | 'pay' | null>(
    null,
  );
  const route = useRoute<RouteProp<any, 'PaymentMethod'>>();
  const packets = route.params?.packets;
  const [selectedCard, setSelectedCard] = React.useState<
    'click' | 'payme' | null
  >(null);
  const { data } = useQuery({
    queryKey: ['exchanges'],
    queryFn: () => exchanges_api.getExchanges(),
  });

  const { bottom } = useSafeAreaInsets();
  const [isModalVisible, setModalVisible] = React.useState(false);
  const toggleModal = () => setModalVisible(true);
  const [cardModal, setCardModal] = React.useState(false);
  const [payModal, setPayModal] = React.useState(false);
  const [success, setSuccess] = React.useState(false);
  const { data: getMe } = useQuery({
    queryKey: ['getMe'],
    queryFn: authApi.getMe,
  });

  const screenWidth = Dimensions.get('window').width;
  const isSmallScreen = screenWidth < 380;
  const svgWidth = screenWidth * 0.8;
  const svgWidthProduct = screenWidth * 1;

  const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(
    packets.qrCode,
  )}`;

  return (
    <LayoutTwo title={t("To'lov usuli")}>
      <ScrollView
        style={PaymentStyle.containerMethod}
        contentContainerStyle={{ paddingBottom: 80 }}
      >
        <View style={PaymentStyle.cardMethod}>
          <View style={PaymentStyle.planeContainer}>
            <View style={{ position: 'relative', width: 200, height: 100 }}>
              <Svg height="80" width="200">
                <Circle cx="15" cy="60" r="15" fill="#313133" />
                <Circle cx="15" cy="60" r="7.5" fill="#3D3C3F" />
                <Circle cx="15" cy="60" r="3.5" fill="#28A7E8" />
                <Path
                  d="M 15 60 Q 100 0 185 60"
                  stroke="#8C8A93"
                  strokeWidth="2"
                  fill="none"
                  strokeDasharray="6"
                />
                <Circle cx="185" cy="60" r="15" fill="#313133" />
                <Circle cx="185" cy="60" r="7.5" fill="#3D3C3F" />
                <Circle cx="185" cy="60" r="3.5" fill="#28A7E8" />
              </Svg>
              <View style={PaymentStyle.planeIcon}>
                <Plane width={50} height={50} color="#DCDEE3" />
              </View>
            </View>
          </View>
          <View style={PaymentStyle.infoCard}>
            <View
              style={[
                PaymentStyle.info,
                isSmallScreen
                  ? { flexBasis: '48%', alignItems: 'flex-start' }
                  : { flexBasis: '48%', alignItems: 'flex-start' },
              ]}
            >
              {data && (
                <>
                  <AppText style={PaymentStyle.titleMethod}>
                    {data[0].code}
                  </AppText>
                  <AppText style={PaymentStyle.textMethod}>
                    {data[0].rate} UZS
                  </AppText>
                </>
              )}
            </View>

            {/* <View
              style={[
                PaymentStyle.info,
                isSmallScreen
                  ? { flexBasis: '48%', alignItems: 'flex-end' }
                  : { flexBasis: '48%', alignItems: 'flex-end' },
              ]}
            >
              <AppText style={PaymentStyle.titleMethod}>Cargo</AppText>
              <AppText style={PaymentStyle.textMethod}>12.267 UZS/ kg</AppText>
            </View> */}

            {/* <View
              style={[
                PaymentStyle.info,
                isSmallScreen
                  ? { flexBasis: '48%', alignItems: 'flex-start' }
                  : { flexBasis: '48%', alignItems: 'flex-start' },
              ]}
            >
              <AppText style={PaymentStyle.titleMethod}>
                {t('Yetkazish vaqti')}
              </AppText>
              <AppText style={PaymentStyle.textMethod}>{}</AppText>
            </View> */}

            <View
              style={[
                PaymentStyle.info,
                isSmallScreen
                  ? { flexBasis: '48%', alignItems: 'flex-end' }
                  : { flexBasis: '48%', alignItems: 'flex-end' },
              ]}
            >
              <AppText style={PaymentStyle.titleMethod}>{t('Reys')}</AppText>
              <AppText style={[PaymentStyle.textMethod, { textAlign: 'left' }]}>
                {packets.packetName}
              </AppText>
            </View>
          </View>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: 30,
            }}
          >
            <View
              style={{
                backgroundColor: '#28a8e80c',
                width: 30,
                height: 30,
                borderRadius: 60,
                position: 'absolute',
                left: -15,
              }}
            />
            <Svg height="1" width={svgWidth}>
              <Path
                d={`M 15 0 Q ${svgWidth} 0 ${svgWidth} 0`}
                stroke="#8C8A93"
                strokeWidth="2"
                fill="none"
                strokeDasharray="6"
              />
            </Svg>
            <View
              style={{
                backgroundColor: '#28A7E81A',
                width: 30,
                height: 30,
                borderRadius: 60,
                position: 'absolute',
                right: -15,
              }}
            />
          </View>
          {packets.items.map((item: any, index: number) => {
            return (
              <View key={index} style={{ marginBottom: 15 }}>
                <View style={PaymentStyle.receiptCard}>
                  <View style={PaymentStyle.rowBetween}>
                    <View style={{ width: '100%' }}>
                      <AppText style={PaymentStyle.itemName}>
                        {item.name}
                      </AppText>
                      <AppText style={PaymentStyle.track}>
                        {t('Trek ID')}: {item.trekId}
                      </AppText>
                    </View>
                  </View>
                  <View style={PaymentStyle.rowBetween}>
                    <AppText style={PaymentStyle.weight}>
                      {t('Og’irligi')}: {item.weight} kg
                    </AppText>
                    <AppText style={PaymentStyle.price}>
                      {t('Narxi')}: {item.price}$
                    </AppText>
                  </View>
                  <View style={PaymentStyle.rowRight}>
                    <AppText style={PaymentStyle.total}>
                      {t('Umumiy narxi')}: {item.totalPrice} $
                    </AppText>
                  </View>
                </View>
                <Svg height="1" width={svgWidthProduct}>
                  <Path
                    d={`M 0 0 Q ${svgWidthProduct} 0 ${svgWidthProduct} 0`}
                    stroke="#8C8A93"
                    strokeWidth="2"
                    fill="none"
                    strokeDasharray="9"
                  />
                </Svg>
              </View>
            );
          })}
          <View style={PaymentStyle.infoCard}>
            <View
              style={[
                PaymentStyle.info,
                isSmallScreen
                  ? { flexBasis: '48%', alignItems: 'flex-start' }
                  : { flexBasis: '48%', alignItems: 'flex-start' },
              ]}
            >
              <AppText style={PaymentStyle.titleMethod}>
                {t('Umumiy narxi')}
              </AppText>
            </View>

            <View
              style={[
                PaymentStyle.info,
                isSmallScreen
                  ? { flexBasis: '48%', alignItems: 'flex-end' }
                  : { flexBasis: '48%', alignItems: 'flex-end' },
              ]}
            >
              <AppText style={PaymentStyle.titleMethod}>
                {formatPrice(packets.totalPrice)} {t('so‘m')}
              </AppText>
            </View>
            <View
              style={{ alignItems: 'center', marginTop: 10, margin: 'auto' }}
            >
              <View
                style={{
                  width: 200,
                  height: 200,
                  position: 'relative',
                  backgroundColor: '#fff',
                  padding: 10,
                }}
              >
                <Image
                  source={{ uri: qrUrl }}
                  style={{ width: '100%', height: '100%' }}
                  resizeMode="contain"
                />

                {/* Top-left */}
                <View
                  style={[
                    styles.cornerStyle,
                    { top: 0, left: 0, borderColor: '#0072FF' },
                  ]}
                />
                {/* Top-right */}
                <View
                  style={[
                    styles.cornerStyle,
                    {
                      top: 0,
                      right: 0,
                      borderColor: '#0072FF',
                      transform: [{ rotate: '90deg' }],
                    },
                  ]}
                />
                {/* Bottom-left */}
                <View
                  style={[
                    styles.cornerStyle,
                    {
                      bottom: 0,
                      left: 0,
                      borderColor: '#0072FF',
                      transform: [{ rotate: '-90deg' }],
                    },
                  ]}
                />
                {/* Bottom-right */}
                <View
                  style={[
                    styles.cornerStyle,
                    {
                      bottom: 0,
                      right: 0,
                      borderColor: '#007AFF',
                      transform: [{ rotate: '180deg' }],
                    },
                  ]}
                />
              </View>
            </View>
          </View>
        </View>
      </ScrollView>
      <ModalPay
        packId={packets.id}
        paymentType={packets.paymentType}
        paymentStatus={packets.paymentStatus}
        isModalVisible={isModalVisible}
        selectedId={selectedId}
        setModalVisible={setModalVisible}
        setSelectedId={setSelectedId}
        cardModal={cardModal}
        setCardModal={setCardModal}
        payModal={payModal}
        setPayModal={setPayModal}
        success={success}
        setSuccess={setSuccess}
      />
      {cardModal && (
        <ModalCard
          isVisible={cardModal}
          packId={packets.id}
          setIsVisible={setCardModal}
          selectedId={selectedCard}
          setSelectedId={setSelectedCard}
        />
      )}
      {success && (
        <ModalSuccess
          visible={success}
          setVisible={setSuccess}
          setPayModal={setPayModal}
        />
      )}
      {getMe && !getMe.aviaCargoId.includes('CP') && (
        <>
          {packets.paymentStatus !== 'PAYED' && (
            <TouchableOpacity
              style={[PaymentStyle.button, { bottom: bottom + 80 }]}
              onPress={toggleModal}
            >
              <AppText style={PaymentStyle.btnText}>{t("To'lash")}</AppText>
            </TouchableOpacity>
          )}
        </>
      )}
    </LayoutTwo>
  );
};

export default PaymentQrCode;

const styles = StyleSheet.create({
  cornerStyle: {
    position: 'absolute' as const,
    width: 40,
    height: 40,
    borderTopWidth: 6,
    borderLeftWidth: 6,
    borderColor: '#007AFF',
  },
});
