import { zodResolver } from '@hookform/resolvers/zod';
import { RouteProp, useRoute } from '@react-navigation/native';
import AppText from 'components/AppText';
import NavbarBack from 'components/NavbarBack';
import Navigation from 'components/Navigation';
import * as React from 'react';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  KeyboardAvoidingView,
  Linking,
  Platform,
  ScrollView,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import AppLink from 'react-native-app-link';
import MaskInput from 'react-native-mask-input';
import { SafeAreaView } from 'react-native-safe-area-context';
import { PaymentStyle } from 'screens/wallet/payment/ui/style';
import ModalSuccess from 'screens/wallet/paymentMethod/ui/ModalSuccess';
import { RootStackParamList } from 'types/types';
import { PaymentFormType, paymentSchema } from '../lib/form';

interface EnterCardProps {}

type EnterCardRouteProp = RouteProp<RootStackParamList, 'EnterCard'>;

const EnterCard = (props: EnterCardProps) => {
  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<PaymentFormType>({
    resolver: zodResolver(paymentSchema),
    defaultValues: {
      card_name: '',
      card_number: '',
      duration: '',
    },
  });
  const [load, setLoad] = React.useState(false);
  const [success, setSuccess] = React.useState(false);
  const [payModal, setPayModal] = React.useState(false);
  const { t } = useTranslation();
  const route = useRoute<EnterCardRouteProp>();
  const { selectedId } = route.params;

  const openPayme = React.useCallback(async () => {
    try {
      await AppLink.maybeOpenURL('https://checkout.paycom.uz/openapp', {
        appName: 'Payme',
        appStoreId: 1093525667,
        appStoreLocale: 'uz',
        playStoreId: 'uz.dida.payme',
      });
    } catch (err) {
      Linking.openURL('https://checkout.paycom.uz/openapp');
    }
  }, []);

  const openClick = async () => {
    try {
      await AppLink.maybeOpenURL('click://my.click.uz/clickp2p/some-id', {
        appName: 'Payme',
        appStoreId: 1093525667,
        appStoreLocale: 'uz',
        playStoreId: 'uz.dida.payme',
      });
    } catch (err) {
      Linking.openURL('click://');
    }
  };
  const onSubmit = (data: PaymentFormType) => {
    setLoad(true);
    setTimeout(() => {
      setSuccess(true);
      setLoad(false);
    }, 3000);
  };

  const openApp = () => {
    setTimeout(() => {
      if (selectedId === 'payme') {
        openPayme();
      } else if (selectedId === 'click') {
        openClick();
      }
    }, 3000);
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1 }}>
        <NavbarBack title={t("To'lov usuli")} />
        <KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        >
          <ScrollView
            style={[PaymentStyle.containerMethod]}
            contentContainerStyle={{ paddingBottom: 80 }}
          >
            <View style={{ gap: 20 }}>
              <Controller
                control={control}
                name="card_name"
                render={({ field: { onChange, value } }) => (
                  <View>
                    <AppText style={PaymentStyle.label}>
                      {t('Karta nomi')}
                    </AppText>
                    <TextInput
                      style={PaymentStyle.input}
                      placeholder={t('Karta nomi')}
                      placeholderTextColor={'#D8DADC'}
                      onChangeText={onChange}
                      value={value}
                    />
                    {errors.card_name && (
                      <AppText style={PaymentStyle.errorText}>
                        {t(errors.card_name.message || '')}
                      </AppText>
                    )}
                  </View>
                )}
              />
              <Controller
                control={control}
                name="card_number"
                render={({ field: { onChange, value } }) => {
                  const rawDigits = value.replace(/\D+/g, '');
                  const formattedValue = value;
                  const ghostMask = '0000 0000 0000 0000';
                  const ghostRemaining = ghostMask.slice(formattedValue.length);

                  return (
                    <View>
                      <AppText style={PaymentStyle.label}>
                        {t('Karta raqami')}
                      </AppText>
                      <View style={{ position: 'relative' }}>
                        {/* Ghost text with value + remaining */}
                        <AppText
                          style={[
                            PaymentStyle.input,
                            {
                              position: 'absolute',
                              top: 0,
                              left: 0,
                              color: '#D8DADC',
                              width: '100%',
                              height: '100%',
                              zIndex: 1,
                              padding: 15,
                              fontSize: 16,
                              fontWeight: '400',
                              pointerEvents: 'none', // 👈 Shart! Shunda cursor ustidan chiqmaydi
                            },
                          ]}
                        >
                          <AppText style={{ color: '#000' }}>
                            {formattedValue}
                          </AppText>
                          <AppText>{ghostRemaining}</AppText>
                        </AppText>
                        <MaskInput
                          value={value}
                          onChangeText={masked => {
                            onChange(masked);
                          }}
                          mask={[
                            /\d/,
                            /\d/,
                            /\d/,
                            /\d/,
                            ' ',
                            /\d/,
                            /\d/,
                            /\d/,
                            /\d/,
                            ' ',
                            /\d/,
                            /\d/,
                            /\d/,
                            /\d/,
                            ' ',
                            /\d/,
                            /\d/,
                            /\d/,
                            /\d/,
                          ]}
                          keyboardType="number-pad"
                          style={[
                            PaymentStyle.input,
                            {
                              color: 'rgba(0,0,0,0)',
                              zIndex: 2,
                              backgroundColor: 'transparent',
                            },
                          ]}
                          caretHidden={false}
                          selectionColor="#000"
                          placeholder=""
                        />
                      </View>
                      {errors.card_number && (
                        <AppText style={PaymentStyle.errorText}>
                          {t(errors.card_number.message || '')}
                        </AppText>
                      )}
                    </View>
                  );
                }}
              />
              <Controller
                control={control}
                name="duration"
                render={({ field: { onChange, value } }) => {
                  // Raqamlarni olib, 2-raqamdan keyin "/" belgisini qo‘shish
                  const formatDuration = (text: string) => {
                    const cleaned = text.replace(/\D+/g, '').slice(0, 4); // Faqat raqamlar, maksimal 4 ta
                    if (cleaned.length >= 3) {
                      return `${cleaned.slice(0, 2)}/${cleaned.slice(2)}`;
                    } else {
                      return cleaned;
                    }
                  };

                  const handleTextChange = (text: string) => {
                    const formatted = formatDuration(text);
                    onChange(formatted);
                  };

                  return (
                    <View>
                      <AppText style={PaymentStyle.label}>
                        {t('Muddati')}
                      </AppText>
                      <TextInput
                        style={PaymentStyle.input}
                        placeholder="MM/YY"
                        placeholderTextColor={'#D8DADC'}
                        onChangeText={handleTextChange}
                        value={value}
                        keyboardType="numeric"
                        maxLength={5}
                      />
                      {errors.duration && (
                        <AppText style={PaymentStyle.errorText}>
                          {t(errors.duration.message || '')}
                        </AppText>
                      )}
                    </View>
                  );
                }}
              />
            </View>
            <TouchableOpacity
              onPress={openApp}
              style={{
                width: '100%',
                justifyContent: 'flex-end',
                alignItems: 'flex-end',
                marginTop: 20,
              }}
            >
              <AppText>
                {selectedId?.toUpperCase()} {t("ilovasi orqali to'lash")}
              </AppText>
            </TouchableOpacity>
          </ScrollView>
        </KeyboardAvoidingView>
        {success && (
          <ModalSuccess
            visible={success}
            setVisible={setSuccess}
            setPayModal={setPayModal}
          />
        )}
        <TouchableOpacity
          style={{
            borderRadius: 8,
            justifyContent: 'center',
            backgroundColor: '#28A7E8',
            zIndex: 10,
            marginBottom: 10,
            width: '95%',
            margin: 'auto',
            height: 56,
          }}
          onPress={handleSubmit(onSubmit)}
          disabled={load}
        >
          {load ? (
            <ActivityIndicator size="small" color="#fff" />
          ) : (
            <AppText style={PaymentStyle.btnText}>{t("To'lash")}</AppText>
          )}
        </TouchableOpacity>
        <Navigation />
      </View>
    </SafeAreaView>
  );
};

export default EnterCard;
