import { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import ContentInput from "@/components/learn/ContentInput";
import ContentAnalysis from "@/components/learn/ContentAnalysis";
import Quiz from "@/components/learn/Quiz";
import Certificate from "@/components/learn/Certificate";
import UserInfoForm from "@/components/learn/UserInfoForm";
import VerificationProfileForm from "@/components/learn/VerificationProfileForm";
import Assessment from "@/components/learn/Assessment";
import { toast } from "@/hooks/use-toast";
import { processAssessmentData, calculateCredits } from "@/utils/assessmentUtils";
import { storeContentEmbedding, getContentEmbeddingById } from "@/utils/embeddingUtils";
import { Button } from "@/components/ui/button";
import { CheckCircle2 } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { getWebhookUrl, parseWebhookResponse } from "@/components/learn/webhook/parseWebhookResponse";

type Stage = "input" | "analysis" | "quiz" | "certificate" | "userInfo" | "verification" | "assessment";

interface UserInfo {
  fullName: string;
  organization: string;
  email: string;
}

interface ContentSummary {
  title: string;
  description: string;
}

const Learn = () => {
  const location = useLocation();
  const [stage, setStage] = useState<Stage>("input");
  const [isLoading, setIsLoading] = useState(false);
  const [analysis, setAnalysis] = useState<any>(null);
  const [quiz, setQuiz] = useState<any>(null);
  const [certificate, setCertificate] = useState<any>(null);
  const [userInfo, setUserInfo] = useState<UserInfo>({
    fullName: "",
    organization: "",
    email: ""
  });
  const [contentSummary, setContentSummary] = useState<ContentSummary>({
    title: "",
    description: ""
  });
  const [contentDetails, setContentDetails] = useState({
    content: "",
    contentType: "",
    transcript: ""
  });
  const [isVerified, setIsVerified] = useState(false);
  const [lastWebhookResponse, setLastWebhookResponse] = useState<any>(null);
  const [webhookDisplayed, setWebhookDisplayed] = useState(false);
  const [assessmentResults, setAssessmentResults] = useState<any>(null);
  
  const [contentPersisted, setContentPersisted] = useState(false);
  const [currentSessionId, setCurrentSessionId] = useState<string>(`session_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`);
  
  const [webhookDebugInfo, setWebhookDebugInfo] = useState<{
    url: string;
    status: string;
    timestamp: string;
    contentType: string | null;
  }>({
    url: getWebhookUrl("youtube"),
    status: "not_sent",
    timestamp: "",
    contentType: null
  });

  // Process n8n webhook response
  const processN8nResponse = (n8nResponse: any, content: string, contentType: string, transcript?: string) => {
    console.log("Processing n8n webhook response:", n8nResponse);
    
    const parsedResponse = parseWebhookResponse(n8nResponse);
    
    if (parsedResponse.status === "error" || parsedResponse.connectionFailed) {
      toast({
        title: "Analysis Error",
        description: parsedResponse.message || "There was an error processing your content.",
        variant: "destructive"
      });
      return;
    }
    
    if (parsedResponse.data || parsedResponse.output) {
      const analysisData = parsedResponse.data || parsedResponse.output || {};
      
      // Transform response data to analysis format
      setAnalysis({
        title: parsedResponse.title || "Content Analysis",
        formattedMessage: parsedResponse.formattedMessage || "",
        subjects: analysisData.subjects || [],
        complexity: analysisData.complexity || "Undergraduate",
        readingTime: analysisData.readingTime || 0,
        understandingTime: analysisData.understandingTime || 0,
        totalStudyTime: parsedResponse.totalStudyTime || analysisData.totalStudyTime || 0,
        wordCount: analysisData.wordCount || 0,
        totalPoints: analysisData.totalPoints || 0,
        quiz: analysisData.quiz || null,
        keyTopics: analysisData.keyTopics || []
      });
      
      setContentSummary({
        title: parsedResponse.title || analysisData.title || "Content Analysis",
        description: parsedResponse.formattedMessage || analysisData.description || ""
      });
      
      setStage("analysis");
    } else if (parsedResponse.status === "submitted" || parsedResponse.status === "processing") {
      toast({
        title: "Analysis In Progress",
        description: "Your content is being analyzed. This may take a few moments.",
        variant: "default"
      });
      
      // Set placeholder analysis data while waiting
      setAnalysis({
        title: "Analysis in Progress",
        subjects: [],
        complexity: "Analyzing...",
        readingTime: 0,
        understandingTime: 0,
        totalStudyTime: 0,
        wordCount: 0,
        totalPoints: 0,
        processingStatus: "submitted"
      });
      
      setContentSummary({
        title: "Analysis in Progress",
        description: `Analyzing your ${contentType} content...`
      });
      
      setStage("analysis");
    } else {
      toast({
        title: "Incomplete Analysis",
        description: "The analysis service returned incomplete results. Try again later.",
        variant: "destructive"
      });
    }
  };

  // Analyze content locally
  const analyzeContent = (content: string, contentType: string, transcript?: string) => {
    console.log(`Analyzing ${contentType} content locally:`, content.substring(0, 100) + "...");
    
    setIsLoading(true);
    
    // Simple mock analysis for demo purposes
    setTimeout(() => {
      const mockAnalysis = {
        title: contentType === "youtube" ? "YouTube Video Analysis" : "Content Analysis",
        subjects: ["Education", "Technology"],
        complexity: "Undergraduate",
        readingTime: 10,
        understandingTime: 15,
        totalStudyTime: 25,
        wordCount: 1500,
        totalPoints: 25,
        quiz: [
          {
            question: "What is the main topic of this content?",
            options: ["Education", "Technology", "Science", "History"],
            correctAnswer: "Education",
          },
          {
            question: "What skill would you develop most from this content?",
            options: ["Critical thinking", "Data analysis", "Communication", "Project management"],
            correctAnswer: "Critical thinking",
          }
        ],
        keyTopics: ["Learning", "Assessment", "Educational Technology"]
      };
      
      setAnalysis(mockAnalysis);
      
      setContentSummary({
        title: mockAnalysis.title,
        description: contentType === "youtube" 
          ? `Analysis of YouTube video: ${content.substring(0, 50)}...` 
          : `Analysis of text content (${mockAnalysis.wordCount} words)`
      });
      
      setIsLoading(false);
      setStage("analysis");
      
    }, 1500); // Simulate processing delay
  };
  
  // Fix for the testWebhook function by ensuring it always receives two arguments
  const testWebhook = async (contentType: string = "youtube", additionalParams: Record<string, any> = {}) => {
    const webhookUrl = getWebhookUrl(contentType);
    setWebhookDebugInfo({
      url: webhookUrl,
      status: "testing",
      timestamp: new Date().toISOString(),
      contentType
    });
    
    try {
      const response = await fetch(webhookUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          test: true,
          timestamp: new Date().toISOString(),
          source: "AiCE-Test",
          ...additionalParams
        })
      });
      
      const status = response.ok ? "success" : "failed";
      setWebhookDebugInfo({
        url: webhookUrl,
        status: status,
        timestamp: new Date().toISOString(),
        contentType
      });
      
      console.log(`Webhook test ${status} for ${contentType}:`, webhookUrl);
    } catch (error) {
      console.error(`Webhook test failed for ${contentType}:`, error);
      setWebhookDebugInfo({
        url: webhookUrl,
        status: "error",
        timestamp: new Date().toISOString(),
        contentType
      });
    }
  };

  const handleContentSubmit = async (content: string, contentType: string, transcript?: string, n8nResponse?: any) => {
    console.log(`Learn.handleContentSubmit called with contentType: ${contentType}, n8nResponse:`, n8nResponse);
    
    if (n8nResponse) {
      setLastWebhookResponse(n8nResponse);
      setWebhookDisplayed(false);
      
      if (n8nResponse.sessionId) {
        setCurrentSessionId(n8nResponse.sessionId);
        console.log("Updated session ID to:", n8nResponse.sessionId);
      }
      
      setWebhookDebugInfo({
        url: getWebhookUrl(contentType),
        status: n8nResponse.connectionFailed ? "failed" : "received",
        timestamp: new Date().toISOString(),
        contentType
      });
    }
    
    setContentDetails({
      content,
      contentType,
      transcript: transcript || ""
    });
    
    setContentPersisted(false);
    
    if (contentType === "youtube") {
      console.log(`Processing YouTube URL with webhook: ${getWebhookUrl("youtube")}`);
      console.log("YouTube content:", content);
      
      if (process.env.NODE_ENV === 'development') {
        toast({
          title: "YouTube Webhook Request", 
          description: `Sending to: ${getWebhookUrl("youtube").substring(0, 30)}...`
        });
      }
    }
    
    if (contentType === "file") {
      if (n8nResponse && !n8nResponse.connectionFailed) {
        console.log("Processing file with n8n response:", n8nResponse);
        processN8nResponse(n8nResponse, content, contentType, transcript);
      } else {
        console.log("File webhook connection failed or no response, using local analysis");
        toast({
          title: "Using Built-in Analysis", 
          description: "Using local content analysis. External service unavailable."
        });
        analyzeContent(content, contentType, transcript);
      }
      return;
    }
    
    if (contentType === "youtube") {
      if (n8nResponse && (n8nResponse.status === "submitted" || n8nResponse.status === "processing")) {
        console.log("YouTube submission acknowledged:", n8nResponse);
        
        toast({
          title: "YouTube Video Submitted", 
          description: "Your video has been sent to the AI analysis service. Processing..."
        });
        
        const placeholderAnalysis = {
          title: "Analyzing YouTube Video",
          subjects: ["Video Content", "YouTube"],
          complexity: "Undergraduate",
          readingTime: 0,
          understandingTime: 0,
          totalStudyTime: 0,
          wordCount: 0,
          totalPoints: 0,
          processingStatus: "submitted"
        };
        
        setAnalysis(placeholderAnalysis);
        setContentSummary({
          title: "YouTube Analysis In Progress",
          description: `The AI service is analyzing your YouTube video: ${content.substring(0, 50)}...`
        });
        
        setWebhookDisplayed(false);
        setStage("analysis");
        
        return;
      }
    }
    
    if (n8nResponse && n8nResponse.connectionFailed) {
      console.log("Connection to n8n webhook failed, using local analysis instead");
      toast({
        title: "Webhook Connection Issue", 
        description: "Using built-in analysis instead of external service"
      });
      analyzeContent(content, contentType, transcript);
      return;
    }
    
    if (n8nResponse && (n8nResponse.output || n8nResponse.data || n8nResponse.result)) {
      processN8nResponse(n8nResponse, content, contentType, transcript);
    } else {
      analyzeContent(content, contentType, transcript);
    }
  };
  
  // Add any missing handler functions
  const handleStartQuiz = () => {
    if (analysis && analysis.quiz) {
      setQuiz(analysis.quiz);
      setStage("quiz");
    } else {
      toast({
        title: "No quiz available",
        description: "There is no quiz available for this content yet.",
        variant: "destructive"
      });
    }
  };

  // Make sure any calls to testWebhook have both parameters
  const handleRetryWebhook = () => {
    if (contentDetails.content && contentDetails.contentType) {
      handleContentSubmit(contentDetails.content, contentDetails.contentType, contentDetails.transcript);
      
      toast({
        title: "Retrying Analysis",
        description: "Sending content for analysis again.",
        variant: "default"
      });
    }
  };

  const handleQuizComplete = (results: any) => {
    setCertificate({
      title: contentSummary.title || "Content Assessment",
      score: results.score,
      maxScore: results.maxScore,
      userInfo: userInfo,
      date: new Date().toLocaleDateString(),
      contentDetails: contentDetails
    });
    
    if (userInfo.fullName && userInfo.email) {
      setStage("certificate");
    } else {
      setStage("userInfo");
    }
  };

  const handleUserInfoSubmit = (info: UserInfo) => {
    setUserInfo(info);
    setStage("certificate");
  };

  const handleVerificationRequest = () => {
    setStage("verification");
  };

  const handleVerificationComplete = (verificationData: any) => {
    setIsVerified(true);
    setStage("certificate");
    
    toast({
      title: "Verification Complete",
      description: "Your identity has been verified successfully.",
      variant: "default"
    });
  };

  const handleDownloadCertificate = () => {
    toast({
      title: "Certificate Download",
      description: "Your certificate is being prepared for download.",
      variant: "default"
    });
    
    // Certificate download logic would go here
    console.log("Certificate download initiated");
  };

  const handleNewAssessment = () => {
    setStage("input");
    setAnalysis(null);
    setQuiz(null);
    setCertificate(null);
    setContentDetails({
      content: "",
      contentType: "",
      transcript: ""
    });
    setContentSummary({
      title: "",
      description: ""
    });
    setWebhookDisplayed(false);
  };

  const handleAssessmentComplete = (results: any) => {
    setAssessmentResults(results);
    const credits = calculateCredits(results);
    
    setCertificate({
      title: contentSummary.title || "Content Assessment",
      score: results.score,
      maxScore: results.maxScore,
      credits: credits,
      userInfo: userInfo,
      date: new Date().toLocaleDateString(),
      contentDetails: contentDetails
    });
    
    if (userInfo.fullName && userInfo.email) {
      setStage("certificate");
    } else {
      setStage("userInfo");
    }
  };

  useEffect(() => {
    const query = new URLSearchParams(location.search);
    const content = query.get('content');
    const type = query.get('type');
    const n8nResponseParam = query.get('n8nResponse');
    const connectionFailed = query.get('connectionFailed') === 'true';
    const error = query.get('error');
    
    if (content && type) {
      let n8nResponseData = null;
      if (n8nResponseParam) {
        try {
          n8nResponseData = JSON.parse(decodeURIComponent(n8nResponseParam));
          console.log("Found n8n response in URL:", n8nResponseData);
          setLastWebhookResponse(n8nResponseData);
        } catch (e) {
          console.error("Error parsing n8n response from URL:", e);
        }
      }
      
      if (connectionFailed && !n8nResponseData) {
        n8nResponseData = {
          connectionFailed: true,
          error: error || "Failed to connect to the AI analysis service"
        };
        setLastWebhookResponse(n8nResponseData);
      }
      
      handleContentSubmit(content, type, undefined, n8nResponseData);
    }
  }, [location]);

  return (
    <div className="max-container section-padding">
      <div className="text-center mb-8">
        <h1 className="text-3xl font-bold mb-2">Learn & Earn Credits</h1>
        <p className="text-muted-foreground max-w-2xl mx-auto">
          Study any content and earn verifiable AiCE Points, CPD, CME, and CE credits through AI-powered assessments. 
          Upload content, generate transcripts, take quizzes, and receive certificates.
        </p>
      </div>
      
      {stage === "input" && (
        <ContentInput 
          onSubmit={handleContentSubmit} 
          isLoading={isLoading}
          initialContent={contentDetails.content}
          initialType={contentDetails.contentType} 
        />
      )}
      
      {stage === "analysis" && analysis && (
        <ContentAnalysis 
          analysis={analysis} 
          onStartQuiz={handleStartQuiz} 
          webhookResponse={lastWebhookResponse}
          webhookDisplayed={webhookDisplayed}
          onWebhookDisplayed={() => setWebhookDisplayed(true)}
          onRetryWebhook={handleRetryWebhook}
          hideErrors={true} 
        />
      )}
      
      {stage === "assessment" && lastWebhookResponse && (
        <Assessment 
          webhookResponse={lastWebhookResponse}
          contentDetails={contentDetails}
          onAssessmentComplete={handleAssessmentComplete}
          onBackToContent={() => setStage("analysis")}
        />
      )}
      
      {stage === "quiz" && quiz && (
        <Quiz questions={quiz} onComplete={handleQuizComplete} />
      )}
      
      {stage === "userInfo" && (
        <UserInfoForm onSubmit={handleUserInfoSubmit} />
      )}
      
      {stage === "verification" && (
        <VerificationProfileForm
          onComplete={handleVerificationComplete}
          onCancel={() => setStage("certificate")}
        />
      )}
      
      {stage === "certificate" && certificate && (
        <Certificate 
          {...certificate}
          isVerified={isVerified}
          onDownload={handleDownloadCertificate}
          onNewAssessment={handleNewAssessment}
          onVerify={handleVerificationRequest}
        />
      )}
    </div>
  );
};

export default Learn;

Build error

today at 12:51 AM


src/pages/Learn.tsx(437,21): error TS2554: Expected 2 arguments, but got 1.