'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Play, Pause, Volume2, VolumeX, Maximize, RotateCcw, RotateCw, BookOpen, MessageCircle, FileText, CheckCircle, Lock, ChevronLeft, ChevronRight, Clock, Users } from 'lucide-react';
import Link from 'next/link';
import { cn } from '@/utils/cn';
import ModuleNavigation, { Course, Module } from '@/components/course/ModuleNavigation';
import { useProgressTracking } from '@/hooks/useProgressTracking';
import ModuleTabs from '@/components/course/ModuleTabs';

// Sample course and module data
const courseData: Course = {
  id: 'haccp-course',
  title: 'HACCP - Hazard Analysis Critical Control Point',
  description: 'Comprehensive course on food safety management system',
  totalModules: 3,
  completedModules: 1,
  totalDuration: '155 menit',
  modules: [
    {
      id: 'module-1',
      title: 'Pengenalan HACCP',
      description: 'Dasar-dasar sistem HACCP dan prinsip-prinsipnya',
      duration: '45 menit',
      isUnlocked: true,
      isCompleted: true,
      progress: 100,
      type: 'video',
      hasQuiz: true
    },
    {
      id: 'module-2',
      title: 'Tindakan Korektif dalam HACCP',
      description: 'Memahami dan menerapkan tindakan korektif yang efektif',
      duration: '60 menit',
      isUnlocked: true,
      isCompleted: false,
      progress: 0,
      type: 'video',
      hasQuiz: true,
      hasAssignment: true
    },
    {
      id: 'module-3',
      title: 'Dokumentasi dan Verifikasi HACCP',
      description: 'Sistem dokumentasi dan verifikasi dalam HACCP',
      duration: '50 menit',
      isUnlocked: false,
      isCompleted: false,
      progress: 0,
      type: 'video',
      hasQuiz: true
    }
  ]
};

const moduleDetails = {
  'module-1': {
    videoUrl: '/videos/haccp-intro.mp4',
    materials: [
      { id: 1, title: 'Slide Presentasi HACCP', type: 'pdf', url: '/materials/haccp-slides.pdf' },
      { id: 2, title: 'Checklist HACCP', type: 'doc', url: '/materials/haccp-checklist.doc' }
    ],
    discussions: [
      { id: 1, author: 'John Doe', message: 'Bagaimana cara mengidentifikasi CCP?', replies: 3, time: '2 jam lalu' },
      { id: 2, author: 'Jane Smith', message: 'Contoh implementasi HACCP di industri makanan', replies: 1, time: '1 hari lalu' }
    ],
    quiz: {
      id: 'quiz-1',
      title: 'Kuis Pengenalan HACCP',
      questions: 10,
      duration: 15,
      attempts: 3
    },
    assignment: {
      id: 'assignment-1',
      title: 'Analisis Bahaya Produk Makanan',
      dueDate: '2024-02-15',
      submitted: false
    }
  },
  'module-2': {
    videoUrl: '/videos/haccp-corrective-actions.mp4',
    materials: [
      { id: 3, title: 'Panduan Tindakan Korektif', type: 'pdf', url: '/materials/corrective-actions.pdf' }
    ],
    discussions: [],
    quiz: {
      id: 'quiz-2',
      title: 'Kuis Tindakan Korektif',
      questions: 8,
      duration: 12,
      attempts: 3
    },
    assignment: {
      id: 'assignment-2',
      title: 'Rencana Tindakan Korektif',
      dueDate: '2024-02-20',
      submitted: false
    }
  },
  'module-3': {
    videoUrl: '/videos/haccp-documentation.mp4',
    materials: [],
    discussions: [],
    quiz: null,
    assignment: null
  }
};

interface ModulePageProps {
  params: {
    courseId: string;
    moduleId: string;
  };
}

