"use client";
import React, { createContext, useContext, useState, ReactNode, useEffect, useCallback } from "react";
import WorkflowSetupModal from "./WorkflowSetupModal";
import { getInfoProfile } from "@/service/auth";
import { usePathname } from "next/navigation";

interface WorkflowInfo {
  hasWorkflowSetup: boolean;
  defaultWorkflowId?: number;
  defaultWorkflowName?: string;
  requiresApproval?: boolean;
  autoPublishArticles?: boolean;
  isApprovalActive?: boolean;
}

interface WorkflowModalContextType {
  showWorkflowModal: (workflowInfo: WorkflowInfo) => void;
  hideWorkflowModal: () => void;
  refreshWorkflowStatus: () => Promise<void>;
}

const WorkflowModalContext = createContext<WorkflowModalContextType | undefined>(undefined);

export function useWorkflowModal() {
  const context = useContext(WorkflowModalContext);
  if (context === undefined) {
    throw new Error('useWorkflowModal must be used within a WorkflowModalProvider');
  }
  return context;
}

interface WorkflowModalProviderProps {
  children: ReactNode;
}

export function WorkflowModalProvider({ children }: WorkflowModalProviderProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [workflowInfo, setWorkflowInfo] = useState<WorkflowInfo | undefined>(undefined);
  const pathname = usePathname();

  // Force hide modal when on tenant settings page
  const forceHideModal = useCallback(() => {
    console.log("Force hiding modal");
    setIsModalOpen(false);
    setWorkflowInfo(undefined);
  }, []);

  const refreshWorkflowStatus = async () => {
    try {
      const response = await getInfoProfile();
      
      if (response?.data?.data && response?.data?.data?.approvalWorkflowInfo) {
        const workflowInfo = response.data.data.approvalWorkflowInfo;
        
        // Update workflow info
        setWorkflowInfo(workflowInfo);
        
        // If workflow is now setup, allow closing modal
        if (workflowInfo.hasWorkflowSetup) {
          console.log("Workflow is now setup, modal can be closed");
        }
      }
    } catch (error) {
      console.error("Error refreshing workflow status:", error);
    }
  };

  // Auto-hide modal when user is on tenant settings page
  useEffect(() => {
    console.log("Current pathname:", pathname);
    
    // Add small delay to ensure pathname is fully updated
    const timeoutId = setTimeout(() => {
      if (pathname?.includes('/admin/settings/tenant') || pathname?.includes('/tenant')) {
        console.log("User is on tenant settings page, hiding modal");
        forceHideModal();
      }
    }, 100); // Small delay to ensure pathname is updated
    
    return () => clearTimeout(timeoutId);
  }, [pathname, forceHideModal]);

  // Auto-refresh workflow status when modal is open and user is not on tenant settings page
  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (isModalOpen && !pathname?.includes('/admin/settings/tenant') && !pathname?.includes('/tenant')) {
      console.log("Starting auto-refresh for workflow status");
      interval = setInterval(async () => {
        await refreshWorkflowStatus();
      }, 5000); // Refresh every 5 seconds
    }
    
    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [isModalOpen, pathname, refreshWorkflowStatus]);

  const showWorkflowModal = (info: WorkflowInfo) => {
    console.log("Show workflow modal: ", info);
    setWorkflowInfo(info);
    setIsModalOpen(true);
  };

  const hideWorkflowModal = () => {
    console.log("Hide workflow modal");
    setIsModalOpen(false);
    setWorkflowInfo(undefined);
  };

  return (
    <WorkflowModalContext.Provider value={{ showWorkflowModal, hideWorkflowModal, refreshWorkflowStatus }}>
      {children}
      {/* <WorkflowSetupModal 
        isOpen={isModalOpen} 
        onClose={hideWorkflowModal}
        workflowInfo={workflowInfo}
        onRefresh={refreshWorkflowStatus}
      /> */}
    </WorkflowModalContext.Provider>
  );
}
