import React, { useState, useEffect, useMemo } from 'react';
import { 
  Play, 
  CheckCircle, 
  Circle, 
  FileText, 
  HelpCircle, 
  PenTool, 
  Download, 
  ChevronLeft, 
  ChevronRight, 
  Info, 
  LayoutDashboard, 
  Clock, 
  StickyNote, 
  Upload, 
  X
} from 'lucide-react';

// --- Types ---
type LessonType = 'video' | 'text' | 'quiz' | 'assignment' | 'resource';
type LessonStatus = 'locked' | 'not_started' | 'in_progress' | 'completed';

interface Lesson {
  id: number;
  title: string;
  description: string;
  type: LessonType;
  duration: number; // in minutes
  status: LessonStatus;
  content?: string; // For text lessons
  videoUrl?: string;
  attachmentUrl?: string;
  userNotes?: string;
}

interface Course {
  id: number;
  title: string;
  category: string;
}

// --- Mock Data (Simulating Database) ---
const MOCK_COURSE: Course = {
  id: 101,
  title: "Advanced Web Development Patterns",
  category: "Computer Science"
};

const INITIAL_LESSONS: Lesson[] = [
  {
    id: 1,
    title: "Introduction to Modern Architecture",
    description: "Overview of what we will build in this course.",
    type: 'video',
    duration: 10,
    status: 'completed',
    videoUrl: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', // Placeholder
    userNotes: "Great intro, remember the 3-tier architecture point."
  },
  {
    id: 2,
    title: "Understanding React Hooks",
    description: "Deep dive into useState and useEffect.",
    type: 'video',
    duration: 25,
    status: 'in_progress',
    videoUrl: 'https://www.youtube.com/watch?v=dpw9EHDh2bM', // Placeholder
    userNotes: ""
  },
  {
    id: 3,
    title: "State Management Reading",
    description: "Read the documentation on Redux vs Context.",
    type: 'text',
    duration: 15,
    status: 'not_started',
    content: `
      <h3>Context API vs Redux</h3>
      <p>While Redux is a predictable state container for JavaScript apps, Context provides a way to pass data through the component tree without having to pass props down manually at every level.</p>
      <ul>
        <li><strong>Redux:</strong> Best for complex state, frequent updates, and large teams.</li>
        <li><strong>Context:</strong> Best for low-frequency updates like themes, user auth, and locale preferences.</li>
      </ul>
    `,
    userNotes: ""
  },
  {
    id: 4,
    title: "Mid-Term Quiz",
    description: "Test your knowledge on the first 3 modules.",
    type: 'quiz',
    duration: 20,
    status: 'not_started',
    userNotes: ""
  },
  {
    id: 5,
    title: "Final Project Assignment",
    description: "Submit your code repository link.",
    type: 'assignment',
    duration: 60,
    status: 'locked',
    userNotes: ""
  }
];

