"use client";

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import CourseForm, { CourseFormValues } from '@/components/admin/CourseForm';
import { showToast } from '@/lib/toast';

export default function AdminCourseEditPage() {
  const params = useParams() as { id: string };
  const courseId = params?.id;
  const router = useRouter();
  const [initial, setInitial] = useState<CourseFormValues | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const ctrl = new AbortController();
    (async () => {
      setLoading(true);
      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();
        setInitial({
          title: String(json?.title ?? ''),
          description: json?.description ?? '',
          instructor: json?.instructor ?? '',
          duration: json?.duration ?? '',
          thumbnail: json?.thumbnail ?? '',
          color: json?.color ?? '#3F51B5',
          status: json?.status ?? 'not_started',
        });
      } catch (e: any) {
        showToast(e?.message || 'Gagal memuat data kursus', 'error');
      } 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">Edit Kursus</h1>
          <p className="text-gray-600">ID: {courseId}</p>
        </div>
        <Link href={`/admin/courses/${courseId}`} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200">Kembali</Link>
      </div>
      {loading && <div className="p-4 bg-white border rounded-lg">Memuat data kursus...</div>}
      {!loading && initial && (
        <CourseForm mode="edit" courseId={courseId} initial={initial} onDone={() => setTimeout(() => router.push(`/admin/courses/${courseId}`), 600)} />
      )}
    </div>
  );
}