"use client"

import { useCallback, useEffect, useRef, useState } from 'react';

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

const formatCountdown = (s: number): string => {
  if (s <= 0) return '';
  const m = Math.floor(s / 60);
  return m > 0 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${s}s`;
};

export interface UseAuthFormStateReturn extends AuthFormState, AuthFormStateHandlers {}

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

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

  // Rate limit countdown
  const [rateLimitSeconds, setRateLimitSeconds] = useState(0);
  const rateLimitTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const startRateLimitCountdown = useCallback((seconds: number) => {
    if (rateLimitTimerRef.current) clearInterval(rateLimitTimerRef.current);
    setRateLimitSeconds(seconds);
    rateLimitTimerRef.current = setInterval(() => {
      setRateLimitSeconds((prev) => {
        if (prev <= 1) {
          clearInterval(rateLimitTimerRef.current!);
          rateLimitTimerRef.current = null;
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  }, []);

  useEffect(() => () => {
    if (rateLimitTimerRef.current) clearInterval(rateLimitTimerRef.current);
  }, []);

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

  return {
    // State
    identifier,
    otp,
    isLoading,
    acceptedTerms,
    step,
    error,
    twoFactorSessionId,
    shouldPrompt2FA,
    twoFactorCode,
    useBackupCode,
    rateLimitSeconds,
    isRateLimited: rateLimitSeconds > 0,
    rateLimitLabel: formatCountdown(rateLimitSeconds),
    webmail,
    // Handlers
    setIdentifier,
    setOtp,
    setAcceptedTerms,
    setError,
    clearError,
    setStep,
    setIsLoading,
    setTwoFactorSessionId,
    setShouldPrompt2FA,
    setTwoFactorCode,
    setUseBackupCode,
    startRateLimitCountdown,
    setWebmail,
  };
};