export default function ModulePage({ params }: ModulePageProps) {
  const [activeTab, setActiveTab] = useState('materi');
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(1);
  const [playbackRate, setPlaybackRate] = useState(1);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [bookmarks, setBookmarks] = useState<number[]>([]);
  const [currentModuleId, setCurrentModuleId] = useState(params.moduleId);
  
  // Sample data for tabs
  const materials = [
    {
      id: 1,
      title: 'Slide Presentasi HACCP',
      type: 'ppt' as const,
      url: '/materials/haccp-slides.ppt',
      size: '2.5 MB',
      description: 'Materi lengkap tentang sistem HACCP'
    },
    {
      id: 2,
      title: 'Panduan Implementasi HACCP',
      type: 'pdf' as const,
      url: '/materials/haccp-guide.pdf',
      size: '1.8 MB',
      description: 'Panduan step-by-step implementasi HACCP'
    },
    {
      id: 3,
      title: 'Template CCP Worksheet',
      type: 'docx' as const,
      url: '/materials/ccp-worksheet.docx',
      size: '0.5 MB',
      description: 'Template untuk analisis Critical Control Points'
    },
    {
      id: 4,
      title: 'Video Tutorial Tambahan',
      type: 'link' as const,
      url: 'https://youtube.com/watch?v=example',
      description: 'Video tutorial dari channel resmi'
    }
  ];

  const discussions = [
    {
      id: 1,
      author: 'Ahmad Rizki',
      message: 'Bagaimana cara menentukan Critical Control Point yang tepat untuk industri makanan kecil?',
      replies: 3,
      time: '2 jam yang lalu',
      likes: 5,
      isLiked: false
    },
    {
      id: 2,
      author: 'Sari Dewi',
      message: 'Apakah ada template khusus untuk dokumentasi HACCP yang bisa digunakan untuk restoran?',
      replies: 1,
      time: '5 jam yang lalu',
      likes: 2,
      isLiked: true
    }
  ];

  const quiz = {
    id: 'quiz-haccp-1',
    title: 'Kuis Pemahaman HACCP Dasar',
    questions: 15,
    duration: 30,
    attempts: 1,
    maxAttempts: 3,
    passingScore: 70,
    lastScore: 85,
    status: 'passed' as const
  };

  const assignment = {
    id: 'assignment-haccp-1',
    title: 'Analisis HACCP untuk Produk Makanan',
    description: 'Buatlah analisis HACCP lengkap untuk satu produk makanan pilihan Anda, termasuk identifikasi bahaya, penentuan CCP, dan penetapan batas kritis.',
    dueDate: '15 Januari 2024',
    maxScore: 100,
    submitted: false,
    status: 'not_submitted' as const
  };
  
  // Progress tracking
  const progressTracking = useProgressTracking(params.courseId);

  // Find current module
  const currentModule = courseData.modules.find(m => m.id === currentModuleId);
  const currentModuleDetails = moduleDetails[currentModuleId as keyof typeof moduleDetails];
  const currentModuleIndex = courseData.modules.findIndex(m => m.id === currentModuleId);
  const nextModule = courseData.modules[currentModuleIndex + 1];
  const prevModule = courseData.modules[currentModuleIndex - 1];
  
  // Get current module progress
  const moduleProgress = progressTracking.getModuleProgress(currentModuleId);

  if (!currentModule) {
    return <div className="flex items-center justify-center min-h-screen">Module not found</div>;
  }

  const handlePlayPause = () => {
    setIsPlaying(!isPlaying);
  };

  const handleMute = () => {
    setIsMuted(!isMuted);
  };

  const handleVolumeChange = (newVolume: number) => {
    setVolume(newVolume);
    setIsMuted(newVolume === 0);
  };

  const handleSeek = (time: number) => {
    setCurrentTime(time);
  };

  const handlePlaybackRateChange = (rate: number) => {
    setPlaybackRate(rate);
  };

  const handleAddBookmark = () => {
    if (!bookmarks.includes(currentTime)) {
      setBookmarks([...bookmarks, currentTime].sort((a, b) => a - b));
      progressTracking.addBookmark(currentModuleId, `Bookmark ${formatTime(currentTime)}`, currentTime, '');
    }
  };

  const handleQuizStart = (quizId: string) => {
    // Navigate to quiz page
    console.log('Starting quiz:', quizId);
  };

  const handleAssignmentSubmit = (assignmentId: string, files: File[]) => {
    // Handle assignment submission
    console.log('Submitting assignment:', assignmentId, files);
  };

  const handleDiscussionPost = (message: string) => {
    // Handle new discussion post
    console.log('New discussion:', message);
  };

  const handleDiscussionReply = (discussionId: string | number, message: string) => {
    // Handle discussion reply
    console.log('Reply to discussion:', discussionId, message);
  };

  const handleDiscussionLike = (discussionId: string | number) => {
    // Handle discussion like
    console.log('Like discussion:', discussionId);
  };

  const handleRemoveBookmark = (time: number) => {
    setBookmarks(bookmarks.filter(b => b !== time));
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };
  
  // Handle module completion
  const handleModuleComplete = () => {
    progressTracking.completeModule(currentModuleId);
  };
  
  const router = useRouter();
  
  // Handle module navigation
  const handleModuleSelect = (moduleId: string) => {
    router.push(`/course/${params.courseId}/module/${moduleId}`);
  };
  
  // Track video progress
  const handleProgressUpdate = (progress: number) => {
    progressTracking.updateModuleProgress(currentModuleId, progress);
  };

  const tabs = [
    { id: 'materi', label: 'Materi', icon: BookOpen },
    { id: 'diskusi', label: 'Diskusi', icon: MessageCircle },
    { id: 'kuis', label: 'Kuis', icon: FileText },
    { id: 'tugas', label: 'Tugas', icon: CheckCircle }
  ];

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link href={`/course/${params.courseId}`} className="text-gray-600 hover:text-gray-800">
                <ChevronLeft className="w-6 h-6" />
              </Link>
              <div>
                <h1 className="text-xl font-bold text-gray-900">{currentModule.title}</h1>
                <p className="text-sm text-gray-600">{courseData.title}</p>
              </div>
            </div>
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <Clock className="w-4 h-4" />
                <span>{currentModule.duration}</span>
              </div>
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <Users className="w-4 h-4" />
                <span>1,234 peserta</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-6 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Sidebar - Module Navigation */}
          <div className="lg:col-span-1 order-2 lg:order-1">
            <ModuleNavigation 
              course={courseData}
              currentModuleId={currentModuleId}
              onModuleSelect={handleModuleSelect}
            />
          </div>
          
          {/* Main Content */}
          <div className="lg:col-span-3 order-1 lg:order-2">
            {/* Video Player */}
            <div className="bg-black rounded-xl overflow-hidden mb-6 relative group">
              <div className="aspect-video relative">
                {/* Video placeholder */}
                <div className="w-full h-full bg-gradient-to-br from-gray-800 to-gray-900 flex items-center justify-center">
                  <div className="text-center text-white">
                    <div className="w-20 h-20 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4">
                      {isPlaying ? <Pause className="w-8 h-8" /> : <Play className="w-8 h-8 ml-1" />}
                    </div>
                    <p className="text-lg font-medium">{currentModule.title}</p>
                    <p className="text-gray-300">{currentModule.description}</p>
                    {moduleProgress && (
                      <div className="mt-4">
                        <div className="w-64 bg-white/20 rounded-full h-2 mx-auto">
                          <div 
                            className="bg-blue-500 h-2 rounded-full" 
                            style={{ width: `${moduleProgress.progress}%` }}
                          />
                        </div>
                        <p className="text-sm text-gray-300 mt-2">{Math.round(moduleProgress.progress)}% selesai</p>
                      </div>
                    )}
                  </div>
                </div>

                {/* Video Controls Overlay */}
                <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                  <div className="absolute inset-0 flex items-center justify-center">
                    <button
                      onClick={handlePlayPause}
                      className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center hover:bg-white/30 transition-colors"
                    >
                      {isPlaying ? <Pause className="w-8 h-8 text-white" /> : <Play className="w-8 h-8 text-white ml-1" />}
                    </button>
                  </div>
                </div>

                {/* Video Controls Bar */}
                <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                  {/* Progress Bar */}
                  <div className="mb-4">
                    <div className="w-full bg-white/20 rounded-full h-1 mb-2">
                      <div 
                        className="bg-blue-500 h-1 rounded-full relative"
                        style={{ width: `${duration > 0 ? (currentTime / duration) * 100 : 0}%` }}
                      >
                        <div className="absolute right-0 top-1/2 transform -translate-y-1/2 w-3 h-3 bg-blue-500 rounded-full"></div>
                      </div>
                    </div>
                    {/* Bookmarks */}
                    <div className="relative">
                      {bookmarks.map((bookmark, index) => (
                        <div
                          key={index}
                          className="absolute w-2 h-2 bg-yellow-400 rounded-full transform -translate-x-1/2 cursor-pointer"
                          style={{ left: `${duration > 0 ? (bookmark / duration) * 100 : 0}%`, top: '-6px' }}
                          onClick={() => handleSeek(bookmark)}
                          title={`Bookmark: ${formatTime(bookmark)}`}
                        />
                      ))}
                    </div>
                  </div>

                  {/* Controls */}
                  <div className="flex items-center justify-between text-white">
                    <div className="flex items-center gap-4">
                      <button onClick={handlePlayPause} className="hover:text-blue-400 transition-colors">
                        {isPlaying ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
                      </button>
                      
                      <div className="flex items-center gap-2">
                        <button onClick={handleMute} className="hover:text-blue-400 transition-colors">
                          {isMuted || volume === 0 ? <VolumeX className="w-5 h-5" /> : <Volume2 className="w-5 h-5" />}
                        </button>
                        <input
                          type="range"
                          min="0"
                          max="1"
                          step="0.1"
                          value={isMuted ? 0 : volume}
                          onChange={(e) => handleVolumeChange(parseFloat(e.target.value))}
                          className="w-20 h-1 bg-white/20 rounded-lg appearance-none cursor-pointer"
                        />
                      </div>

                      <span className="text-sm">
                        {formatTime(currentTime)} / {formatTime(duration)}
                      </span>
                    </div>

                    <div className="flex items-center gap-4">
                      <button
                        onClick={handleAddBookmark}
                        className="text-yellow-400 hover:text-yellow-300 transition-colors"
                        title="Add Bookmark"
                      >
                        <BookOpen className="w-5 h-5" />
                      </button>

                      <select
                        value={playbackRate}
                        onChange={(e) => handlePlaybackRateChange(parseFloat(e.target.value))}
                        className="bg-white/20 text-white text-sm rounded px-2 py-1 border-none outline-none"
                      >
                        <option value={0.5}>0.5x</option>
                        <option value={0.75}>0.75x</option>
                        <option value={1}>1x</option>
                        <option value={1.25}>1.25x</option>
                        <option value={1.5}>1.5x</option>
                        <option value={2}>2x</option>
                      </select>

                      <button
                        onClick={() => setIsFullscreen(!isFullscreen)}
                        className="hover:text-blue-400 transition-colors"
                      >
                        <Maximize className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Module Tabs */}
            <div className="mt-8">
              <ModuleTabs
                materials={materials}
                discussions={discussions}
                quiz={quiz}
                assignment={assignment}
                onQuizStart={handleQuizStart}
                onAssignmentSubmit={handleAssignmentSubmit}
                onDiscussionPost={handleDiscussionPost}
                onDiscussionReply={handleDiscussionReply}
                onDiscussionLike={handleDiscussionLike}
              />
            </div>

            {/* Navigation */}
            <div className="flex items-center justify-between mt-6">
              <div>
                {prevModule && (
                  <button
                    onClick={() => handleModuleSelect(prevModule.id)}
                    className="flex items-center gap-2 px-6 py-3 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
                  >
                    <ChevronLeft className="w-4 h-4" />
                    {prevModule.title}
                  </button>
                )}
              </div>
              <div className="flex gap-2">
                {moduleProgress && moduleProgress.progress >= 80 && (
                  <button 
                    onClick={handleModuleComplete}
                    className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                  >
                    Tandai Selesai
                  </button>
                )}
                {nextModule && nextModule.isUnlocked && (
                  <button
                    onClick={() => handleModuleSelect(nextModule.id)}
                    className="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    {nextModule.title}
                    <ChevronRight className="w-4 h-4" />
                  </button>
                )}
                {nextModule && !nextModule.isUnlocked && (
                  <div className="flex items-center gap-2 px-6 py-3 bg-gray-100 text-gray-400 rounded-lg cursor-not-allowed">
                    <Lock className="w-4 h-4" />
                    {nextModule.title}
                  </div>
                )}
              </div>
            </div>
          </div>


        </div>
      </div>
    </div>
  );
}