import { useState } from 'react';
import authService from '../services/authService';
import { useNavigate } from 'react-router-dom';

const useRegister = () => {
  const [fullname, setFullname] = useState('');
  const [email, setEmail] = useState('');
  const [roleValue, setRoleValue] = useState('1'); // Default ke student
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [nisnOrNip, setNisnOrNip] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const handleRegister = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    if (password !== confirmPassword) {
      setError('Passwords do not match!');
      setLoading(false);
      return;
    }

    try {
      const roleEndpoint = roleValue === '1' ? 'student' : 'teacher';

      const data = {
        NAME_USERS : fullname,
        EMAIL : email,
        PASSWORD : password,
        CONFIRM_PASSWORD : confirmPassword,
        [roleValue === '1' ? 'NISN' : 'NIP']: nisnOrNip,
      };

      await authService.register(roleEndpoint, data);

      navigate('/validate-email');
    } catch (err) {
      setError(err.message || 'Registration failed');
    } finally {
      setLoading(false);
    }
  };

  return {
    fullname,
    setFullname,
    email,
    setEmail,
    roleValue,
    setRoleValue,
    password,
    setPassword,
    confirmPassword,
    setConfirmPassword,
    nisnOrNip,
    setNisnOrNip,
    loading,
    error,
    handleRegister,
  };
};

export default useRegister;
