import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'expo-router';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { auth_api } from '../lib/api';

type Lang = 'uz' | 'ru' | 'en';

export function UseLoginForm() {
  const [phone, setPhone] = useState('');
  const [error, setError] = useState('');
  const router = useRouter();

  const { t, i18n } = useTranslation();

  const { mutate, isPending } = useMutation({
    mutationFn: (body: { phone: string }) => auth_api.login(body),
    onError: (err: any) => {
      const errorMessage =
        err?.response?.data?.data?.detail || err?.response?.data?.data?.phone?.[0];

      setError(errorMessage || t('auth.error_general'));
    },
  });

  const submit = () => {
    if (phone.length !== 9) {
      setError(t('auth.error_incomplete'));
      return;
    }

    mutate(
      { phone: `998${phone}` },
      {
        onSuccess: () => {
          setError('');
          router.push('/(auth)/confirm');
        },
      }
    );
  };

  // ✅ MUHIM: wrapper function
  const changeLanguage = async (lang: Lang) => {
    await i18n.changeLanguage(lang);
  };

  const getLanguageName = () => {
    switch (i18n.language) {
      case 'uz':
        return 'O‘zbek';
      case 'ru':
        return 'Русский';
      case 'en':
        return 'English';
      default:
        return '';
    }
  };

  return {
    phone,
    setPhone,
    submit,
    loading: isPending,
    error,
    t,
    language: i18n.language,
    changeLanguage, // ✅ endi undefined EMAS
    getLanguageName,
  };
}
