import { useState } from 'react';
import { approveLevel, rejectLevel, addApproverAtLevel, skipApprover, addSpectator } from '@/services/workflowApi';

/**
 * Custom Hook: useModalManager
 * 
 * Purpose: Centralized management of all modals and their actions
 * 
 * Responsibilities:
 * - Manages visibility state for all modals (approve, reject, add approver, etc.)
 * - Handles approval and rejection workflows
 * - Manages approver and spectator addition
 * - Handles approver skipping
 * - Provides action status feedback
 * - Triggers data refresh after actions
 * 
 * Modals managed:
 * - Approval Modal
 * - Rejection Modal  
 * - Add Approver Modal
 * - Add Spectator Modal
 * - Skip Approver Modal
 * - Action Status Modal (success/error feedback)
 * 
 * @param requestIdentifier - Request number or UUID
 * @param currentApprovalLevel - Current user's approval level data
 * @param refreshDetails - Function to refresh request data
 * @returns Object with modal states and action handlers
 */
export function useModalManager(
  requestIdentifier: string,
  currentApprovalLevel: any,
  refreshDetails: () => Promise<void>
) {
  // Modal visibility states
  const [showApproveModal, setShowApproveModal] = useState(false);
  const [showRejectModal, setShowRejectModal] = useState(false);
  const [showAddApproverModal, setShowAddApproverModal] = useState(false);
  const [showAddSpectatorModal, setShowAddSpectatorModal] = useState(false);
  const [showSkipApproverModal, setShowSkipApproverModal] = useState(false);
  const [showActionStatusModal, setShowActionStatusModal] = useState(false);
  
  // State: Data for skip approver modal (which approver to skip)
  const [skipApproverData, setSkipApproverData] = useState<{
    levelId: string;
    approverName: string;
    levelNumber: number;
  } | null>(null);
  
  // State: Action status (success or error) to show in modal
  const [actionStatus, setActionStatus] = useState<{
    success: boolean;
    title: string;
    message: string;
  } | null>(null);

  /**
   * Handler: handleApproveConfirm
   * 
   * Purpose: Process approval action when user confirms
   * 
   * Process:
   * 1. Validate level ID exists
   * 2. Call backend API to approve level
   * 3. Refresh request data to show approval
   * 4. Close modal and show success message
   * 
   * Backend Actions:
   * - Updates level status to APPROVED
   * - Records approval timestamp
   * - Moves workflow to next level
   * - Sends notifications to relevant users
   * 
   * @param description - Optional approval comments/remarks
   */
  const handleApproveConfirm = async (description: string) => {
    const levelId = currentApprovalLevel?.levelId || currentApprovalLevel?.level_id;
    
    // Validate: Ensure level ID is available
    if (!levelId) {
      alert('Approval level not found');
      return;
    }

    // API Call: Submit approval
    await approveLevel(requestIdentifier, levelId, description || '');
    
    // Small delay to ensure backend has fully processed the approval and updated the status
    // This is especially important for additional approvers where the workflow moves to the next step
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // Refresh: Update UI with new approval status
    await refreshDetails();
    
    // Legacy: Global handlers (can be replaced with better toast system)
    (window as any)?.closeModal?.();
    (window as any)?.toast?.('Approved successfully');
  };

  /**
   * Handler: handleRejectConfirm
   * 
   * Purpose: Process rejection action when user confirms
   * 
   * Process:
   * 1. Validate rejection comments are provided
   * 2. Call backend API to reject level
   * 3. Refresh request data to show rejection
   * 4. Close modal and show success message
   * 
   * Backend Actions:
   * - Updates level status to REJECTED
   * - Records rejection timestamp and reason
   * - Stops workflow progression
   * - Sends notifications to initiator and relevant users
   * 
   * @param description - Required rejection comments/remarks
   */
  const handleRejectConfirm = async (description: string) => {
    // Validate: Rejection must have comments
    if (!description?.trim()) {
      alert('Comments & remarks are required');
      return;
    }

    const levelId = currentApprovalLevel?.levelId || currentApprovalLevel?.level_id;
    
    // Validate: Ensure level ID is available
    if (!levelId) {
      alert('Approval level not found');
      return;
    }

    // API Call: Submit rejection
    // Note: Backend expects both comments and remarks (currently same value)
    await rejectLevel(requestIdentifier, levelId, description.trim(), description.trim());
    
    // Refresh: Update UI with rejection status
    await refreshDetails();
    
    // Legacy: Global handlers
    (window as any)?.closeModal?.();
    (window as any)?.toast?.('Rejected successfully');
  };

  /**
   * Handler: handleAddApprover
   * 
   * Purpose: Add a new approver at specific level with TAT
   * 
   * Use Case: Initiator can add approvers dynamically if workflow needs change
   * 
   * Process:
   * 1. Validate email, TAT, and level
   * 2. Call backend to add approver
   * 3. Refresh request to show new approver
   * 4. Show success/error modal
   * 5. Close add approver modal
   * 
   * Backend Actions:
   * - Creates new approval level or adds to existing
   * - Sends notification to new approver
   * - Updates workflow structure
   * 
   * @param email - Email of user to add as approver
   * @param tatHours - Turnaround time allocated for this approver
   * @param level - Which approval level to add approver to
   */
  const handleAddApprover = async (email: string, tatHours: number, level: number) => {
    try {
      // API Call: Add approver at specified level
      await addApproverAtLevel(requestIdentifier, email, tatHours, level);
      
      // Refresh: Update workflow to show new approver
      await refreshDetails();
      
      // Close modal
      setShowAddApproverModal(false);
      
      // Success feedback with details
      setActionStatus?.({
        success: true,
        title: 'Approver Added',
        message: `Approver added successfully at Level ${level} with ${tatHours}h TAT`
      });
      setShowActionStatusModal?.(true);
    } catch (error: any) {
      // Error feedback with backend message
      setActionStatus?.({
        success: false,
        title: 'Failed to Add Approver',
        message: error?.response?.data?.error || 'Failed to add approver. Please try again.'
      });
      setShowActionStatusModal?.(true);
      throw error;
    }
  };

  /**
   * Handler: handleSkipApprover
   * 
   * Purpose: Skip an approver who is unavailable or unresponsive
   * 
   * Use Case: When approver is on leave, workflow can continue without them
   * 
   * Process:
   * 1. Validate skip data exists
   * 2. Submit skip reason to backend
   * 3. Workflow moves to next level automatically
   * 4. Show success/error feedback
   * 5. Clear skip data and close modal
   * 
   * Backend Actions:
   * - Marks level as SKIPPED
   * - Records skip reason and timestamp
   * - Moves workflow to next level
   * - Sends notifications
   * 
   * @param reason - Required reason for skipping approver
   */
  const handleSkipApprover = async (reason: string) => {
    if (!skipApproverData) return;
    
    try {
      // API Call: Skip approver with reason
      await skipApprover(requestIdentifier, skipApproverData.levelId, reason);
      
      // Refresh: Update workflow to show skipped status
      await refreshDetails();
      
      // Cleanup and close
      setShowSkipApproverModal(false);
      setSkipApproverData(null);
      
      // Success feedback
      setActionStatus?.({
        success: true,
        title: 'Approver Skipped',
        message: 'Approver skipped successfully. The workflow has moved to the next level.'
      });
      setShowActionStatusModal?.(true);
    } catch (error: any) {
      // Error feedback
      setActionStatus?.({
        success: false,
        title: 'Failed to Skip Approver',
        message: error?.response?.data?.error || 'Failed to skip approver. Please try again.'
      });
      setShowActionStatusModal?.(true);
      throw error;
    }
  };

  /**
   * Handler: handleAddSpectator
   * 
   * Purpose: Add a spectator who can view request but cannot approve/reject
   * 
   * Use Case: Add stakeholders who need visibility but not approval authority
   * 
   * Process:
   * 1. Validate email
   * 2. Call backend to add spectator
   * 3. Refresh to show new spectator
   * 4. Show success/error feedback
   * 5. Close add spectator modal
   * 
   * Backend Actions:
   * - Adds user as SPECTATOR participant
   * - Grants view-only access
   * - Sends notification to spectator
   * 
   * @param email - Email of user to add as spectator
   */
  const handleAddSpectator = async (email: string) => {
    try {
      // API Call: Add spectator
      await addSpectator(requestIdentifier, email);
      
      // Refresh: Update participants list
      await refreshDetails();
      
      // Close modal
      setShowAddSpectatorModal(false);
      
      // Success feedback
      setActionStatus?.({
        success: true,
        title: 'Spectator Added',
        message: 'Spectator added successfully. They can now view this request.'
      });
      setShowActionStatusModal?.(true);
    } catch (error: any) {
      // Error feedback
      setActionStatus?.({
        success: false,
        title: 'Failed to Add Spectator',
        message: error?.response?.data?.error || 'Failed to add spectator. Please try again.'
      });
      setShowActionStatusModal?.(true);
      throw error;
    }
  };

  return {
    // Modal visibility states
    showApproveModal,
    setShowApproveModal,
    showRejectModal,
    setShowRejectModal,
    showAddApproverModal,
    setShowAddApproverModal,
    showAddSpectatorModal,
    setShowAddSpectatorModal,
    showSkipApproverModal,
    setShowSkipApproverModal,
    showActionStatusModal,
    setShowActionStatusModal,
    
    // Skip approver data
    skipApproverData,
    setSkipApproverData,
    
    // Action status
    actionStatus,
    setActionStatus,
    
    // Action handlers
    handleApproveConfirm,
    handleRejectConfirm,
    handleAddApprover,
    handleSkipApprover,
    handleAddSpectator
  };
}

