'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { 
  ChevronLeftIcon, 
  PlayIcon, 
  ClockIcon, 
  UserIcon,
  CheckCircleIcon,
  LockClosedIcon,
  BookOpenIcon,
  DocumentTextIcon,
  AcademicCapIcon
} from '@heroicons/react/24/outline';
import DashboardLayout from '@/layouts/DashboardLayout';
import { cn } from '@/utils/cn';

// Removed fallback dummy courseData per retrospective

const colorClasses = {
  pink: 'from-pink-400 to-pink-600',
  blue: 'from-blue-400 to-blue-600',
  orange: 'from-orange-400 to-orange-600',
  green: 'from-green-400 to-green-600',
  purple: 'from-purple-400 to-purple-600'
};

interface CourseModule {
  id: string;
  title: string;
  description: string;
  duration: string;
  isUnlocked: boolean;
  isCompleted: boolean;
  progress: number;
  type: string;
  hasQuiz: boolean;
  hasAssignment: boolean;
}

interface CourseDetail {
  id: string;
  title: string;
  description: string;
  instructor: string;
  duration: string;
  totalModules: number;
  completedModules: number;
  progress: number;
  thumbnail: string;
  color: 'pink' | 'blue' | 'orange' | 'green' | 'purple' | string;
  modules: CourseModule[];
}

interface CourseDetailPageProps {
  params: {
    courseId: string;
  };
}

