"use client";

import { useEffect, useState } from "react";
import Link from "next/link";

interface Student {
  id: string;
  status: string;
  createdAt: string;
  user: {
    id: string;
    phone: string;
    fullName?: string;
    profile?: { fullName?: string | null } | null;
  };
}

interface CourseGroup {
  courseId: string;
  courseTitle: string;
  courseSlug: string;
  students: Student[];
}

export default function CoachStudents() {
  const [groups, setGroups] = useState<CourseGroup[]>([]);

  useEffect(() => {
    fetch("/api/registrations", {
      headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
    })
      .then((r) => r.json())
      .then((data) => {
        const raw = Array.isArray(data) ? data : [];
        const map = new Map<string, CourseGroup>();
        raw.forEach((r: any) => {
          const courseId = r.course?.id || r.courseId;
          const courseTitle = r.course?.title || "بدون عنوان";
          const courseSlug = r.course?.slug || "";
          if (!map.has(courseId)) {
            map.set(courseId, { courseId, courseTitle, courseSlug, students: [] });
          }
          map.get(courseId)!.students.push({
            id: r.id,
            status: r.status,
            createdAt: r.createdAt,
            user: {
              id: r.user?.id || r.userId,
              phone: r.user?.phone || "",
              fullName: r.user?.fullName,
              profile: r.user?.profile || null,
            },
          });
        });
        setGroups(Array.from(map.values()));
      })
      .catch(() => {});
  }, []);

  const regStatusLabel: Record<string, string> = {
    PENDING: "در انتظار", CONFIRMED: "تأیید شده", COMPLETED: "تکمیل شده", CANCELLED: "لغو شده",
  };
  const regStatusColor: Record<string, string> = {
    PENDING: "bg-amber-50 text-amber-700", CONFIRMED: "bg-green-50 text-green-700",
    COMPLETED: "bg-blue-50 text-blue-700", CANCELLED: "bg-red-50 text-red-700",
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">هنرجویان</h1>

      {groups.length === 0 ? (
        <div className="rounded-xl border bg-white p-12 text-center">
          <p className="text-gray-500">هنرجویی یافت نشد</p>
        </div>
      ) : (
        <div className="space-y-8">
          {groups.map((group) => (
            <div key={group.courseId} className="rounded-xl border bg-white overflow-hidden">
              <div className="bg-gray-50 px-5 py-3 border-b flex items-center justify-between">
                <h2 className="font-semibold text-gray-900">
                  {group.courseTitle}
                </h2>
                <span className="text-xs text-gray-500">{group.students.length} هنرجو</span>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="text-gray-600">
                    <tr>
                      <th className="text-right p-3 font-medium">نام</th>
                      <th className="text-right p-3 font-medium">موبایل</th>
                      <th className="text-right p-3 font-medium">وضعیت</th>
                      <th className="text-right p-3 font-medium">تاریخ ثبت‌نام</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {group.students.map((s) => (
                      <tr key={s.id}>
                        <td className="p-3 font-medium text-gray-900">
                          {s.user.fullName || s.user.profile?.fullName || "---"}
                        </td>
                        <td className="p-3 text-gray-500" dir="ltr">{s.user.phone}</td>
                        <td className="p-3">
                          <span className={`text-xs px-2 py-0.5 rounded-full ${regStatusColor[s.status]}`}>
                            {regStatusLabel[s.status]}
                          </span>
                        </td>
                        <td className="p-3 text-gray-500">{new Date(s.createdAt).toLocaleDateString("fa-IR")}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
