'use client';

import Link from 'next/link';
import DashboardLayout from '@/layouts/DashboardLayout';
import { BookOpenIcon, ClockIcon, UserIcon } from '@heroicons/react/24/outline';
import { cn } from '@/utils/cn';
import { useEffect, useState } from 'react';

// Removed fallback dummy courses dataset per retrospective

const statusColors = {
  'Wajib': 'bg-red-100 text-red-800',
  'Berlangsung': 'bg-blue-100 text-blue-800',
  'Baru': 'bg-green-100 text-green-800',
  'Selesai': 'bg-gray-100 text-gray-800'
};

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'
};

export default function CoursesPage() {
  const [courseList, setCourseList] = useState<UiCourse[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const res = await fetch('/api/courses?page=1&limit=20');
        const json = await res.json();
        const mapped = Array.isArray(json.data) ? json.data.map(toUiCourse) : [];
        setCourseList(mapped);
      } catch (e) {
        setError('Gagal memuat data kursus');
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  return (
    <DashboardLayout>
      <div className="p-6">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Kursus Saya</h1>
          <p className="text-gray-600">Kelola dan pantau progress pembelajaran Anda</p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Total Kursus</p>
                <p className="text-2xl font-bold text-gray-900">{courseList.length}</p>
              </div>
              <div className="p-3 bg-blue-100 rounded-lg">
                <BookOpenIcon className="h-6 w-6 text-blue-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Sedang Berjalan</p>
                <p className="text-2xl font-bold text-gray-900">{courseList.filter(c => c.status === 'Berlangsung').length}</p>
              </div>
              <div className="p-3 bg-yellow-100 rounded-lg">
                <ClockIcon className="h-6 w-6 text-yellow-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Selesai</p>
                <p className="text-2xl font-bold text-gray-900">{courseList.filter(c => c.status === 'Selesai').length}</p>
              </div>
              <div className="p-3 bg-green-100 rounded-lg">
                <BookOpenIcon className="h-6 w-6 text-green-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Rata-rata Progress</p>
                <p className="text-2xl font-bold text-gray-900">{Math.round(courseList.length ? courseList.reduce((a, c) => a + c.progress, 0) / courseList.length : 0)}%</p>
              </div>
              <div className="p-3 bg-purple-100 rounded-lg">
                <UserIcon className="h-6 w-6 text-purple-600" />
              </div>
            </div>
          </div>
        </div>

        {/* Courses Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {courseList.map((course) => (
            <div key={course.id} className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-shadow">
              {/* Course Thumbnail */}
              <div className={cn(
                "h-48 bg-gradient-to-br flex items-center justify-center",
                colorClasses[course.color as keyof typeof colorClasses]
              )}>
                <BookOpenIcon className="h-16 w-16 text-white" />
              </div>

              {/* Course Content */}
              <div className="p-6">
                {/* Status Badge */}
                <div className="flex items-center justify-between mb-3">
                  <span className={cn(
                    "px-2 py-1 rounded-full text-xs font-medium",
                    statusColors[course.status as keyof typeof statusColors]
                  )}>
                    {course.status}
                  </span>
                  <span className="text-xs text-gray-500">{course.enrolled}</span>
                </div>

                {/* Course Title */}
                <h3 className="font-semibold text-gray-900 mb-2 line-clamp-2">
                  {course.title}
                </h3>

                {/* Instructor */}
                <p className="text-sm text-gray-600 mb-4 flex items-center">
                  <UserIcon className="h-4 w-4 mr-1" />
                  {course.instructor}
                </p>

                {/* Course Info */}
                <div className="flex items-center justify-between text-sm text-gray-500 mb-4">
                  <span>{course.modules} Modul</span>
                  <span className="flex items-center">
                    <ClockIcon className="h-4 w-4 mr-1" />
                    {course.duration}
                  </span>
                </div>

                {/* Progress Bar */}
                <div className="mb-4">
                  <div className="flex items-center justify-between text-sm mb-1">
                    <span className="text-gray-600">Progress</span>
                    <span className="font-medium text-gray-900">{course.progress}%</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className={cn(
                        "h-2 rounded-full transition-all duration-300",
                        course.progress === 100 ? 'bg-green-500' : 'bg-blue-500'
                      )}
                      style={{ width: `${course.progress}%` }}
                    />
                  </div>
                </div>

                {/* Action Button */}
                <Link 
                  href={`/course/${course.id}`}
                  className={cn(
                    "w-full py-2 px-4 rounded-lg font-medium transition-colors text-center block",
                    course.progress === 100 
                      ? "bg-green-100 text-green-700 hover:bg-green-200"
                      : course.progress > 0
                      ? "bg-blue-600 text-white hover:bg-blue-700"
                      : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                  )}
                >
                  {course.progress === 100 ? 'Lihat Sertifikat' : course.progress > 0 ? 'Lanjutkan' : 'Mulai Belajar'}
                </Link>
              </div>
            </div>
          ))}
        </div>
      </div>
    </DashboardLayout>
  );
}

type UiCourse = {
  id: string;
  title: string;
  instructor: string;
  progress: number;
  status: 'Wajib' | 'Berlangsung' | 'Baru' | 'Selesai';
  color: 'pink' | 'blue' | 'orange' | 'green' | 'purple';
  thumbnail: string;
  duration: string;
  modules: number;
  enrolled: string;
};

function toUiCourse(item: any): UiCourse {
  const status: UiCourse['status'] = item.progress === 100
    ? 'Selesai'
    : item.status === 'in_progress'
    ? 'Berlangsung'
    : 'Baru';
  const color: UiCourse['color'] = item.color === '#FF9800'
    ? 'orange'
    : item.color === '#3F51B5'
    ? 'blue'
    : 'blue';
  const duration = typeof item.duration === 'string' ? item.duration.replace('h', ' jam') : `${item.duration || ''}`;
  return {
    id: item.id,
    title: item.title,
    instructor: item.instructor,
    progress: Number(item.progress || 0),
    status,
    color,
    thumbnail: item.thumbnail || '/api/placeholder/300/200',
    duration,
    modules: Number(item.modules || 0),
    enrolled: item.enrolled || '',
  };
}