'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 AppText from 'components/AppText';
import DatePickerInput from 'components/DatePicker';
import ErrorNotification from 'components/ErrorNotification';
import SingleFileDrop from 'components/FileDrop';
import { saveAuth } from 'helpers/event';
import { useEffect, useRef, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Animated,
  Dimensions,
  Image,
  ImageBackground,
  Keyboard,
  KeyboardAvoidingView,
  ScrollView,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Logo from 'screens/../../assets/bootsplash/logo_512.png';
import LanguageSelector from 'screens/auth/select-language/SelectLang';
import ArrowLeft from 'svg/ArrowLeft';
import Calendar from 'svg/Calendar';
import { RootStackParamList } from 'types/types';
import { SecondStepFormType, SecondStepSchema } from '../lib/form';
import { useUserStore } from '../lib/userstore';
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 { firstName, lastName } = useUserStore(state => state);
  const passportSeriyaRef = useRef<TextInput>(null);
  const jshshirRef = useRef<TextInput>(null);
  const birthDateRef = useRef<TextInput>(null);
  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 [visible, setVisible] = useState(false);
  const [error, setError] = useState<string>('Xatolik yuz berdi');

  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.replace('Home');
      saveAuth();
    },
    onError: (err: any) => {
      setError(err?.response?.data || 'Xatolik yuz berdi');
      setVisible(true);
    },
  });

  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) => {
    if (
      errors.birthDate?.message ||
      errors.jshshir?.message ||
      errors.passportNumber?.message ||
      errors.passportSeriya?.message
    ) {
      setError("Ma'lumotlarni to'liq kiriting");
      setVisible(true);
      return;
    }

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

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

  const onErrorSubmit = (errors: any) => {
    setError("Ma'lumotlarni to'liq kiriting");
    setVisible(true);
  };

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

        <ErrorNotification
          setVisible={setVisible}
          error={error}
          visible={visible}
        />

        <KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior="padding"
          keyboardVerticalOffset={50}
        >
          <ScrollView
            contentContainerStyle={{ flexGrow: 1 }}
            keyboardShouldPersistTaps="handled"
          >
            <View style={RegisterStyle.scrollContainer}>
              <View style={RegisterStyle.loginContainer}>
                <AppText style={RegisterStyle.title}>
                  {t('Shaxsiy maʼlumotlar')}
                </AppText>
                <Image
                  source={require('screens/../../assets/bootsplash/passport-sample.jpg')}
                  style={{ width: '100%', height: 300, borderRadius: 8 }}
                  resizeMode="contain"
                />
                <View>
                  {/* PASSPORT */}
                  <AppText style={RegisterStyle.label}>
                    {t('Passport seriya raqami')}
                  </AppText>
                  <View style={{ flexDirection: 'row' }}>
                    <Controller
                      control={control}
                      name="passportSeriya"
                      render={({ field: { onChange, value } }) => (
                        <TextInput
                          ref={passportSeriyaRef}
                          style={[
                            RegisterStyle.input,
                            RegisterStyle.seriyaInput,
                          ]}
                          placeholder="AA"
                          maxLength={2}
                          autoCapitalize="characters"
                          value={value}
                          returnKeyType="next"
                          onChangeText={text => {
                            onChange(text);
                            if (text.length === 2)
                              passportNumberRef.current?.focus();
                          }}
                          placeholderTextColor="#D8DADC"
                          onSubmitEditing={() =>
                            passportNumberRef.current?.focus()
                          }
                        />
                      )}
                    />
                    <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}
                          returnKeyType="next"
                          onChangeText={text => {
                            const onlyNumbers = text.replace(/[^0-9]/g, '');
                            onChange(onlyNumbers);
                          }}
                          onSubmitEditing={() => jshshirRef.current?.focus()}
                          placeholderTextColor="#D8DADC"
                        />
                      )}
                    />
                  </View>
                </View>
                {/* JSHSHIR */}
                <Controller
                  control={control}
                  name="jshshir"
                  render={({ field: { onChange, value } }) => (
                    <View>
                      <AppText style={RegisterStyle.label}>
                        {t('JSHSHIR')}{' '}
                      </AppText>
                      <TextInput
                        style={RegisterStyle.input}
                        ref={jshshirRef}
                        placeholder="12345678901234"
                        placeholderTextColor="#D8DADC"
                        keyboardType="numeric"
                        maxLength={14}
                        returnKeyType="next"
                        value={value}
                        onChangeText={text =>
                          onChange(text.replace(/[^0-9]/g, ''))
                        }
                        onSubmitEditing={() => birthDateRef.current?.focus()}
                      />
                    </View>
                  )}
                />

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

                      <View
                        style={[
                          RegisterStyle.inputContainer,
                          { paddingHorizontal: 0 },
                        ]}
                      >
                        <TextInput
                          style={[
                            RegisterStyle.input,
                            { flex: 1, borderWidth: 0 },
                          ]}
                          ref={birthDateRef}
                          placeholder="dd/mm/yyyy"
                          placeholderTextColor="#D8DADC"
                          keyboardType="numeric"
                          value={value}
                          returnKeyType="done"
                          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);
                          }}
                          onSubmitEditing={handleSubmit(onSubmit)}
                        />
                        <TouchableOpacity
                          onPress={() => setDatePickerVisibility(true)}
                          style={{ right: 15 }}
                        >
                          <Calendar color="#D8DADC" width={24} height={24} />
                        </TouchableOpacity>
                      </View>
                    </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 */}
                <AppText style={RegisterStyle.mainTitle}>
                  {t('Passport/ID karta rasmi yoki faylni yuklang')}
                </AppText>
                <View
                  style={[
                    RegisterStyle.sectionsContainer,
                    { flexDirection: isSmallScreen ? 'column' : 'row' },
                  ]}
                >
                  <View
                    style={{
                      width: isSmallScreen ? '100%' : '48%',
                      marginBottom: 10,
                    }}
                  >
                    <SingleFileDrop
                      title={t('Old tomon')}
                      onFileSelected={file => {
                        setFrontImage(file);
                        Keyboard.dismiss();
                      }}
                    />
                  </View>
                  <View
                    style={{
                      width: isSmallScreen ? '100%' : '48%',
                      marginBottom: 10,
                    }}
                  >
                    <SingleFileDrop
                      title={t('Orqa tomon')}
                      onFileSelected={file => {
                        setBackImage(file);
                        Keyboard.dismiss();
                      }}
                    />
                  </View>
                </View>
                {/* BUTTON */}
                <TouchableOpacity
                  onPress={handleSubmit(onSubmit, onErrorSubmit)}
                  style={[
                    RegisterStyle.button,
                    !termsAccepted && RegisterStyle.buttonDisabled,
                  ]}
                  disabled={!termsAccepted}
                >
                  {isPending ? (
                    <ActivityIndicator color="#fff" />
                  ) : (
                    <AppText
                      style={[
                        RegisterStyle.btnText,
                        !termsAccepted && RegisterStyle.buttonTextDisabled,
                      ]}
                    >
                      {t('Tasdiqlash')}
                    </AppText>
                  )}
                </TouchableOpacity>
              </View>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
      </SafeAreaView>
    </ImageBackground>
  );
};

export default SecondStep;
