import { useState } from 'react';
import { Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import RouteName from '../../../Constants/RouteName.constants';
import { RootStackParamList } from '../../../Constants/RouteParamsList.contants';
import api from '../../../api/api';

type RegisterNavProp = NativeStackNavigationProp<RootStackParamList>;

const useRegister = () => {
  const navigation = useNavigation<RegisterNavProp>();
  const [name, setName]                       = useState('');
  const [email, setEmail]                     = useState('');
  const [password, setPassword]               = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword]       = useState(false);
  const [loading, setLoading]                 = useState(false);

  const toggleShowPassword = () => setShowPassword(prev => !prev);
  const goToLogin = () => navigation.navigate(RouteName.LoginNavigation);

  const onRegister = async () => {
    if (!name.trim())     return Alert.alert('Validasi', 'Nama wajib diisi');
    if (!email.trim())    return Alert.alert('Validasi', 'Email wajib diisi');
    if (!password.trim()) return Alert.alert('Validasi', 'Password wajib diisi');
    if (password !== confirmPassword)
      return Alert.alert('Validasi', 'Konfirmasi password tidak sama');
    if (password.length < 6)
      return Alert.alert('Validasi', 'Password minimal 6 karakter');

    setLoading(true);
    try {
      const res = await api.post('/auth/register', {
        nama: name,
        email,
        password,
        konfirmasi_password: confirmPassword,
      });

      if (res.data.success) {
        Alert.alert('Berhasil', 'Register sukses. Silakan login.', [
          { text: 'OK', onPress: () => navigation.navigate(RouteName.LoginNavigation) },
        ]);
      } else {
        Alert.alert('Gagal', res.data.message);
      }
    } catch (err: any) {
      Alert.alert('Error', err.response?.data?.message || 'Gagal terhubung ke server');
    } finally {
      setLoading(false);
    }
  };

  return {
    name, setName,
    email, setEmail,
    password, setPassword,
    confirmPassword, setConfirmPassword,
    showPassword, toggleShowPassword,
    loading, onRegister, goToLogin,
  };
};

export default useRegister;
