'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';

type CourseDetail = {
  id: string;
  title: string;
  description?: string;
  instructor?: string;
  modules?: Array<{ id: string; title: string; locked?: boolean; completed?: boolean }>;
  progress?: number;
};

export default function AdminCourseDetailPage() {
  const params = useParams() as { id: string };
  const courseId = params?.id;

  const [course, setCourse] = useState<CourseDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const ctrl = new AbortController();
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await fetch(`/api/courses/${encodeURIComponent(courseId)}`, { signal: ctrl.signal });
        if (!res.ok) throw new Error(`Gagal memuat (${res.status})`);
        const json = await res.json();
        setCourse({
          id: String(json?.id ?? courseId),
          title: String(json?.title ?? 'Tanpa Judul'),
          description: json?.description ?? '',
          instructor: json?.instructor ?? '',
          modules: Array.isArray(json?.modules) ? json.modules.map((m: any) => ({
            id: String(m?.id ?? ''),
            title: String(m?.title ?? 'Untitled'),
            locked: !!m?.locked,
            completed: !!m?.completed,
          })) : [],
          progress: Number(json?.progress ?? 0),
        });
      } catch (e: any) {
        setError(e?.message || 'Gagal memuat detail kursus');
      } finally {
        setLoading(false);
      }
    })();
    return () => ctrl.abort();
  }, [courseId]);

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Detail Kursus</h1>
          <p className="text-gray-600">ID: {courseId}</p>
        </div>
        <div className="flex gap-2">
          <Link href={`/admin/courses/${courseId}/edit`} className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Edit</Link>
          <Link href="/admin/courses" className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200">Kembali</Link>
        </div>
      </div>

      {loading && <div className="p-4 bg-white border rounded-lg">Memuat detail kursus...</div>}
      {error && <div className="p-4 bg-red-50 text-red-700 border border-red-200 rounded-lg">{error}</div>}

      {course && !loading && !error && (
        <div className="space-y-6">
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 className="text-xl font-semibold text-gray-900 mb-2">{course.title}</h2>
            {course.description && <p className="text-gray-700 mb-2">{course.description}</p>}
            <p className="text-sm text-gray-600">Instruktur: {course.instructor || '-'}</p>
            <p className="text-sm text-gray-600">Progress: {course.progress ?? 0}%</p>
          </div>

          <div className="bg-white rounded-xl shadow-sm border border-gray-100">
            <div className="p-4 border-b">
              <h3 className="text-lg font-semibold text-gray-900">Modul</h3>
            </div>
            <ul className="divide-y">
              {course.modules?.length ? course.modules.map((m) => (
                <li key={m.id} className="p-4 flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-900">{m.title}</div>
                    <div className="text-xs text-gray-500">{m.locked ? 'Terkunci' : m.completed ? 'Selesai' : 'Belum'}</div>
                  </div>
                  <Link href={`/course/${course.id}?module=${m.id}`} className="text-sm px-3 py-1.5 bg-gray-100 text-gray-700 rounded hover:bg-gray-200">
                    Buka di halaman kursus
                  </Link>
                </li>
              )) : (
                <li className="p-4 text-gray-600">Tidak ada modul</li>
              )}
            </ul>
          </div>
        </div>
      )}
    </div>
  );
}