import React, { useState, useEffect } from 'react';
import { BookOpen, CheckCircle, Loader, ArrowRight, Plus, Search, ChevronLeft, MessageSquare } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Link } from 'react-router-dom';
import Card from '../components/ui/Card';
import Button from '../components/ui/Button';
import Tag from '../components/ui/Tag';
import Input from '../components/ui/Input';
import LearningContentViewer from '../components/ui/LearningContentViewer';
import { useApp } from '../store/AppContext';
import { getAssignedTopic, generateLearningContent, getCachedContent, generateCustomTopic } from '../lib/learningService';
import * as db from '../lib/db';

const Leren = () => {
  const { state } = useApp();
  const [assignedTopic, setAssignedTopic] = useState(null);
  const [allTopics, setAllTopics] = useState([]);
  
  // View state
  const [view, setView] = useState('overview'); // overview, detail, creating
  const [activeTopic, setActiveTopic] = useState(null);
  const [content, setContent] = useState(null);
  
  // Loading & Error
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  
  // Custom Topic
  const [customTopicQuery, setCustomTopicQuery] = useState('');
  
  // Weekly status
  const [weeklyDone, setWeeklyDone] = useState(false);
  const [sessionDone, setSessionDone] = useState(false);

  // Feedback
  const [showFeedbackModal, setShowFeedbackModal] = useState(false);
  const [feedbackText, setFeedbackText] = useState('');
  const [feedbackPrompted, setFeedbackPrompted] = useState(false);

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

  const handleOpenTopic = async (topic) => {
    setActiveTopic(topic);
    setView('detail');
    setSessionDone(false);
    setError(null);
    setFeedbackText('');
    setFeedbackPrompted(false);
    const cached = await getCachedContent(topic.id);
    if (cached) {
      setContent(cached);
    } else {
      setContent(null);
    }
  };

  const loadContent = async () => {
    if (!activeTopic) return;
    setIsLoading(true);
    setError(null);
    try {
      const generated = await generateLearningContent(activeTopic);
      setContent(generated);
    } catch (e) {
      setError(e.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateCustom = async (e) => {
    e.preventDefault();
    if (!customTopicQuery.trim()) return;
    
    setIsLoading(true);
    setView('creating');
    setError(null);
    try {
      const newTopic = await generateCustomTopic(customTopicQuery);
      setAllTopics(await db.getTopics());
      setCustomTopicQuery('');
      handleOpenTopic(newTopic);
    } catch (e) {
      setError(e.message);
      setView('overview');
    } finally {
      setIsLoading(false);
    }
  };

  const doComplete = async () => {
    setSessionDone(true);
    if (!weeklyDone) {
      setWeeklyDone(true);
      await db.setLearnDone(state.currentUser.id, state.weekNumber);
    }
  };

  const handleComplete = () => {
    if (!feedbackPrompted) {
      setFeedbackPrompted(true);
      setShowFeedbackModal(true);
      return;
    }
    doComplete();
  };

  const handleSubmitFeedback = async () => {
    if (feedbackText.trim()) {
      await db.setSetting(
        `feedback:${state.currentUser.id}:${activeTopic.id}:${state.weekNumber}`,
        feedbackText.trim()
      );
    }
    setShowFeedbackModal(false);
    doComplete();
  };

  const handleSkipFeedback = () => {
    setShowFeedbackModal(false);
    doComplete();
  };

  // ── 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">Learning session complete!</h1>
          <p className="text-fg-muted mb-8">
            You have successfully reviewed "<strong>{activeTopic.label}</strong>".
            {weeklyDone && ' Your weekly minimum is met.'}
          </p>
          <div className="flex justify-center gap-4">
            <Button variant="outline" onClick={() => setView('overview')}>Learn Another</Button>
            <Link to="/test">
              <Button>Start Weekly Test <ArrowRight size={18} className="ml-2" /></Button>
            </Link>
          </div>
        </div>
      );
    }

    return (
      <div className="p-4 md:p-8 max-w-4xl mx-auto pb-24 md:pb-8">
        <AnimatePresence>
          {showFeedbackModal && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 z-50 flex items-center justify-center p-4"
              style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}
            >
              <motion.div
                initial={{ scale: 0.95, opacity: 0, y: 16 }}
                animate={{ scale: 1, opacity: 1, y: 0 }}
                exit={{ scale: 0.95, opacity: 0, y: 16 }}
                transition={{ type: 'spring', stiffness: 300, damping: 24 }}
                className="w-full max-w-lg"
              >
                <Card className="border border-bg-warm shadow-xl">
                  <div className="flex items-center gap-3 mb-2">
                    <div className="w-10 h-10 rounded-full bg-teal/10 flex items-center justify-center flex-shrink-0">
                      <MessageSquare size={20} className="text-teal" />
                    </div>
                    <h2 className="text-xl font-bold">How was this content?</h2>
                  </div>
                  <p className="text-fg-muted text-sm mb-5">
                    Your feedback helps improve future learning content. This is optional — you can skip if you prefer.
                  </p>
                  <textarea
                    autoFocus
                    value={feedbackText}
                    onChange={e => setFeedbackText(e.target.value)}
                    placeholder="What was clear? What could be improved? Anything missing?"
                    rows={4}
                    className="w-full rounded-[var(--r-sm)] border border-bg-warm bg-bg p-3 text-sm resize-none focus:outline-none focus:border-teal transition-colors"
                  />
                  <div className="flex justify-end gap-3 mt-4">
                    <Button variant="outline" onClick={handleSkipFeedback}>Skip</Button>
                    <Button onClick={handleSubmitFeedback}>Submit Feedback</Button>
                  </div>
                </Card>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>

        <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>

        {!content && !isLoading && (
          <Card className="border border-bg-warm text-center py-16">
            <BookOpen size={48} className="mx-auto text-teal/30 mb-4" />
            <p className="text-fg-muted mb-6">Click the button to generate personalized AI learning content for this topic.</p>
            <Button onClick={loadContent}>Generate Learning Content</Button>
          </Card>
        )}

        {isLoading && (
          <Card className="border border-bg-warm text-center py-16">
            <Loader size={48} className="mx-auto text-teal animate-spin mb-4" />
            <p className="font-medium">AI is generating your learning module...</p>
            <p className="text-fg-muted text-sm mt-2">This may take 10–30 seconds.</p>
          </Card>
        )}

        {error && (
          <Card className="border border-red-200 bg-red-50 text-red-900 p-6">
            <p className="font-bold mb-1">Generation failed</p>
            <p className="text-sm">{error}</p>
            <Button onClick={loadContent} variant="outline" className="mt-4 border-red-300 text-red-700">Try again</Button>
          </Card>
        )}

        {content && <LearningContentViewer content={content} topic={activeTopic} />}

        {content && (
          <div className="mt-10 pt-6 border-t border-bg-warm flex justify-end">
            <Button onClick={handleComplete}>
              <CheckCircle size={18} className="mr-2" /> Complete Session
            </Button>
          </div>
        )}
      </div>
    );
  }

  // ── Creating Topic Loading ─────────────────────────────────
  if (view === 'creating') {
    return (
      <div className="p-4 md:p-8 max-w-2xl mx-auto text-center py-20">
        <Loader size={48} className="mx-auto text-teal animate-spin mb-4" />
        <h1 className="text-2xl font-bold text-teal mb-2">Architecting New Topic</h1>
        <p className="text-fg-muted">The AI is creating a structure for "{customTopicQuery}"...</p>
      </div>
    );
  }

  // ── Overview ──────────────────────────────────────────────
  const otherTopics = allTopics.filter(t => t.id !== assignedTopic?.id && t.type !== 'fact');

  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">
          You must complete at least 1 topic per week. Feel free to explore more from the library!
        </p>
      </div>

      {error && (
        <div className="mb-6 bg-red-50 text-red-800 p-4 rounded-[var(--r-sm)] border border-red-200">
          {error}
        </div>
      )}

      {/* Required Topic */}
      {assignedTopic && (
        <div className="mb-12">
          <h2 className="text-xl font-bold mb-4 flex items-center gap-2">
            Weekly Assignment {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>
                <Tag variant={weeklyDone ? 'success' : 'accent'} className="mb-2">
                  {weeklyDone ? 'Completed' : 'Required'}
                </Tag>
                <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;
