/**
 * Custom hook for managing registration form state
 * Provides centralized state management for the registration flow
 * Updated for new atomic architecture with 3DS support
 */

import { useState, useCallback } from 'react';
import { validateEmail } from '../../../../utils/validation';

export type RegistrationStep = 'basic_info' | 'subscription' | 'payment';

export type BasicInfoData = {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
  confirmPassword: string;
  acceptTerms: boolean;
  marketingConsent: boolean;
  analyticsConsent: boolean;
};

export type SubscriptionData = {
  planId: 'starter' | 'professional' | 'enterprise';
  billingInterval: 'monthly' | 'yearly';
  useTrial: boolean;
  couponCode?: string;
  planMetadata?: {
    monthly_price: number;
    yearly_price: number;
    name: string;
    description: string;
  };
};

export type PaymentSetupData = {
  success: boolean;
  customerId?: string;
  subscriptionId?: string;
  paymentMethodId?: string;
  planId?: string;
  threedsCompleted?: boolean;
  trialPeriodDays?: number;  // Trial period from coupon (e.g., 90 for PILOT2025)
};

export type RegistrationState = {
  basicInfo: BasicInfoData;
  subscription: SubscriptionData;
  paymentSetup?: PaymentSetupData;
  errors: any;
};

interface RegistrationStateParams {
  initialPlan: 'starter' | 'professional' | 'enterprise';
  initialBillingCycle: 'monthly' | 'yearly';
  isPilot: boolean;
}

export const useRegistrationState = ({ 
  initialPlan, 
  initialBillingCycle, 
  isPilot 
}: RegistrationStateParams) => {
  // Form state
  const [step, setStep] = useState<RegistrationStep>('basic_info');
  
  const [registrationState, setRegistrationState] = useState<RegistrationState>({
    basicInfo: {
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      confirmPassword: '',
      acceptTerms: false,
      marketingConsent: false,
      analyticsConsent: false
    },
    subscription: {
      planId: initialPlan,
      billingInterval: initialBillingCycle,
      useTrial: isPilot,
      couponCode: undefined,
      planMetadata: undefined
    },
    errors: {}
  });
  
  // Loading state
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // Navigation functions
  const nextStep = useCallback(() => {
    setStep(prev => {
      switch (prev) {
        case 'basic_info': return 'subscription';
        case 'subscription': return 'payment';
        // Payment is the last step - no next step
        default: return prev;
      }
    });
  }, []);

  const prevStep = useCallback(() => {
    setStep(prev => {
      switch (prev) {
        case 'subscription': return 'basic_info';
        case 'payment': return 'subscription';
        default: return prev;
      }
    });
  }, []);
  
  // Update registration state function
  const updateRegistrationState = useCallback((updates: Partial<RegistrationState>) => {
    setRegistrationState(prev => ({
      ...prev,
      ...updates
    }));
  }, []);
  
  // Validation function for basic info
  const validateBasicInfo = useCallback((): boolean => {
    const { basicInfo } = registrationState;
    const newErrors: any = {};
    let isValid = true;
    
    if (!basicInfo.firstName.trim()) {
      newErrors.firstName = 'First name is required';
      isValid = false;
    }
    
    if (!basicInfo.lastName.trim()) {
      newErrors.lastName = 'Last name is required';
      isValid = false;
    }
    
    const emailValidation = validateEmail(basicInfo.email);
    if (!emailValidation.isValid) {
      newErrors.email = emailValidation.error || 'Invalid email';
      isValid = false;
    }
    
    if (!basicInfo.password) {
      newErrors.password = 'Password is required';
      isValid = false;
    } else if (basicInfo.password.length < 8) {
      newErrors.password = 'Password must be at least 8 characters';
      isValid = false;
    }
    
    if (basicInfo.password !== basicInfo.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match';
      isValid = false;
    }
    
    if (!basicInfo.acceptTerms) {
      newErrors.acceptTerms = 'You must accept the terms';
      isValid = false;
    }
    
    updateRegistrationState({ errors: newErrors });
    return isValid;
  }, [registrationState]);
  
  // Validation function for subscription
  const validateSubscription = useCallback((): boolean => {
    const { subscription } = registrationState;
    const newErrors: any = {};
    let isValid = true;
    
    if (!subscription.planId) {
      newErrors.planId = 'Please select a plan';
      isValid = false;
    }
    
    if (!subscription.billingInterval) {
      newErrors.billingInterval = 'Please select a billing cycle';
      isValid = false;
    }
    
    updateRegistrationState({ errors: newErrors });
    return isValid;
  }, [registrationState]);
  
  // Reset form
  const resetForm = useCallback(() => {
    setRegistrationState({
      basicInfo: {
        firstName: '',
        lastName: '',
        email: '',
        password: '',
        confirmPassword: '',
        acceptTerms: false,
        marketingConsent: false,
        analyticsConsent: false
      },
      subscription: {
        planId: initialPlan,
        billingInterval: initialBillingCycle,
        useTrial: isPilot,
        couponCode: undefined,
        planMetadata: undefined
      },
      errors: {}
    });
    setStep('basic_info');
  }, [initialPlan, initialBillingCycle, isPilot]);
  
  return {
    step,
    setStep,
    registrationState,
    updateRegistrationState,
    nextStep,
    prevStep,
    validateBasicInfo,
    validateSubscription,
    resetForm,
    isSubmitting,
    setIsSubmitting
  };
};

export default useRegistrationState;