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);
    
    // Pass contentType as second argument here
    const parsedResponse = parseWebhookResponse(n8nResponse, contentType);
    
    if (parsedResponse.status === "error" || parsedResponse.connectionFailed) {
      // Removed toast notification for analysis error
      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") {
      // Removed toast notification for analysis in progress
      
      // 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 {
      // Removed toast notification for incomplete analysis
    }
  };

  // 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
  };
  
  // Fixed testWebhook function to properly accept and use both parameters
  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 {
      console.log(`Testing webhook for ${contentType} at URL:`, webhookUrl);
      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
        })
      });
      
      // Enhanced error handling to check the actual response status
      const status = response.ok ? "success" : "failed";
      console.log(`Webhook test ${status} for ${contentType} with status code:`, response.status);

      setWebhookDebugInfo({
        url: webhookUrl,
        status: status,
        timestamp: new Date().toISOString(),
        contentType
      });
      
      // Log the response details for debugging
      if (response.ok) {
        try {
          const responseData = await response.json();
          console.log("Webhook test response data:", responseData);
        } catch (e) {
          const responseText = await response.text();
          console.log("Webhook test raw response:", responseText);
          console.log("Response status:", response.status);
        }
      } else {
        console.error(`Webhook test failed with status: ${response.status}`);
        const responseText = await response.text();
        console.error("Error response:", responseText);
      }
    } 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
      });
    }
    
    // Update content details with the new content
    setContentDetails({
      content,
      contentType,
      transcript: transcript || ""
    });
    
    setContentPersisted(false);
    
    if (contentType === "youtube") {
      console.log(`Processing YouTube URL with webhook: ${getWebhookUrl("youtube")}`);
      console.log("YouTube content:", content);
      
      // Removed toast notification for YouTube webhook request
    }
    
    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");
        // Removed toast notification for using built-in analysis
        analyzeContent(content, contentType, transcript);
      }
      return;
    }
    
    if (contentType === "youtube") {
      if (n8nResponse && (n8nResponse.status === "submitted" || n8nResponse.status === "processing")) {
        console.log("YouTube submission acknowledged:", n8nResponse);
        
        // Removed toast notification for YouTube video submission
        
        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");
      // Removed toast notification for webhook connection issue
      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"
      });
    }
  };

  const handleRetryWebhook = () => {
    if (contentDetails.content && contentDetails.contentType) {
      handleContentSubmit(contentDetails.content, contentDetails.contentType, contentDetails.transcript);
      
      // Removed toast notification for retrying analysis
    }
  };

  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");
  };

  // Fix: Ensure testWebhook is called with both parameters
  const handleNewAssessment = () => {
    setStage("input");
    setAnalysis(null);
    setQuiz(null);
    setCertificate(null);
    setContentDetails({
      content: "",
      contentType: "",
      transcript: ""
    });
    setContentSummary({
      title: "",
      description: ""
    });
    setWebhookDisplayed(false);
    
    // Fixed: Add the second parameter to testWebhook call
    testWebhook("youtube", {});
  };

  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(() => {
    // Call testWebhook with both parameters
    testWebhook("youtube", { initialTest: true });
    
    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;