export default function CoursePlayer() {
  const [lessons, setLessons] = useState<Lesson[]>(INITIAL_LESSONS);
  const [currentLessonId, setCurrentLessonId] = useState<number>(2);
  const [showNotes, setShowNotes] = useState<boolean>(false);
  const [showAssignmentModal, setShowAssignmentModal] = useState<boolean>(false);
  const [tempNote, setTempNote] = useState<string>("");

  // Derived State
  const currentLesson = lessons.find(l => l.id === currentLessonId) || lessons[0];
  const currentIndex = lessons.findIndex(l => l.id === currentLessonId);
  
  const completedCount = lessons.filter(l => l.status === 'completed').length;
  const progressPercentage = Math.round((completedCount / lessons.length) * 100);
  
  const totalTimeSpent = lessons.reduce((acc, curr) => {
    return curr.status === 'completed' ? acc + curr.duration : acc;
  }, 0);

  // Sync temp note when lesson changes
  useEffect(() => {
    setTempNote(currentLesson.userNotes || "");
  }, [currentLessonId, lessons]);

  // --- Handlers ---

  const handleNavigate = (direction: 'prev' | 'next') => {
    const newIndex = direction === 'next' ? currentIndex + 1 : currentIndex - 1;
    if (newIndex >= 0 && newIndex < lessons.length) {
      setCurrentLessonId(lessons[newIndex].id);
    }
  };

  const handleMarkComplete = () => {
    setLessons(prev => prev.map(l => {
      if (l.id === currentLessonId) {
        return { ...l, status: 'completed' };
      }
      // Unlock next lesson logic could go here
      return l;
    }));
  };

  const handleSaveNote = () => {
    setLessons(prev => prev.map(l => 
      l.id === currentLessonId ? { ...l, userNotes: tempNote } : l
    ));
    // In a real app, this would call your API endpoint
    alert("Notes saved successfully!");
  };

  const getEmbedUrl = (url?: string) => {
    if (!url) return '';
    // Simple regex for Youtube to mimic PHP logic
    const ytMatch = url.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/);
    if (ytMatch) return `https://www.youtube.com/embed/${ytMatch[1]}`;
    return url;
  };

  // --- Render Helpers ---

  const getIcon = (type: LessonType, status: LessonStatus) => {
    if (status === 'completed') return <CheckCircle className="w-5 h-5 text-green-500" />;
    
    switch (type) {
      case 'video': return <Play className={`w-5 h-5 ${status === 'in_progress' ? 'text-blue-500' : 'text-gray-400'}`} />;
      case 'quiz': return <HelpCircle className="w-5 h-5 text-gray-400" />;
      case 'assignment': return <PenTool className="w-5 h-5 text-gray-400" />;
      case 'resource': return <Download className="w-5 h-5 text-gray-400" />;
      default: return <FileText className="w-5 h-5 text-gray-400" />;
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 font-sans text-slate-800">
      
      {/* --- Header --- */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-20 flex items-center justify-between">
          <div className="flex-1">
            <h1 className="text-xl font-bold text-slate-800">{MOCK_COURSE.title}</h1>
            <div className="mt-2 flex items-center gap-3">
              <div className="h-2 w-48 bg-gray-100 rounded-full overflow-hidden">
                <div 
                  className="h-full bg-gradient-to-r from-green-500 to-emerald-400 transition-all duration-500"
                  style={{ width: `${progressPercentage}%` }}
                />
              </div>
              <span className="text-xs text-gray-500 font-medium">{progressPercentage}% Complete</span>
            </div>
          </div>
          
          <div className="flex gap-3">
            <button className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-colors">
              <Info size={16} />
              <span className="hidden sm:inline">Course Info</span>
            </button>
            <button className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
              <LayoutDashboard size={16} />
              <span className="hidden sm:inline">Dashboard</span>
            </button>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
          
          {/* --- Left Sidebar (Lesson List) --- */}
          <div className="lg:col-span-3">
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden sticky top-24">
              <div className="p-4 border-b border-gray-100 bg-gray-50/50">
                <h3 className="font-semibold text-gray-900">Course Content</h3>
                <p className="text-xs text-gray-500 mt-1">{lessons.length} lessons • {lessons.reduce((a,b) => a + b.duration, 0)} mins total</p>
              </div>
              <div className="max-h-[calc(100vh-300px)] overflow-y-auto">
                {lessons.map((lesson, idx) => (
                  <button
                    key={lesson.id}
                    onClick={() => setCurrentLessonId(lesson.id)}
                    className={`w-full flex items-start gap-3 p-4 text-left transition-colors border-l-4 ${
                      currentLessonId === lesson.id 
                        ? 'bg-blue-50 border-blue-600' 
                        : 'border-transparent hover:bg-gray-50'
                    }`}
                  >
                    <div className="mt-0.5">
                      {getIcon(lesson.type, lesson.status)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className={`text-sm font-medium truncate ${
                        currentLessonId === lesson.id ? 'text-blue-900' : 'text-gray-700'
                      }`}>
                        {idx + 1}. {lesson.title}
                      </p>
                      <div className="flex items-center gap-2 mt-1">
                        <span className="text-xs text-gray-400 flex items-center gap-1 capitalize">
                          {lesson.type}
                        </span>
                        <span className="text-gray-300">•</span>
                        <span className="text-xs text-gray-400">{lesson.duration} min</span>
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* --- Main Content Area --- */}
          <div className="lg:col-span-6">
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 min-h-[600px] flex flex-col">
              
              {/* Navigation Bar */}
              <div className="p-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/30">
                <button 
                  onClick={() => handleNavigate('prev')}
                  disabled={currentIndex === 0}
                  className="flex items-center gap-1 text-sm text-gray-600 hover:text-blue-600 disabled:opacity-30 disabled:hover:text-gray-600 transition-colors"
                >
                  <ChevronLeft size={16} /> Previous
                </button>
                <button 
                  onClick={() => handleNavigate('next')}
                  disabled={currentIndex === lessons.length - 1}
                  className="flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-700 disabled:opacity-30 disabled:hover:text-blue-600 transition-colors"
                >
                  Next <ChevronRight size={16} />
                </button>
              </div>

              {/* Content Body */}
              <div className="p-6 sm:p-8 flex-1">
                <h2 className="text-2xl font-bold text-slate-900 mb-2">{currentLesson.title}</h2>
                <p className="text-gray-500 mb-6">{currentLesson.description}</p>

                {/* --- Dynamic Content Rendering based on Type --- */}
                <div className="mb-8">
                  {currentLesson.type === 'video' && currentLesson.videoUrl && (
                    <div className="aspect-video bg-black rounded-lg overflow-hidden shadow-lg">
                      <iframe 
                        src={getEmbedUrl(currentLesson.videoUrl)} 
                        className="w-full h-full"
                        allowFullScreen
                        title={currentLesson.title}
                      />
                    </div>
                  )}

                  {currentLesson.type === 'text' && (
                    <div 
                      className="prose prose-slate max-w-none bg-gray-50 p-6 rounded-lg border border-gray-100"
                      dangerouslySetInnerHTML={{ __html: currentLesson.content || '' }} 
                    />
                  )}

                  {currentLesson.type === 'quiz' && (
                    <div className="bg-blue-50 border border-blue-100 rounded-lg p-8 text-center">
                      <div className="w-16 h-16 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                        <HelpCircle size={32} />
                      </div>
                      <h3 className="text-lg font-semibold text-blue-900 mb-2">Quiz Time!</h3>
                      <p className="text-blue-700 mb-6">This module contains a quiz to test your understanding. You need 80% to pass.</p>
                      <button className="bg-blue-600 text-white px-6 py-2.5 rounded-lg hover:bg-blue-700 transition-colors font-medium inline-flex items-center gap-2">
                        <Play size={16} /> Start Quiz
                      </button>
                    </div>
                  )}

                  {currentLesson.type === 'assignment' && (
                    <div className="bg-amber-50 border border-amber-100 rounded-lg p-8 text-center">
                      <div className="w-16 h-16 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-4">
                        <PenTool size={32} />
                      </div>
                      <h3 className="text-lg font-semibold text-amber-900 mb-2">Assignment Required</h3>
                      <p className="text-amber-700 mb-6">Please upload your project files to complete this lesson.</p>
                      <button 
                        onClick={() => setShowAssignmentModal(true)}
                        className="bg-amber-600 text-white px-6 py-2.5 rounded-lg hover:bg-amber-700 transition-colors font-medium inline-flex items-center gap-2"
                      >
                        <Upload size={16} /> Submit Assignment
                      </button>
                    </div>
                  )}
                </div>
              </div>

              {/* Lesson Footer Actions */}
              <div className="p-6 bg-gray-50 border-t border-gray-100 flex items-center justify-between">
                <button 
                  onClick={handleMarkComplete}
                  disabled={currentLesson.status === 'completed'}
                  className={`flex items-center gap-2 px-6 py-2.5 rounded-lg font-medium transition-all ${
                    currentLesson.status === 'completed'
                      ? 'bg-green-100 text-green-700 cursor-default'
                      : 'bg-green-600 text-white hover:bg-green-700 shadow-sm'
                  }`}
                >
                  <CheckCircle size={18} />
                  {currentLesson.status === 'completed' ? 'Completed' : 'Mark as Complete'}
                </button>

                <button 
                  onClick={() => setShowNotes(!showNotes)}
                  className="flex items-center gap-2 px-4 py-2.5 text-gray-700 hover:bg-white hover:shadow-sm rounded-lg transition-all border border-transparent hover:border-gray-200"
                >
                  <StickyNote size={18} />
                  <span className="hidden sm:inline">Notes</span>
                </button>
              </div>
            </div>
          </div>

          {/* --- Right Sidebar (Progress & Notes) --- */}
          <div className="lg:col-span-3">
            <div className="sticky top-24 space-y-6">
              
              {/* Notes Panel (Conditionally visible on mobile/desktop based on preference, here always visible but toggleable in mobile view usually) */}
              <div className={`bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden transition-all ${showNotes ? 'ring-2 ring-blue-500' : ''}`}>
                <div className="p-4 border-b border-gray-100 bg-yellow-50/50 flex justify-between items-center">
                  <h4 className="font-semibold text-gray-900 flex items-center gap-2">
                    <StickyNote size={16} className="text-yellow-600" />
                    My Notes
                  </h4>
                  {currentLesson.userNotes && <span className="text-xs bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded-full">Saved</span>}
                </div>
                <div className="p-4">
                  <textarea 
                    value={tempNote}
                    onChange={(e) => setTempNote(e.target.value)}
                    className="w-full h-40 p-3 text-sm text-gray-700 bg-yellow-50/20 border border-gray-200 rounded-lg focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 resize-none"
                    placeholder="Type your notes for this lesson here..."
                  />
                  <button 
                    onClick={handleSaveNote}
                    className="mt-3 w-full py-2 bg-gray-900 text-white text-xs font-medium rounded-lg hover:bg-gray-800 transition-colors"
                  >
                    Save Note
                  </button>
                </div>
              </div>

              {/* Stats Panel */}
              <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                <h4 className="font-semibold text-gray-900 mb-4">Your Progress</h4>
                
                <div className="grid grid-cols-2 gap-4 mb-6">
                  <div className="text-center p-3 bg-blue-50 rounded-lg">
                    <span className="block text-xl font-bold text-blue-600">{completedCount}/{lessons.length}</span>
                    <span className="text-xs text-blue-600/80">Lessons</span>
                  </div>
                  <div className="text-center p-3 bg-purple-50 rounded-lg">
                    <span className="block text-xl font-bold text-purple-600">{totalTimeSpent}m</span>
                    <span className="text-xs text-purple-600/80">Time Spent</span>
                  </div>
                </div>

                <div className="space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-green-500"></div>
                      <span className="text-gray-600">Completed</span>
                    </div>
                    <span className="font-medium text-gray-900">{completedCount}</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-blue-500"></div>
                      <span className="text-gray-600">In Progress</span>
                    </div>
                    <span className="font-medium text-gray-900">{lessons.filter(l => l.status === 'in_progress').length}</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-gray-300"></div>
                      <span className="text-gray-600">Not Started</span>
                    </div>
                    <span className="font-medium text-gray-900">{lessons.filter(l => l.status === 'not_started').length}</span>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>

      {/* --- Assignment Modal --- */}
      {showAssignmentModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-xl shadow-2xl max-w-lg w-full overflow-hidden animate-in fade-in zoom-in duration-200">
            <div className="p-4 border-b border-gray-100 flex justify-between items-center">
              <h5 className="font-semibold text-lg">Submit Assignment</h5>
              <button 
                onClick={() => setShowAssignmentModal(false)}
                className="text-gray-400 hover:text-gray-600"
              >
                <X size={20} />
              </button>
            </div>
            <div className="p-6">
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">Submission Text</label>
                <textarea 
                  className="w-full border border-gray-300 rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                  rows={4}
                  placeholder="Describe your submission..."
                ></textarea>
              </div>
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-1">Attachment</label>
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:bg-gray-50 transition-colors cursor-pointer">
                  <Upload className="mx-auto text-gray-400 mb-2" size={24} />
                  <p className="text-xs text-gray-500">Click or drag files to upload</p>
                </div>
              </div>
              <div className="flex justify-end gap-3">
                <button 
                  onClick={() => setShowAssignmentModal(false)}
                  className="px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 rounded-lg"
                >
                  Cancel
                </button>
                <button 
                  onClick={() => {
                    setShowAssignmentModal(false);
                    handleMarkComplete();
                    alert("Assignment submitted!");
                  }}
                  className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg"
                >
                  Submit Assignment
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}