import { useState } from 'react';
import { FormData } from './useCreateRequestForm';

const STEP_NAMES = [
  'Template Selection',
  'Basic Information',
  'Approval Workflow',
  'Participants & Access',
  'Documents & Attachments',
  'Review & Submit'
];

/**
 * Custom Hook: useWizardNavigation
 * 
 * Purpose: Manages wizard step navigation and validation
 * 
 * Responsibilities:
 * - Manages current step state
 * - Validates steps before navigation
 * - Handles step transitions
 */
export function useWizardNavigation(
  isEditing: boolean,
  selectedTemplate: any,
  formData: FormData
) {
  const [currentStep, setCurrentStep] = useState(isEditing ? 2 : 1);
  const totalSteps = STEP_NAMES.length;

  const validateEmail = (email: string) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  };

  const isStepValid = (): boolean => {
    switch (currentStep) {
      case 1:
        return selectedTemplate !== null;
      case 2:
        return formData.title.trim() !== '' && 
               formData.description.trim() !== '' && 
               formData.priority !== '';
      case 3:
        return (formData.approverCount || 1) > 0 &&
               formData.approvers.length === (formData.approverCount || 1) &&
               formData.approvers.every(approver => {
                 if (!approver || !approver.email) return false;
                 if (!validateEmail(approver.email)) return false;
                 if (!approver.userId) return true; // Will be validated on next step
                 const tatType = approver.tatType || 'hours';
                 if (tatType === 'hours') {
                   return approver.tat && approver.tat > 0 && approver.tat <= 720;
                 } else if (tatType === 'days') {
                   return approver.tat && approver.tat > 0 && approver.tat <= 30;
                 }
                 return false;
               });
      case 4:
        return true; // Participants are optional
      case 5:
        return true; // Documents are optional
      case 6:
        return true; // Review & Submit
      default:
        return false;
    }
  };

  const nextStep = () => {
    if (!isStepValid()) return;
    
    if (window.innerWidth < 640) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    
    if (currentStep < totalSteps) {
      setCurrentStep(currentStep + 1);
    }
  };

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
      if (window.innerWidth < 640) {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    }
  };

  const goToStep = (step: number) => {
    if (step >= 1 && step <= totalSteps) {
      setCurrentStep(step);
    }
  };

  return {
    currentStep,
    setCurrentStep,
    totalSteps,
    stepNames: STEP_NAMES,
    isStepValid,
    nextStep,
    prevStep,
    goToStep,
    validateEmail
  };
}

