'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import {
  useNavigation,
  useRoute,
  type RouteProp,
} from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useMutation } from '@tanstack/react-query';
import passportApi, { sendPassportPayload } from 'api/passport';
import DatePickerInput from 'components/DatePicker';
import SingleFileDrop from 'components/FileDrop';
import { useEffect, useRef, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Animated,
  Dimensions,
  Image,
  ImageBackground,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import AntDesign from 'react-native-vector-icons/AntDesign';
import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons';
import Logo from 'screens/../../assets/bootsplash/logo_512.png';
import LanguageSelector from 'screens/auth/select-language/SelectLang';
import { RootStackParamList } from 'types/types';
import { SecondStepFormType, SecondStepSchema } from '../lib/form';
import { RegisterStyle } from './styled';

interface FileData {
  uri: string;
  name: string;
  type: string;
  base64: string;
}

const SecondStep = () => {
  const { t } = useTranslation();
  const windowWidth = Dimensions.get('window').width;
  const [frontImage, setFrontImage] = useState<FileData | null>(null);
  const [backImage, setBackImage] = useState<FileData | null>(null);
  const isSmallScreen = windowWidth < 200;
  const [termsAccepted, setTermsAccepted] = useState(true);
  const passportNumberRef = useRef<TextInput>(null);
  const [checkboxAnimation] = useState(new Animated.Value(1));
  const [inputValue, setInputValue] = useState('');

  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList, 'Login'>>();
  const route = useRoute<RouteProp<RootStackParamList, 'Register'>>();
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);

  const formatDate = (date: Date) => {
    const day = date.getDate().toString().padStart(2, '0');
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
  };

  const { mutate, isPending } = useMutation({
    mutationFn: (payload: sendPassportPayload) =>
      passportApi.sendPassport(payload),
    onSuccess: res => {
      navigation.navigate('Home');
    },
    onError: err => {
      console.dir(err);
    },
  });

  useEffect(() => {
    if (route.params?.termsAccepted) {
      setTermsAccepted(true);
      Animated.spring(checkboxAnimation, {
        toValue: 1,
        useNativeDriver: false,
        tension: 100,
        friction: 8,
      }).start();
    }
  }, [route.params]);

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<SecondStepFormType>({
    resolver: zodResolver(SecondStepSchema),
    defaultValues: {
      passportNumber: '',
      passportSeriya: '',
      birthDate: '',
      jshshir: '',
    },
  });

  const onSubmit = async (data: SecondStepFormType) => {
    const [d, m, y] = data.birthDate.split('/');
    const isoBirthDate = `${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`;

    mutate({
      fullName: data.passportSeriya.toUpperCase(),
      birthDate: isoBirthDate,
      passportSerial: `${data.passportSeriya.toUpperCase()}${
        data.passportNumber
      }`,
      passportPin: data.jshshir,
      passportFrontImage: frontImage ? `${frontImage.base64}` : '',
      passportBackImage: backImage ? `${backImage.base64}` : '',
    });
  };

  return (
    <ImageBackground
      source={Logo}
      style={RegisterStyle.background}
      resizeMode="contain"
      imageStyle={{
        opacity: 0.3,
        height: '100%',
        width: '100%',
        transform: [{ scale: 1.5 }],
      }}
    >
      <SafeAreaView style={{ flex: 1 }}>
        <View style={RegisterStyle.langContainer}>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <SimpleLineIcons name="arrow-left" color="#000" size={20} />
          </TouchableOpacity>
          <LanguageSelector />
        </View>

        <KeyboardAvoidingView
          style={RegisterStyle.container}
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        >
          <ScrollView style={RegisterStyle.content}>
            <View style={RegisterStyle.scrollContainer}>
              <View style={RegisterStyle.loginContainer}>
                <Text style={RegisterStyle.title}>
                  {t('Shaxsiy maʼlumotlar')}
                </Text>
                <Image
                  source={require('screens/../../assets/bootsplash/passport-sample.jpg')}
                  style={{ width: '100%', height: 300, borderRadius: 8 }}
                  resizeMode="contain"
                />
                <View>
                  {/* PASSPORT */}
                  <Text style={RegisterStyle.label}>
                    {t('Passport seriya raqami')}
                  </Text>
                  <View style={{ flexDirection: 'row' }}>
                    <Controller
                      control={control}
                      name="passportSeriya"
                      render={({ field: { onChange, value } }) => (
                        <TextInput
                          style={[
                            RegisterStyle.input,
                            RegisterStyle.seriyaInput,
                          ]}
                          placeholder="AA"
                          maxLength={2}
                          autoCapitalize="characters"
                          value={value}
                          onChangeText={text => {
                            onChange(text);
                            if (text.length === 2)
                              passportNumberRef.current?.focus();
                          }}
                          placeholderTextColor="#D8DADC"
                        />
                      )}
                    />
                    <Controller
                      control={control}
                      name="passportNumber"
                      render={({ field: { onChange, value } }) => (
                        <TextInput
                          ref={passportNumberRef}
                          style={[
                            RegisterStyle.input,
                            RegisterStyle.raqamInput,
                          ]}
                          placeholder="1234567"
                          maxLength={7}
                          keyboardType="numeric"
                          value={value}
                          onChangeText={text => {
                            const onlyNumbers = text.replace(/[^0-9]/g, '');
                            onChange(onlyNumbers);
                          }}
                          placeholderTextColor="#D8DADC"
                        />
                      )}
                    />
                  </View>
                  {(errors.passportSeriya || errors.passportNumber) && (
                    <Text style={RegisterStyle.errorText}>
                      {t(errors.passportSeriya?.message || '') ||
                        t(errors.passportNumber?.message || '')}
                    </Text>
                  )}
                </View>
                {/* JSHSHIR */}
                <Controller
                  control={control}
                  name="jshshir"
                  render={({ field: { onChange, value } }) => (
                    <View>
                      <Text style={RegisterStyle.label}>{t('JSHSHIR')}</Text>
                      <TextInput
                        style={RegisterStyle.input}
                        placeholder="12345678901234"
                        placeholderTextColor="#D8DADC"
                        keyboardType="numeric"
                        maxLength={14}
                        value={value}
                        onChangeText={text =>
                          onChange(text.replace(/[^0-9]/g, ''))
                        }
                      />
                      {errors.jshshir && (
                        <Text style={RegisterStyle.errorText}>
                          {t(errors.jshshir.message || '')}
                        </Text>
                      )}
                    </View>
                  )}
                />

                {/* BIRTH DATE */}
                <Controller
                  control={control}
                  name="birthDate"
                  render={({ field: { onChange, value } }) => (
                    <View style={{ marginBottom: 10 }}>
                      <Text style={RegisterStyle.label}>
                        {t("Tug'ilgan sana")}
                      </Text>

                      <View
                        style={[
                          RegisterStyle.inputContainer,
                          { paddingHorizontal: 0 },
                        ]}
                      >
                        <TextInput
                          style={[
                            RegisterStyle.input,
                            { flex: 1, borderWidth: 0 },
                          ]}
                          placeholder="dd/mm/yyyy"
                          placeholderTextColor="#D8DADC"
                          keyboardType="numeric"
                          value={value}
                          onChangeText={text => {
                            let cleaned = text
                              .replace(/[^\d]/g, '')
                              .slice(0, 8);
                            let formatted = '';

                            // Early validation for day and month before formatting
                            if (cleaned.length >= 1) {
                              const firstDigit = cleaned[0];
                              if (firstDigit > '3') return; // Day can't start with 4-9
                            }

                            if (cleaned.length >= 2) {
                              const day = parseInt(cleaned.slice(0, 2), 10);
                              if (day > 31 || day === 0) return;
                            }

                            if (cleaned.length >= 3) {
                              const monthFirstDigit = cleaned[2];
                              if (monthFirstDigit > '1') return; // Month can't start with 2-9
                            }

                            if (cleaned.length >= 4) {
                              const month = parseInt(cleaned.slice(2, 4), 10);
                              if (month > 12 || month === 0) return;
                            }

                            // Now format it after initial checks
                            if (cleaned.length <= 2) {
                              formatted = cleaned;
                            } else if (cleaned.length <= 4) {
                              formatted = `${cleaned.slice(
                                0,
                                2,
                              )}/${cleaned.slice(2)}`;
                            } else {
                              formatted = `${cleaned.slice(
                                0,
                                2,
                              )}/${cleaned.slice(2, 4)}/${cleaned.slice(4)}`;
                            }

                            // Validate full date not in future
                            if (formatted.length === 10) {
                              const [d, m, y] = formatted.split('/');
                              const inputDate = new Date(+y, +m - 1, +d);
                              const today = new Date();
                              inputDate.setHours(0, 0, 0, 0);
                              today.setHours(0, 0, 0, 0);

                              if (inputDate > today) return;
                            }

                            setValue('birthDate', formatted);
                          }}
                        />
                        <TouchableOpacity
                          onPress={() => setDatePickerVisibility(true)}
                          style={{ right: 15 }}
                        >
                          <AntDesign
                            name="calendar"
                            color="#D8DADC"
                            size={25}
                          />
                        </TouchableOpacity>
                      </View>

                      {errors.birthDate && (
                        <Text style={RegisterStyle.errorText}>
                          {t(errors.birthDate?.message || '')}
                        </Text>
                      )}
                    </View>
                  )}
                />

                <DatePickerInput
                  showPicker={isDatePickerVisible}
                  setShowPicker={setDatePickerVisibility}
                  value={selectedDate || new Date()}
                  onChange={date => {
                    if (date) {
                      const formattedDate = formatDate(date);
                      setSelectedDate(date);
                      setInputValue(formattedDate);
                      setValue('birthDate', formattedDate);
                    }
                  }}
                  maximumDate={new Date()}
                />

                {/* FILE UPLOAD */}
                <Text style={RegisterStyle.mainTitle}>
                  {t('Passport/ID karta rasmi yoki faylni yuklang')}
                </Text>
                <View
                  style={[
                    RegisterStyle.sectionsContainer,
                    { flexDirection: isSmallScreen ? 'column' : 'row' },
                  ]}
                >
                  <View
                    style={{
                      width: isSmallScreen ? '100%' : '48%',
                      marginBottom: 10,
                    }}
                  >
                    <SingleFileDrop
                      title={t('Old tomon')}
                      onFileSelected={setFrontImage}
                    />
                  </View>
                  <View
                    style={{
                      width: isSmallScreen ? '100%' : '48%',
                      marginBottom: 10,
                    }}
                  >
                    <SingleFileDrop
                      title={t('Orqa tomon')}
                      onFileSelected={setBackImage}
                    />
                  </View>
                </View>

                {/* BUTTON */}
                <TouchableOpacity
                  onPress={handleSubmit(onSubmit)}
                  style={[
                    RegisterStyle.button,
                    !termsAccepted && RegisterStyle.buttonDisabled,
                  ]}
                  disabled={!termsAccepted}
                >
                  {isPending ? (
                    <ActivityIndicator color="#fff" />
                  ) : (
                    <Text
                      style={[
                        RegisterStyle.btnText,
                        !termsAccepted && RegisterStyle.buttonTextDisabled,
                      ]}
                    >
                      {t('Tasdiqlash')}
                    </Text>
                  )}
                </TouchableOpacity>
              </View>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
      </SafeAreaView>
    </ImageBackground>
  );
};

export default SecondStep;
