"use client";

import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { showToast } from "@/lib/toast";

export default function AdminCoursesPage() {
  const [courses, setCourses] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [query, setQuery] = useState("");
  const [deletingId, setDeletingId] = useState<string | null>(null);

  useEffect(() => {
    const ctrl = new AbortController();
    (async () => {
      setLoading(true);
      try {
        const res = await fetch("/api/courses", { signal: ctrl.signal });
        if (!res.ok) throw new Error(`Gagal memuat (${res.status})`);
        const json = await res.json();
        const arr = Array.isArray(json?.data) ? json.data : (Array.isArray(json) ? json : []);
        setCourses(arr);
      } catch (e: any) {
        showToast(e?.message || "Gagal memuat daftar kursus", "error");
      } finally {
        setLoading(false);
      }
    })();
    return () => ctrl.abort();
  }, []);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return courses;
    return courses.filter((c) =>
      [c.title, c.description, c.instructor]
        .filter(Boolean)
        .some((v: string) => String(v).toLowerCase().includes(q))
    );
  }, [courses, query]);

  async function handleDelete(id: string) {
    if (!id) return;
    const ok = window.confirm("Hapus kursus ini? Tindakan tidak dapat dibatalkan.");
    if (!ok) return;
    setDeletingId(id);
    try {
      const res = await fetch(`/api/courses/${encodeURIComponent(id)}`, {
        method: "DELETE",
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) {
        const msg = data?.error || "Gagal menghapus (endpoint belum tersedia)";
        showToast(String(msg), "error");
        throw new Error(msg);
      }
      showToast("Kursus berhasil dihapus", "success");
      setCourses((prev) => prev.filter((c) => String(c.id) !== String(id)));
    } catch (e: any) {
      // noop; toast already shown
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-2xl font-bold text-gray-900">Kursus</h1>
        <Link
          href="/admin/courses/create"
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Tambah Kursus
        </Link>
      </div>

      <div className="mb-4">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Cari judul, deskripsi, atau instruktur..."
          className="w-full max-w-md px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>

      {loading && <div className="p-4 bg-white border rounded-lg">Memuat...</div>}

      {!loading && filtered.length === 0 && (
        <div className="p-6 bg-white border rounded-lg text-gray-600">Tidak ada kursus.</div>
      )}

      {!loading && filtered.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filtered.map((course) => (
            <div key={course.id} className="bg-white border rounded-xl p-4 shadow-sm">
              <div className="flex items-center justify-between">
                <Link href={`/admin/courses/${course.id}`} className="text-lg font-semibold text-gray-900 hover:underline">
                  {course.title}
                </Link>
                <span className="text-xs px-2 py-1 rounded bg-gray-100 text-gray-700">
                  {course.status || "not_started"}
                </span>
              </div>
              <p className="text-gray-600 mt-1 text-sm line-clamp-2">{course.description}</p>
              <div className="mt-2 text-sm text-gray-700">Instruktur: {course.instructor || "-"}</div>
              <div className="mt-3 flex items-center justify-end gap-2">
                <Link
                  href={`/admin/courses/${course.id}/edit`
                  }
                  className="px-3 py-1 text-sm bg-gray-100 text-gray-800 rounded hover:bg-gray-200"
                >
                  Edit
                </Link>
                <button
                  onClick={() => handleDelete(course.id)}
                  disabled={deletingId === String(course.id)}
                  className="px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-60"
                >
                  {deletingId === String(course.id) ? "Menghapus..." : "Hapus"}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}