import { useState, useEffect } from 'react';
import { useBeforeUnload } from '../../hooks/useBeforeUnload';
import { Calendar, Wand2, CheckCircle2, Loader, AlertTriangle, Play, Sparkles, X, Clock, Target } from 'lucide-react';
import Card from '../ui/Card';
import Button from '../ui/Button';
import Tag from '../ui/Tag';
import * as db from '../../lib/db';
import {
  getCurriculumWeek,
  generateCurriculumDraft,
  confirmVersion,
  rejectVersion,
  enrichTopicsForCurriculum,
  getActiveVersion,
  getDraftVersion
} from '../../lib/curriculumService';

const CurriculumManager = () => {
  const [activeVersion, setActiveVersion] = useState(null);
  const [draftVersion, setDraftVersion] = useState(null);
  const [topics, setTopics] = useState([]);
  
  const [isLoading, setIsLoading] = useState(true);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isEnriching, setIsEnriching] = useState(false);
  const [statusMessage, setStatusMessage] = useState('');
  
  const [generationReason, setGenerationReason] = useState('');

  // Prevent tab close during long AI operations
  useBeforeUnload(isGenerating || isEnriching);

  const currentIsoWeek = (() => {
    const d = new Date();
    d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
    const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
    return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
  })();
  
  const currentWeek = getCurriculumWeek(currentIsoWeek);

  const load = async () => {
    setIsLoading(true);
    try {
      const [active, draft, allTopics] = await Promise.all([
        getActiveVersion(),
        getDraftVersion(),
        db.getTopics(),
      ]);
      setActiveVersion(active);
      setDraftVersion(draft);
      setTopics(allTopics);
    } catch (e) {
      console.error('Failed to load curriculum state:', e);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => { load(); }, []);

  const showStatus = (msg) => {
    setStatusMessage(msg);
    setTimeout(() => setStatusMessage(''), 4000);
  };

  const handleEnrichTopics = async () => {
    setIsEnriching(true);
    try {
      const res = await enrichTopicsForCurriculum();
      showStatus(`Enrichment complete! Enriched: ${res.enriched}, Skipped: ${res.skipped}`);
      await load();
    } catch (e) {
      showStatus(`Enrichment failed: ${e.message}`);
    } finally {
      setIsEnriching(false);
    }
  };

  const handleGenerate = async () => {
    setIsGenerating(true);
    try {
      await generateCurriculumDraft(generationReason || 'Admin request');
      setGenerationReason('');
      showStatus('Draft generated successfully!');
      await load();
    } catch (e) {
      showStatus(`Generation failed: ${e.message}`);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleConfirmDraft = async () => {
    if (!draftVersion) return;
    if (!confirm('This will replace the currently active curriculum for all employees. Proceed?')) return;
    
    try {
      // Typically we'd pass the actual admin user ID here, hardcoded to 'admin' for MVP
      await confirmVersion(draftVersion.id, 'admin');
      showStatus('Curriculum activated!');
      await load();
    } catch (e) {
      showStatus(`Confirmation failed: ${e.message}`);
    }
  };

  const handleRejectDraft = async () => {
    if (!draftVersion) return;
    if (!confirm('Are you sure you want to discard this draft?')) return;
    
    try {
      await rejectVersion(draftVersion.id);
      showStatus('Draft discarded.');
      await load();
    } catch (e) {
      showStatus(`Rejection failed: ${e.message}`);
    }
  };

  // --- Rendering Helpers ---

  const renderCoverageStats = (stats) => {
    if (!stats) return null;
    return (
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
        <div className="text-center p-3 bg-bg-warm rounded-[var(--r-sm)]">
          <div className="text-xl font-bold text-teal">{stats.themes_scheduled} / {stats.themes_kb}</div>
          <div className="text-xs text-fg-muted">Themes Scheduled</div>
        </div>
        <div className="text-center p-3 bg-bg-warm rounded-[var(--r-sm)]">
          <div className="text-xl font-bold text-purple-600">{stats.topics_scheduled} / {stats.topics_kb}</div>
          <div className="text-xs text-fg-muted">Topics Covered</div>
        </div>
        <div className="text-center p-3 bg-bg-warm rounded-[var(--r-sm)]">
          <div className="text-xl font-bold text-amber-600">26</div>
          <div className="text-xs text-fg-muted">Total Weeks</div>
        </div>
        <div className="text-center p-3 bg-bg-warm rounded-[var(--r-sm)]">
          <div className="text-xl font-bold text-blue-600">100%</div>
          <div className="text-xs text-fg-muted">Perpetual Cycle</div>
        </div>
      </div>
    );
  };

  const renderScheduleList = (schedule, isActiveVersion = false) => {
    return (
      <div className="divide-y divide-bg-warm mt-6 border border-bg-warm rounded-[var(--r-lg)] overflow-hidden">
        {schedule.map((week) => {
          const isCurrent = isActiveVersion && week.week_number === currentWeek;
          
          return (
            <div key={week.week_number} className={`p-4 ${isCurrent ? 'bg-teal/5 border-l-4 border-l-teal' : 'bg-bg'}`}>
              <div className="flex flex-col md:flex-row md:items-center gap-4">
                <div className={`w-12 h-12 rounded-[var(--r-org)] flex items-center justify-center font-mono text-lg font-bold flex-shrink-0 ${isCurrent ? 'bg-teal text-white' : 'bg-bg-warm text-fg'}`}>
                  {week.week_number}
                </div>
                
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <Tag variant="dark" className="text-xs">{week.theme}</Tag>
                    {isCurrent && <Tag variant="accent" className="text-[10px]">Current Week</Tag>}
                    <span className="text-xs text-fg-muted flex items-center gap-1 ml-2">
                      <Clock size={12} /> {week.estimated_duration}m
                    </span>
                  </div>
                  
                  <div className="font-medium text-sm mb-1">
                    Topics: {week.topic_ids.join(', ')}
                  </div>
                  
                  <p className="text-xs text-fg-muted italic">
                    Rationale: {week.week_rationale}
                  </p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  // --- Main Render ---

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader size={32} className="text-teal animate-spin" />
      </div>
    );
  }

  const learningTopics = topics.filter(t => t.type !== 'fact' && t.learning_relevance !== 'exclude');
  const unenrichedCount = learningTopics.filter(t => !t.theme).length;

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-20">
      
      {/* Header & Global Status */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-teal flex items-center gap-2">
            <Calendar size={24} /> 26-Week Curriculum
          </h1>
          <p className="text-sm text-fg-muted">Manage the AI-generated perpetual learning cycle.</p>
        </div>
        
        {statusMessage && (
          <div className="px-4 py-2 bg-teal/10 text-teal rounded-[var(--r-sm)] text-sm font-medium animate-in slide-in-from-top-2">
            {statusMessage}
          </div>
        )}
      </div>

      {/* Draft Preview View */}
      {draftVersion && (
        <Card className="border-2 border-amber-400 bg-amber-50/30">
          <div className="flex items-center justify-between border-b border-amber-200 pb-4 mb-4">
            <div>
              <h2 className="text-xl font-bold text-amber-700 flex items-center gap-2">
                <Sparkles size={20} /> Curriculum Draft Preview
              </h2>
              <p className="text-sm text-amber-600/80">Generated for: "{draftVersion.generation_reason}"</p>
            </div>
            <div className="flex gap-2">
              <Button variant="outline" onClick={handleRejectDraft} className="border-amber-300 text-amber-700 hover:bg-amber-100">
                <X size={16} className="mr-2" /> Discard
              </Button>
              <Button onClick={handleConfirmDraft} className="bg-amber-600 text-white hover:bg-amber-700">
                <CheckCircle2 size={16} className="mr-2" /> Confirm & Activate
              </Button>
            </div>
          </div>
          
          {renderCoverageStats(draftVersion.coverage_stats)}
          {renderScheduleList(draftVersion.schedule, false)}
        </Card>
      )}

      {/* Empty State / Generation Tools */}
      {!draftVersion && (
        <Card className="border border-bg-warm">
          <div className="mb-6">
            <h2 className="text-lg font-bold mb-2">Curriculum Generator</h2>
            <p className="text-sm text-fg-muted">Generate a new 26-week draft based on the current knowledge base.</p>
          </div>
          
          {learningTopics.length === 0 ? (
            <div className="flex items-center gap-2 text-amber-600 bg-amber-50 p-4 rounded-[var(--r-sm)] border border-amber-200">
              <AlertTriangle size={20} />
              <span>No learning topics in the knowledge base. Import sources first before generating a curriculum.</span>
            </div>
          ) : unenrichedCount > 0 ? (
            <div className="space-y-4">
              <div className="flex items-center gap-2 text-amber-600 bg-amber-50 p-4 rounded-[var(--r-sm)] border border-amber-200">
                <AlertTriangle size={20} />
                <span>There are {unenrichedCount} topics missing theme and complexity data. Enrich them before generating.</span>
              </div>
              <Button onClick={handleEnrichTopics} disabled={isEnriching}>
                {isEnriching ? <Loader size={16} className="animate-spin mr-2" /> : <Sparkles size={16} className="mr-2" />}
                Enrich {unenrichedCount} Topics
              </Button>
            </div>
          ) : (
            <div className="flex flex-col md:flex-row gap-4 items-end">
              <div className="flex-1">
                <label className="block text-sm font-medium mb-1 text-fg-muted">Reason for generation (optional)</label>
                <input
                  type="text"
                  value={generationReason}
                  onChange={e => setGenerationReason(e.target.value)}
                  placeholder="e.g., 'Include new privacy topics' or 'Q3 refresh'"
                  className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-2 bg-bg focus:outline-none focus:border-teal"
                />
              </div>
              <Button onClick={handleGenerate} disabled={isGenerating}>
                {isGenerating ? (
                  <><Loader size={16} className="animate-spin mr-2" /> Architecting...</>
                ) : (
                  <><Wand2 size={16} className="mr-2" /> Generate Draft</>
                )}
              </Button>
            </div>
          )}
        </Card>
      )}

      {/* Active Version View */}
      {!draftVersion && activeVersion && (
        <Card className="border border-bg-warm">
          <div className="flex items-center justify-between border-b border-bg-warm pb-4 mb-4">
            <div>
              <h2 className="text-xl font-bold flex items-center gap-2">
                <Target size={20} className="text-teal" /> Active Curriculum
              </h2>
              <p className="text-sm text-fg-muted">Version {activeVersion.version_number} · Confirmed {new Date(activeVersion.confirmed_at).toLocaleDateString()}</p>
            </div>
            <Tag variant="success">Active</Tag>
          </div>
          
          {renderCoverageStats(activeVersion.coverage_stats)}
          {renderScheduleList(activeVersion.schedule, true)}
        </Card>
      )}
      
      {!draftVersion && !activeVersion && learningTopics.length > 0 && unenrichedCount === 0 && (
        <div className="text-center py-12">
          <Calendar size={48} className="mx-auto text-fg-muted/30 mb-4" />
          <h3 className="text-xl font-bold mb-2">No active curriculum</h3>
          <p className="text-fg-muted max-w-md mx-auto">
            Generate your first curriculum draft above to get started.
          </p>
        </div>
      )}
    </div>
  );
};

export default CurriculumManager;
