import { useState, useEffect } from 'react';
import { BookOpen, CheckCircle, ArrowRight, ChevronLeft, Calendar, CheckSquare } from 'lucide-react';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import Card from '../components/ui/Card';
import Button from '../components/ui/Button';
import Tag from '../components/ui/Tag';
import { useApp } from '../store/AppContext';
import { getAssignedTopic } from '../lib/learningService';
import { generateWeeklyQuiz } from '../lib/testService';
import { getYearProgress, getCurriculumCycle, getCurriculumWeek, getActiveVersion, getCurrentWeekContent } from '../lib/curriculumService';
import * as db from '../lib/db';
import MicroLearningSelector from '../components/micro_learning/MicroLearningSelector';
import { useMicroLearningCompletions } from '../hooks/useMicroLearningCompletions';

const Leren = () => {
  const { state } = useApp();
  const navigate = useNavigate();
  const [assignedTopic, setAssignedTopic] = useState(null);
  const [allTopics, setAllTopics] = useState([]);
  
  // View state
  const [view, setView] = useState('overview'); // overview, detail
  const [activeTopic, setActiveTopic] = useState(null);
  
  // Weekly status
  const [weeklyDone, setWeeklyDone] = useState(false);
  const [sessionDone, setSessionDone] = useState(false);

  // Curriculum state
  const [hasCurriculum, setHasCurriculum] = useState(false);
  const [yearProgress, setYearProgress] = useState(null);
  const [weekContent, setWeekContent] = useState(null);

  const { getSessionCompletions } = useMicroLearningCompletions();

  useEffect(() => {
    if (state.currentUser) {
      const load = async () => {
        const [assigned, topics] = await Promise.all([
          getAssignedTopic(state.currentUser.id, state.weekNumber),
          db.getTopics(),
        ]);
        setAssignedTopic(assigned);
        setAllTopics(topics);

        // Load curriculum data
        let currentWeekContent = null;
        try {
          const activeVersion = await getActiveVersion();
          setHasCurriculum(!!activeVersion);
          if (activeVersion) {
            const [yProgress, wc] = await Promise.all([
              getYearProgress(state.currentUser.id, state.weekNumber),
              getCurrentWeekContent(state.weekNumber),
            ]);
            setYearProgress(yProgress);
            currentWeekContent = wc;
            setWeekContent(wc);
          }
        } catch (e) {
          console.warn('[Learn] Could not load curriculum data:', e.message);
        }

        // Check completions for the current week
        const completions = await getSessionCompletions(state.weekNumber);
        
        // Define required topics for the week
        // We assume assignedTopic is the minimum required if no explicit list in weekContent.
        // Actually, let's just check if the assignedTopic is completed.
        const requiredTopicIds = currentWeekContent?.topics || [assigned?.id].filter(Boolean);
        
        const completedTopicIds = new Set(completions.map(c => c.topic_id));
        const allRequiredCompleted = requiredTopicIds.length > 0 && requiredTopicIds.every(id => completedTopicIds.has(id));

        setWeeklyDone(allRequiredCompleted);
      };
      load();
    }
  }, [state.currentUser, state.weekNumber, view]); // Reload when view changes (e.g. going back to overview)

  const handleOpenTopic = (topic) => {
    setActiveTopic(topic);
    setView('detail');
    setSessionDone(false);
  };

  const handleTopicCompleted = () => {
    setSessionDone(true);
    // Pre-generate this week's test questions in the background so they are
    // ready in localStorage by the time the user navigates to /test. The call
    // is fire-and-forget — a failure here is harmless; the test page will just
    // generate on demand as before.
    if (state.currentUser) {
      generateWeeklyQuiz(state.currentUser.id, state.weekNumber).catch(() => {});
    }
  };

  // ── Detail View ──────────────────────────────────────────
  if (view === 'detail' && activeTopic) {
    if (sessionDone) {
      return (
        <div className="p-4 md:p-8 max-w-2xl mx-auto text-center py-20">
          <motion.div initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: 'spring', stiffness: 200 }}>
            <CheckCircle size={80} className="mx-auto text-teal mb-6" />
          </motion.div>
          <h1 className="text-3xl font-bold mb-4">Topic reviewed!</h1>
          <p className="text-fg-muted mb-2">
            You have successfully completed a micro learning for "<strong>{activeTopic.label}</strong>".
          </p>
          <p className="text-fg-muted mb-8">
            Ready to put it to the test, or explore another format for this topic?
          </p>
          <div className="flex flex-wrap justify-center gap-3">
            <Button variant="outline" onClick={() => { setView('overview'); setSessionDone(false); }}>
              <ChevronLeft size={16} className="mr-2" /> Back to Station
            </Button>
            <Button variant="outline" onClick={() => setSessionDone(false)}>
              Try another format
            </Button>
            <Button onClick={() => navigate('/test')}>
              <CheckSquare size={16} className="mr-2" /> Go to test
            </Button>
          </div>
        </div>
      );
    }

    return (
      <div className="p-4 md:p-8 max-w-4xl mx-auto pb-24 md:pb-8">
        <button onClick={() => setView('overview')} className="flex items-center gap-2 text-fg-muted hover:text-teal mb-6 transition-colors">
          <ChevronLeft size={16} /> Back to overview
        </button>

        <div className="mb-8">
          <div className="flex items-center gap-3 mb-2">
            <Tag variant="dark" className="font-mono text-xs">{activeTopic.type}</Tag>
            {activeTopic.id === assignedTopic?.id && <Tag variant="accent">Weekly Required</Tag>}
          </div>
          <h1 className="text-3xl md:text-4xl font-bold text-teal">{activeTopic.label}</h1>
          <p className="text-fg-muted mt-2">{activeTopic.description}</p>
        </div>

        <MicroLearningSelector 
          topicId={activeTopic.id} 
          sessionWeek={state.weekNumber} 
          onTopicCompleted={handleTopicCompleted} 
        />
      </div>
    );
  }

  // ── Overview ──────────────────────────────────────────────
  const otherTopics = allTopics.filter(t => t.id !== assignedTopic?.id && t.type !== 'fact' && t.learning_relevance !== 'exclude');
  const currentCycle = getCurriculumCycle(state.weekNumber);
  const currWeek = getCurriculumWeek(state.weekNumber);

  return (
    <div className="p-4 md:p-8 max-w-5xl mx-auto pb-24 md:pb-8 animate-in fade-in duration-300">
      <div className="mb-10">
        <h1 className="text-3xl md:text-4xl font-bold text-teal mb-3">Learning Station</h1>
        <p className="text-fg-muted text-lg">
          {hasCurriculum
            ? `Cycle ${currentCycle} · Week ${currWeek} of 26`
            : 'Complete at least 1 topic per week. Explore more from the library!'}
        </p>
      </div>

      {/* Progress Cards (only shown when curriculum exists) */}
      {hasCurriculum && yearProgress && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
          {/* Cycle Progress */}
          <Card className="border border-bg-warm text-center p-4">
            <div className="relative w-16 h-16 mx-auto mb-2">
              <svg viewBox="0 0 36 36" className="w-full h-full -rotate-90">
                <circle cx="18" cy="18" r="15.5" fill="none" stroke="var(--color-bg-warm)" strokeWidth="3" />
                <circle
                  cx="18" cy="18" r="15.5" fill="none"
                  stroke="var(--color-teal)" strokeWidth="3"
                  strokeDasharray={`${yearProgress.percentage} 100`}
                  strokeLinecap="round"
                  className="transition-all duration-700"
                />
              </svg>
              <span className="absolute inset-0 flex items-center justify-center text-sm font-bold">
                {yearProgress.percentage}%
              </span>
            </div>
            <div className="text-xs text-fg-muted">Cycle Progress</div>
            <div className="text-[10px] text-fg-muted">{yearProgress.completed}/{yearProgress.total} weeks</div>
          </Card>

          {/* Current Week */}
          <Card className="border border-bg-warm text-center p-4 flex flex-col items-center justify-center">
            <Calendar size={24} className="text-teal mb-1" />
            <div className="text-2xl font-bold text-teal">{currWeek}</div>
            <div className="text-xs text-fg-muted">Current Week</div>
          </Card>

          {/* Theme */}
          <Card className="border border-bg-warm text-center p-4 flex flex-col items-center justify-center col-span-2">
            <BookOpen size={24} className="text-purple-600 mb-1" />
            <div className="text-lg font-bold text-purple-700">{weekContent?.theme || 'General'}</div>
            <div className="text-xs text-fg-muted">Current Theme</div>
          </Card>
        </div>
      )}

      {/* Required Topic */}
      {assignedTopic && (
        <div className="mb-8">
          <h2 className="text-xl font-bold mb-4 flex items-center gap-2">
            This Week's Topic {weeklyDone && <CheckCircle size={20} className="text-teal" />}
          </h2>
          <Card 
            hoverable 
            className={`border-2 cursor-pointer transition-all ${weeklyDone ? 'border-teal/30 bg-teal/5' : 'border-teal shadow-md'}`}
            onClick={() => handleOpenTopic(assignedTopic)}
          >
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div>
                <div className="flex items-center gap-2 mb-2">
                  <Tag variant={weeklyDone ? 'success' : 'accent'} className="text-xs">
                    {weeklyDone ? 'Completed' : 'Required'}
                  </Tag>
                  {hasCurriculum && (
                    <Tag variant="dark" className="text-[10px]">Theme: {weekContent?.theme || 'General'}</Tag>
                  )}
                </div>
                <h3 className="text-2xl font-bold text-teal">{assignedTopic.label}</h3>
                <p className="text-fg-muted mt-1">{assignedTopic.description}</p>
              </div>
              <Button className="whitespace-nowrap flex-shrink-0">
                {weeklyDone ? 'Review' : 'Start Learning'} <ArrowRight size={18} className="ml-2" />
              </Button>
            </div>
          </Card>
        </div>
      )}

      {/* Other Available Topics */}
      {otherTopics.length > 0 && (
        <div>
          <h2 className="text-xl font-bold mb-4">Knowledge Base Library</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {otherTopics.map(topic => (
              <Card 
                key={topic.id} 
                hoverable 
                className="border border-bg-warm cursor-pointer flex flex-col h-full"
                onClick={() => handleOpenTopic(topic)}
              >
                <Tag variant="dark" className="self-start text-[10px] mb-2">{topic.type}</Tag>
                <h3 className="font-bold text-lg mb-1">{topic.label}</h3>
                <p className="text-sm text-fg-muted line-clamp-2 mb-4 flex-1">{topic.description}</p>
                <div className="flex items-center text-teal font-medium text-sm mt-auto group">
                  Learn <ArrowRight size={14} className="ml-1 transition-transform group-hover:translate-x-1" />
                </div>
              </Card>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default Leren;
