"use client"

import { useCallback, useState } from 'react';

import type { AuthChannel, AuthFormState, AuthFormStateHandlers, AuthStep } from '../types';

export interface UseAuthFormStateReturn extends AuthFormState, AuthFormStateHandlers {}

/**
 * Hook for auth form state management.
 * Pure state - no side effects, no API calls.
 */
export const useAuthFormState = (
  initialIdentifier = '',
  initialChannel: AuthChannel = 'email'
): UseAuthFormStateReturn => {
  const [identifier, setIdentifier] = useState(initialIdentifier);
  const [channel, setChannel] = useState<AuthChannel>(initialChannel);
  const [otp, setOtp] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [step, setStep] = useState<AuthStep>('identifier');
  const [error, setError] = useState('');

  // 2FA state
  const [twoFactorSessionId, setTwoFactorSessionId] = useState<string | null>(null);
  const [shouldPrompt2FA, setShouldPrompt2FA] = useState(false);
  const [twoFactorCode, setTwoFactorCode] = useState('');
  const [useBackupCode, setUseBackupCode] = useState(false);

  const clearError = useCallback(() => setError(''), []);

  return {
    // State
    identifier,
    channel,
    otp,
    isLoading,
    acceptedTerms,
    step,
    error,
    twoFactorSessionId,
    shouldPrompt2FA,
    twoFactorCode,
    useBackupCode,
    // Handlers
    setIdentifier,
    setChannel,
    setOtp,
    setAcceptedTerms,
    setError,
    clearError,
    setStep,
    setIsLoading,
    setTwoFactorSessionId,
    setShouldPrompt2FA,
    setTwoFactorCode,
    setUseBackupCode,
  };
};
