import { useEffect, useMemo, useState } from "react";
import { FlashcardView } from "../features/flashcard/FlashcardView";
import { AssessmentView } from "../features/learning-assessment/AssessmentView";
import { QuizView } from "../features/quiz/QuizView";
import { generateContent, resolveGatewayEndpoint } from "../integrations/ai-gateway/client";
import type { AssessmentResponse, Question } from "../types/api";
import type { AppView } from "../types/learning";
import { AppShell } from "./components/AppShell";
import { Button, RuntimeStateCard } from "./components/ui";
import { useLocalServiceHealth } from "./hooks/useLocalServiceHealth";
import { useLearningContentCache } from "./hooks/useLearningContentCache";
import { useVideoRagSession } from "./hooks/useVideoRagSession";
import { useYouTubeContext } from "./hooks/useYouTubeContext";
import { HomeView } from "./views/HomeView";
import { ProgressiveQuizSession, quizBatchLoader } from "../integrations/learning/progressiveQuiz";

interface AssessmentSession {
  assessment: AssessmentResponse;
  questions: Question[];
  videoId: string;
}

export function App() {
  const [activeView, setActiveView] = useState<AppView>("home");
  const [isDark, setIsDark] = useState(false);
  const [assessmentSession, setAssessmentSession] = useState<AssessmentSession | null>(null);
  const learningContent = useLearningContentCache(generateContent);
  const serviceHealth = useLocalServiceHealth(true);
  const youtube = useYouTubeContext(true);
  const video = youtube.state.status === "ready" ? youtube.state.video : undefined;
  const quizSession = useMemo(() => video ? new ProgressiveQuizSession(
    `${video.videoId}:${video.durationSec}:${video.language}`, quizBatchLoader(video, generateContent),
  ) : undefined, [video?.videoId, video?.durationSec, video?.language]);
  useEffect(() => () => quizSession?.suspend(), [quizSession]);
  useEffect(() => {
    if (!quizSession) return;
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 5000);
    void (async () => {
      try {
        const endpoint = resolveGatewayEndpoint();
        const response = await fetch(endpoint.replace(/\/generate$/, "/health"), {
          signal: controller.signal, cache: "no-store", credentials: "omit",
        });
        if (!response.ok) return;
        const health = await response.json();
        if (!controller.signal.aborted && health.status === "ok"
          && typeof health.provider === "string" && typeof health.model === "string") {
          quizSession.reconcileGateway(JSON.stringify([endpoint, health.provider, health.model]));
        }
      } catch { /* Keep the existing cooldown if gateway identity cannot be verified. */ }
      finally { clearTimeout(timer); }
    })();
    return () => { controller.abort(); clearTimeout(timer); };
  }, [quizSession]);
  const ragSession = useVideoRagSession({
    enabled: true,
    serviceStatus: serviceHealth.state.status,
    video,
  });
  const ragRetryable = "retryable" in ragSession.state && ragSession.state.retryable;
  const navigate = (view: AppView) => {
    setActiveView(view);
  };

  useEffect(() => {
    setActiveView("home");
    setAssessmentSession(null);
  }, [video?.videoId]);

  const completeQuiz = (result: AssessmentResponse, questions: Question[]) => {
    if (!video) {
      return;
    }
    setAssessmentSession({ assessment: result, questions, videoId: video.videoId });
    setActiveView("assessment");
  };

  const restartQuiz = () => {
    setAssessmentSession(null);
    if (quizSession?.getSnapshot().status === "submitted") quizSession.redo();
    setActiveView("quiz");
  };

  const renderActiveView = () => {
    if (activeView === "home") {
      return (
        <HomeView
          extensionOrigin={serviceHealth.extensionOrigin}
          generateContent={generateContent}
          onNavigate={navigate}
          onRefreshHealth={serviceHealth.refresh}
          onRetryRag={ragSession.retry}
          onSeek={(seconds) => void youtube.seekTo(seconds)}
          ragReady={ragSession.isReady}
          ragState={ragSession.state}
          serviceHealth={serviceHealth.state}
          video={video}
          videoDetectionMessage={youtube.state.message}
        />
      );
    }

    if (activeView === "assessment") {
      const belongsToActiveVideo = Boolean(
        video && assessmentSession?.videoId === video.videoId,
      );
      return (
        <AssessmentView
          assessment={belongsToActiveVideo ? assessmentSession?.assessment ?? null : null}
          onReviewQuiz={restartQuiz}
          onSeek={(seconds) => void youtube.seekTo(seconds)}
          onStartQuiz={restartQuiz}
          questions={belongsToActiveVideo ? assessmentSession?.questions ?? [] : []}
        />
      );
    }

    if (!video || !ragSession.isReady) {
      return (
        <div className="view-stack">
          <RuntimeStateCard
            message={video ? ragSession.state.message : youtube.state.message}
            title="Nội dung video chưa sẵn sàng"
          >
            <Button onClick={() => setActiveView("home")} tone="secondary">
              Về trang chính
            </Button>
            {video && ragRetryable && serviceHealth.state.status === "ready" ? (
              <Button onClick={ragSession.retry}>Thử lại</Button>
            ) : null}
          </RuntimeStateCard>
        </div>
      );
    }

    if (activeView === "quiz" && quizSession) {
      return (
        <QuizView
          generateContent={generateContent}
          key={video.videoId}
          session={quizSession}
          onComplete={completeQuiz}
          onSeek={(seconds) => void youtube.seekTo(seconds)}
          video={video}
        />
      );
    }

    return (
      <FlashcardView
        generateContent={generateContent}
        key={video.videoId}
        loadFlashcards={learningContent.loadFlashcards}
        onSeek={(seconds) => void youtube.seekTo(seconds)}
        video={video}
      />
    );
  };

  return (
    <AppShell
      activeView={activeView}
      isDark={isDark}
      notice={youtube.notice}
      onDismissNotice={youtube.dismissNotice}
      onNavigate={navigate}
      onToggleTheme={() => setIsDark((current) => !current)}
    >
      <div className="learning-session" key={video?.videoId ?? "no-video"}>
        {renderActiveView()}
      </div>
    </AppShell>
  );
}
