import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation } from '@tanstack/react-query';
import passportApi, { AddPassportPayload } from 'api/passport';
import AppText from 'components/AppText';
import DatePickerInput from 'components/DatePicker';
import ErrorNotification from 'components/ErrorNotification';
import SingleFileDrop from 'components/FileDrop';
import LayoutTwo from 'components/LayoutTwo';
import React, { useEffect, useRef, useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Dimensions,
  KeyboardAvoidingView,
  ScrollView,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import Calendar from 'svg/Calendar';
import { PassportStyle } from '../../myPassport/ui/styled';
import { CreatePassSchema, CreatePassSchemaType } from '../lib/form';
import CreateModal from './CreateModal';

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

const CreatePassword = () => {
  const { t } = useTranslation();
  const windowWidth = Dimensions.get('window').width;
  const isSmallScreen = windowWidth < 300;
  const passportNumberRef = useRef<TextInput>(null);
  const [inputValue, setInputValue] = useState('');
  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [success, setSuccess] = React.useState(false);
  const [error, setError] = useState<string>('Xatolik yuz berdi');
  const [frontImage, setFrontImage] = useState<FileData | null>(null);
  const [backImage, setBackImage] = useState<FileData | null>(null);
  const [visible, setVisible] = useState(false);
  const [errorVisible, setErrorVisible] = useState(false);
  const [errorText, setErrorText] = useState('');
  // firstName: '',
  //     lastName: '',
  //     birthDate: '',
  //     passportSeriya: '',
  //     passportNumber: '',
  //     jshshir: '',
  const firstNameRef = useRef<TextInput>(null);
  const lastNameRef = useRef<TextInput>(null);
  const birthDateRef = useRef<TextInput>(null);
  const passportSeriyaRef = useRef<TextInput>(null);
  const jshshirRef = useRef<TextInput>(null);

  const { mutate, isPending } = useMutation({
    mutationFn: (payload: AddPassportPayload) => {
      const res = passportApi.addPassport(payload);
      return res;
    },
    onSuccess: () => {
      setSuccess(true);
    },
    onError: (err: any) => {
      console.dir(err);
      setErrorVisible(true);
      setErrorText(
        err?.response?.data || err?.response?.message || 'Xatolik yuz berdi',
      );
    },
  });

  useEffect(() => {
    if (isPending) {
      setSuccess(true);
    }
  }, [isPending]);

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
    getValues,
  } = useForm<CreatePassSchemaType>({
    resolver: zodResolver(CreatePassSchema),
    defaultValues: {
      firstName: '',
      lastName: '',
      birthDate: '',
      passportSeriya: '',
      passportNumber: '',
      jshshir: '',
    },
  });

  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 onSubmit = (data: CreatePassSchemaType) => {
    if (
      errors.birthDate ||
      errors.firstName ||
      errors.jshshir ||
      errors.lastName ||
      errors.passportNumber ||
      errors.passportSeriya
    ) {
      const firstError =
        errors.birthDate?.message ||
        errors.passportSeriya?.message ||
        errors.passportNumber?.message ||
        errors.firstName?.message ||
        errors.lastName?.message ||
        errors.jshshir?.message ||
        'Xatolik yuz berdi';
      setError(
        firstError ? "Ma'lumotlarni to'liq kiriting" : 'Xatolik yuz berdi',
      );
      setVisible(true);
      return;
    }
    const [d, m, y] = data.birthDate.split('/');
    const isoBirthDate = `${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`;

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

  const onErrorSubmit = (errors: any) => {
    const firstError =
      errors.birthDate?.message ||
      errors.passportSeriya?.message ||
      errors.passportNumber?.message ||
      errors.firstName?.message ||
      errors.lastName?.message ||
      errors.jshshir?.message ||
      'Xatolik yuz berdi';
    setError(
      firstError ? "Ma'lumotlarni to'liq kiriting" : 'Xatolik yuz berdi',
    );
    setVisible(true);
  };

  return (
    <LayoutTwo title={t("Yangi pasport qo'shish")}>
      <KeyboardAvoidingView
        style={PassportStyle.container}
        behavior={'padding'}
        keyboardVerticalOffset={30}
      >
        <ScrollView
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
          style={PassportStyle.content}
        >
          <View style={PassportStyle.scrollContainer}>
            <ErrorNotification
              setVisible={setVisible}
              error={error}
              visible={visible}
            />
            <View style={PassportStyle.loginContainer}>
              <Controller
                control={control}
                name="firstName"
                render={({ field: { onChange, value } }) => (
                  <View>
                    <AppText style={PassportStyle.label}>{t('Ism')}</AppText>
                    <TextInput
                      ref={firstNameRef}
                      returnKeyType="next"
                      onSubmitEditing={() => lastNameRef.current?.focus()}
                      style={PassportStyle.input}
                      placeholder={t('Ismingiz')}
                      onChangeText={onChange}
                      value={value}
                      placeholderTextColor={'#D8DADC'}
                    />
                  </View>
                )}
              />
              <Controller
                control={control}
                name="lastName"
                render={({ field: { onChange, value } }) => (
                  <View>
                    <AppText style={PassportStyle.label}>
                      {t('Familiya')}
                    </AppText>
                    <TextInput
                      ref={lastNameRef}
                      returnKeyType="next"
                      onSubmitEditing={() => passportSeriyaRef.current?.focus()}
                      style={PassportStyle.input}
                      placeholder={t('Familiyangiz')}
                      placeholderTextColor={'#D8DADC'}
                      onChangeText={onChange}
                      value={value}
                    />
                  </View>
                )}
              />
              <View>
                <AppText style={PassportStyle.label}>
                  {t('Passport seriya raqami')}
                </AppText>
                <View style={{ flexDirection: 'row' }}>
                  <Controller
                    control={control}
                    name="passportSeriya"
                    render={({ field: { onChange, value } }) => (
                      <TextInput
                        ref={passportSeriyaRef}
                        returnKeyType="next"
                        onSubmitEditing={() =>
                          passportNumberRef.current?.focus()
                        }
                        style={[PassportStyle.input, PassportStyle.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}
                        returnKeyType="next"
                        onSubmitEditing={() => jshshirRef.current?.focus()}
                        style={[PassportStyle.input, PassportStyle.raqamInput]}
                        placeholder="1234567"
                        maxLength={7}
                        keyboardType="numeric"
                        value={value}
                        onChangeText={text => {
                          const onlyNumbers = text.replace(/[^0-9]/g, '');
                          onChange(onlyNumbers);
                        }}
                        placeholderTextColor="#D8DADC"
                      />
                    )}
                  />
                </View>
              </View>
              <View>
                <AppText style={PassportStyle.label}>{t('JSHSHIR')}</AppText>
                <Controller
                  control={control}
                  name="jshshir"
                  render={({ field: { onChange, value } }) => (
                    <TextInput
                      style={PassportStyle.input}
                      ref={jshshirRef}
                      returnKeyType="next"
                      onSubmitEditing={() => birthDateRef.current?.focus()}
                      placeholder="12345678901234"
                      placeholderTextColor={'#D8DADC'}
                      keyboardType="numeric"
                      maxLength={14}
                      value={value}
                      onChangeText={text => {
                        const onlyNumbers = text.replace(/[^0-9]/g, '');
                        onChange(onlyNumbers);
                      }}
                    />
                  )}
                />
              </View>
              <View>
                <Controller
                  control={control}
                  name="birthDate"
                  render={({ field: { onChange, value } }) => (
                    <View style={{ marginBottom: 10 }}>
                      <AppText style={PassportStyle.label}>
                        {t("Tug'ilgan sana")}
                      </AppText>

                      <View style={[PassportStyle.inputContainer]}>
                        <TextInput
                          ref={birthDateRef}
                          returnKeyType="done"
                          style={[
                            PassportStyle.input,
                            { flex: 1, borderWidth: 0, padding: 0 },
                          ]}
                          placeholder="dd/mm/yyyy"
                          placeholderTextColor="#D8DADC"
                          keyboardType="numeric"
                          value={value}
                          onChangeText={text => {
                            let cleaned = text
                              .replace(/[^\d]/g, '')
                              .slice(0, 8);
                            let formatted = '';
                            if (cleaned.length >= 1) {
                              const firstDigit = cleaned[0];
                              if (firstDigit > '3') return;
                            }

                            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;
                            }

                            if (cleaned.length >= 4) {
                              const month = parseInt(cleaned.slice(2, 4), 10);
                              if (month > 12 || month === 0) return;
                            }
                            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)}`;
                            }
                            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)}
                        >
                          <Calendar color="#D8DADC" width={25} height={25} />
                        </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()}
                />
              </View>
              <View>
                <AppText style={PassportStyle.mainTitle}>
                  {t('Passport/ID karta rasmi yoki faylni yuklang')}
                </AppText>
                <View
                  style={[
                    PassportStyle.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>
              </View>
              <TouchableOpacity
                onPress={handleSubmit(onSubmit, onErrorSubmit)}
                style={PassportStyle.button}
              >
                {isPending ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <AppText style={PassportStyle.btnText}>
                    {t("Qo'shish")}
                  </AppText>
                )}
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
      {success && (
        <CreateModal
          visible={success}
          setVisible={setSuccess}
          error={errorVisible}
          errorText={errorText}
        />
      )}
    </LayoutTwo>
  );
};

export default CreatePassword;