export default function CourseDetailPage({ params }: CourseDetailPageProps) {
  // Fetch detail kursus dari API Next (proxy ke backend)
  const [course, setCourse] = useState<CourseDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const res = await fetch(`/api/courses/${params.courseId}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json();
        const color = json.color === '#FF9800' ? 'orange' : json.color === '#3F51B5' ? 'blue' : 'blue';
        setCourse({ ...json, color });
      } catch (e) {
        setError('Gagal memuat detail kursus');
      } finally {
        setLoading(false);
      }
    })();
  }, [params.courseId]);

  // using fetched course from state
  // Tampilkan loading lebih dulu
  if (loading) {
    return (
      <DashboardLayout>
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-center text-gray-700">Memuat detail kursus...</div>
        </div>
      </DashboardLayout>
    );
  }

  if (!course) {
    return (
      <DashboardLayout>
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-center">
            <h1 className="text-2xl font-bold text-gray-900 mb-2">Course Not Found</h1>
            <p className="text-gray-600 mb-4">The course you're looking for doesn't exist.</p>
            <Link 
              href="/courses" 
              className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              <ChevronLeftIcon className="w-4 h-4 mr-2" />
              Back to Courses
            </Link>
          </div>
        </div>
      </DashboardLayout>
    );
  }

  const getModuleIcon = (module: CourseModule) => {
    if (module.isCompleted) {
      return <CheckCircleIcon className="w-6 h-6 text-green-600" />;
    }
    if (!module.isUnlocked) {
      return <LockClosedIcon className="w-6 h-6 text-gray-400" />;
    }
    return <PlayIcon className="w-6 h-6 text-blue-600" />;
  };

  const getNextModule = (): CourseModule | undefined => {
    return course?.modules?.find((module: CourseModule) => module.isUnlocked && !module.isCompleted);
  };

  const nextModule = getNextModule();

  return (
    <DashboardLayout>
      <div className="p-6">
        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-sm text-gray-600 mb-6">
          <Link href="/courses" className="hover:text-gray-900 transition-colors">
            Kursus Saya
          </Link>
          <span>/</span>
          <span className="text-gray-900 font-medium">{course.title}</span>
        </div>

        {/* Course Header */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden mb-6">
          <div className={cn(
            "h-48 bg-gradient-to-br flex items-center justify-center relative",
            colorClasses[course.color as keyof typeof colorClasses]
          )}>
            <div className="absolute inset-0 bg-black/20" />
            <div className="relative z-10 text-center text-white">
              <BookOpenIcon className="w-16 h-16 mx-auto mb-4" />
              <h1 className="text-2xl font-bold mb-2">{course.title}</h1>
              <p className="text-lg opacity-90">{course.description}</p>
            </div>
          </div>
          
          <div className="p-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
              <div className="flex items-center gap-3">
                <UserIcon className="w-5 h-5 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-600">Instruktur</p>
                  <p className="font-medium text-gray-900">{course.instructor}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <ClockIcon className="w-5 h-5 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-600">Durasi</p>
                  <p className="font-medium text-gray-900">{course.duration}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <DocumentTextIcon className="w-5 h-5 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-600">Modul</p>
                  <p className="font-medium text-gray-900">{course.completedModules}/{course.totalModules} selesai</p>
                </div>
              </div>
            </div>

            {/* Progress Bar */}
            <div className="mb-6">
              <div className="flex items-center justify-between text-sm mb-2">
                <span className="text-gray-600">Progress Keseluruhan</span>
                <span className="font-medium text-gray-900">{course.progress}%</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-3">
                <div 
                  className="bg-gradient-to-r from-blue-500 to-green-500 h-3 rounded-full transition-all duration-500"
                  style={{ width: `${course.progress}%` }}
                />
              </div>
            </div>

            {/* Continue Learning Button */}
            {nextModule && (
              <div className="bg-blue-50 rounded-lg p-4 border border-blue-200">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-blue-900 mb-1">Lanjutkan Belajar</p>
                    <p className="text-sm text-blue-700">{nextModule.title}</p>
                  </div>
                  <Link
                    href={`/course/${course.id}/module/${nextModule.id}`}
                    className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    <PlayIcon className="w-4 h-4 mr-2" />
                    Mulai
                  </Link>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Modules List */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100">
          <div className="p-6 border-b border-gray-200">
            <h2 className="text-xl font-bold text-gray-900 mb-2">Daftar Modul</h2>
            <p className="text-gray-600">Ikuti modul secara berurutan untuk hasil pembelajaran yang optimal</p>
          </div>
          
          <div className="p-6">
            <div className="space-y-4">
              {course.modules.map((module: CourseModule, index: number) => {
                const isClickable = module.isUnlocked;
                
                return (
                  <div key={module.id} className="relative">
                    {/* Connection Line */}
                    {index < course.modules.length - 1 && (
                      <div className="absolute left-8 top-16 w-0.5 h-12 bg-gray-200"></div>
                    )}
                    
                    <div className={cn(
                      "flex items-start gap-4 p-4 rounded-lg border-2 transition-all duration-200",
                      module.isCompleted && "border-green-200 bg-green-50",
                      !module.isCompleted && module.isUnlocked && "border-blue-200 bg-blue-50 hover:border-blue-300",
                      !module.isUnlocked && "border-gray-200 bg-gray-50",
                      isClickable && "cursor-pointer",
                      !isClickable && "cursor-not-allowed"
                    )}>
                      {/* Module Icon */}
                      <div className="flex-shrink-0 mt-1">
                        {getModuleIcon(module)}
                      </div>
                      
                      {/* Module Content */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between mb-2">
                          <div className="flex-1">
                            <h3 className={cn(
                              "font-semibold mb-1",
                              module.isCompleted && "text-green-900",
                              !module.isCompleted && module.isUnlocked && "text-blue-900",
                              !module.isUnlocked && "text-gray-500"
                            )}>
                              {module.title}
                            </h3>
                            <p className={cn(
                              "text-sm mb-2",
                              module.isUnlocked ? "text-gray-600" : "text-gray-400"
                            )}>
                              {module.description}
                            </p>
                          </div>
                          
                          {/* Module Duration */}
                          <div className="flex items-center gap-1 text-sm text-gray-500 ml-4">
                            <ClockIcon className="w-4 h-4" />
                            <span>{module.duration}</span>
                          </div>
                        </div>
                        
                        {/* Module Features */}
                        <div className="flex items-center gap-4 mb-3">
                          {module.hasQuiz && (
                            <div className="flex items-center gap-1 text-xs text-gray-500">
                              <AcademicCapIcon className="w-3 h-3" />
                              <span>Kuis</span>
                            </div>
                          )}
                          {module.hasAssignment && (
                            <div className="flex items-center gap-1 text-xs text-gray-500">
                              <DocumentTextIcon className="w-3 h-3" />
                              <span>Tugas</span>
                            </div>
                          )}
                        </div>
                        
                        {/* Progress Bar for Current Module */}
                        {module.isUnlocked && module.progress > 0 && (
                          <div className="mb-3">
                            <div className="flex items-center justify-between text-xs mb-1">
                              <span className="text-gray-600">Progress</span>
                              <span className="font-medium text-gray-900">{module.progress}%</span>
                            </div>
                            <div className="w-full bg-gray-200 rounded-full h-1.5">
                              <div 
                                className="bg-blue-500 h-1.5 rounded-full transition-all duration-300"
                                style={{ width: `${module.progress}%` }}
                              />
                            </div>
                          </div>
                        )}
                        
                        {/* Action Button */}
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            {module.isCompleted && (
                              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                <CheckCircleIcon className="w-3 h-3 mr-1" />
                                Selesai
                              </span>
                            )}
                            {!module.isUnlocked && (
                              <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                                <LockClosedIcon className="w-3 h-3 mr-1" />
                                Terkunci
                              </span>
                            )}
                          </div>
                          
                          {module.isUnlocked && (
                            <Link
                              href={`/course/${course.id}/module/${module.id}`}
                              className={cn(
                                "inline-flex items-center px-3 py-1.5 rounded-lg text-sm font-medium transition-colors",
                                module.isCompleted 
                                  ? "bg-green-100 text-green-700 hover:bg-green-200"
                                  : "bg-blue-600 text-white hover:bg-blue-700"
                              )}
                            >
                              {module.isCompleted ? 'Tinjau Ulang' : module.progress > 0 ? 'Lanjutkan' : 'Mulai'}
                              <PlayIcon className="w-3 h-3 ml-1" />
                            </Link>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </DashboardLayout>
  );
}