"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import {
  ArrowLeft,
  CalendarDays,
  MapPin,
  Users,
  Clock,
  ExternalLink,
  Video,
  UserCheck,
  FileText,
  Save,
  Loader2,
  GraduationCap,
} from "lucide-react";

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

interface CoachProfile {
  id: string;
  profile?: { fullName?: string | null } | null;
  coachSports?: { id: string; sport: { id: string; name: string }; coachLevel?: string }[];
}

interface CourseCoach {
  id: string;
  isMain: boolean;
  coach: CoachProfile;
}

interface Course {
  id: string;
  title: string;
  slug: string;
  description?: string;
  sport: { id: string; name: string };
  type: string;
  status: string;
  price: string;
  capacity: number;
  startDate?: string | null;
  endDate?: string | null;
  location?: string | null;
  onlineLink?: string | null;
  image?: string | null;
  surveyTemplateId: string | null;
  coaches: CourseCoach[];
  _count: { registrations: number; files: number };
}

export default function CoachCourseDetail() {
  const { slug } = useParams<{ slug: string }>();
  const router = useRouter();
  const [course, setCourse] = useState<Course | null>(null);
  const [students, setStudents] = useState<Student[]>([]);
  const [onlineLink, setOnlineLink] = useState("");
  const [description, setDescription] = useState("");
  const [location, setLocation] = useState("");
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState("");
  const [evaluations, setEvaluations] = useState<Record<string, { score: string; comment: string }>>({});
  const [grading, setGrading] = useState(false);
  const [gradeMessage, setGradeMessage] = useState("");

  const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null;

  useEffect(() => {
    (async () => {
      const [courseRes, regsRes] = await Promise.all([
        fetch(`/api/courses/${slug}`, { headers: { Authorization: `Bearer ${token}` } }),
        fetch("/api/registrations", { headers: { Authorization: `Bearer ${token}` } }),
      ]);
      if (courseRes.ok) {
        const c: Course = await courseRes.json();
        setCourse(c);
        setOnlineLink(c.onlineLink || "");
        setDescription(c.description || "");
        setLocation(c.location || "");
      }
      if (regsRes.ok) {
        const data = await regsRes.json();
        const mapped: Student[] = (Array.isArray(data) ? data : []).map((r: any) => ({
          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,
          },
        }));
        setStudents(mapped);
      }
      setLoading(false);
    })();
  }, [slug]);

  useEffect(() => {
    if (!course || course.status !== "COMPLETED") return;
    (async () => {
      const res = await fetch(`/api/evaluations?courseId=${course.id}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        const map: Record<string, { score: string; comment: string }> = {};
        for (const ev of data) {
          map[ev.userId] = {
            score: ev.score != null ? String(ev.score) : "",
            comment: ev.comment || "",
          };
        }
        setEvaluations(map);
      }
    })();
  }, [course]);

  const handleSave = async () => {
    if (!course) return;
    setSaving(true);
    setMessage("");
    const res = await fetch(`/api/courses/${course.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({
        onlineLink: onlineLink || null,
        description: description || null,
        location: location || null,
      }),
    });
    setSaving(false);
    if (res.ok) {
      setMessage("تغییرات ذخیره شد");
      setTimeout(() => setMessage(""), 3000);
    } else {
      setMessage("خطا در ذخیره");
    }
  };

  const handleGradeSave = async () => {
    if (!course) return;
    setGrading(true);
    setGradeMessage("");
    const evals = students
      .filter((s) => s.user.id)
      .map((s) => ({
        userId: s.user.id,
        score: evaluations[s.user.id]?.score ? parseInt(evaluations[s.user.id].score) : null,
        comment: evaluations[s.user.id]?.comment || null,
      }));
    const res = await fetch("/api/evaluations", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({ courseId: course.id, evaluations: evals }),
    });
    setGrading(false);
    if (res.ok) {
      setGradeMessage("نمرات ذخیره شد");
      setTimeout(() => setGradeMessage(""), 3000);
    } else {
      const data = await res.json().catch(() => ({}));
      setGradeMessage(data.error || "خطا در ذخیره نمرات");
    }
  };

  if (loading) {
    return <div className="flex items-center justify-center h-64"><Loader2 className="h-6 w-6 animate-spin text-gray-400" /></div>;
  }

  if (!course) {
    return <div className="text-center py-12 text-gray-500">دوره یافت نشد</div>;
  }

  const typeLabel = course.type === "ONLINE" ? "آنلاین" : course.type === "IN_PERSON" ? "حضوری" : "ترکیبی";
  const statusLabel: Record<string, string> = { DRAFT: "پیش‌نویس", ACTIVE: "فعال", COMPLETED: "تکمیل شده", CANCELLED: "لغو شده" };
  const statusColor: Record<string, string> = {
    ACTIVE: "bg-green-50 text-green-700", DRAFT: "bg-gray-100 text-gray-600",
    COMPLETED: "bg-blue-50 text-blue-700", CANCELLED: "bg-red-50 text-red-700",
  };

  const mainCoach = course.coaches.find((c) => c.isMain) || course.coaches[0];
  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>
      <button
        onClick={() => router.push("/dashboard/coach/courses")}
        className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-900 mb-4 transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        بازگشت به دوره‌های من
      </button>

      <div className="grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          {/* Course Info */}
          <div className="rounded-xl border bg-white p-6">
            <div className="flex items-center gap-2 mb-3">
              <span className="text-xs bg-blue-50 text-[#2563EB] px-2.5 py-1 rounded-full">{course.sport.name}</span>
              <span className="text-xs bg-gray-100 text-gray-600 px-2.5 py-1 rounded-full">{typeLabel}</span>
              <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${statusColor[course.status]}`}>
                {statusLabel[course.status]}
              </span>
            </div>

            <h1 className="text-2xl font-bold text-gray-900 mb-4">{course.title}</h1>

            <div className="grid gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">توضیحات دوره</label>
                <textarea
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB] min-h-[80px]"
                  rows={3}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">لینک کلاس آنلاین</label>
                <input
                  value={onlineLink}
                  onChange={(e) => setOnlineLink(e.target.value)}
                  placeholder="https://meet.google.com/..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">مکان برگزاری</label>
                <input
                  value={location}
                  onChange={(e) => setLocation(e.target.value)}
                  placeholder="آدرس..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
                />
              </div>

              <div className="flex items-center gap-3 pt-2">
                <Button className="bg-[#2563EB] hover:bg-[#1D4ED8]" onClick={handleSave} disabled={saving}>
                  {saving ? <Loader2 className="h-4 w-4 animate-spin ml-1" /> : <Save className="h-4 w-4 ml-1" />}
                  ذخیره تغییرات
                </Button>
                {message && (
                  <span className={`text-sm ${message.includes("خطا") ? "text-red-600" : "text-green-600"}`}>
                    {message}
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* Students */}
          <div className="rounded-xl border bg-white p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <Users className="h-5 w-5 text-[#2563EB]" />
              هنرجویان ({students.length})
            </h2>

            {students.length === 0 ? (
              <p className="text-gray-500 text-center py-6">هنرجویی ثبت‌نام نکرده است</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 text-gray-600">
                    <tr>
                      <th className="text-right p-2 font-medium">نام</th>
                      <th className="text-right p-2 font-medium">موبایل</th>
                      <th className="text-right p-2 font-medium">وضعیت</th>
                      <th className="text-right p-2 font-medium">تاریخ ثبت‌نام</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {students.map((s) => (
                      <tr key={s.id}>
                        <td className="p-2 font-medium text-gray-900">
                          {s.user.fullName || s.user.profile?.fullName || "---"}
                        </td>
                        <td className="p-2 text-gray-500" dir="ltr">{s.user.phone}</td>
                        <td className="p-2">
                          <span className={`text-xs px-2 py-0.5 rounded-full ${regStatusColor[s.status]}`}>
                            {regStatusLabel[s.status]}
                          </span>
                        </td>
                        <td className="p-2 text-gray-500">{new Date(s.createdAt).toLocaleDateString("fa-IR")}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* Grading - only for COMPLETED courses */}
          {course.status === "COMPLETED" && students.length > 0 && (
            <div className="rounded-xl border bg-white p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <GraduationCap className="h-5 w-5 text-[#2563EB]" />
                نمره‌دهی
              </h2>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 text-gray-600">
                    <tr>
                      <th className="text-right p-2 font-medium w-12">ردیف</th>
                      <th className="text-right p-2 font-medium">نام ورزشکار</th>
                      <th className="text-right p-2 font-medium w-28">نمره</th>
                      <th className="text-right p-2 font-medium">توضیحات</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {students.map((s, i) => (
                      <tr key={s.id} className="hover:bg-gray-50">
                        <td className="p-2 text-gray-500 text-center">{i + 1}</td>
                        <td className="p-2 font-medium text-gray-900">
                          {s.user.fullName || s.user.profile?.fullName || "---"}
                        </td>
                        <td className="p-2">
                          <input
                            type="number"
                            min={0}
                            max={100}
                            value={evaluations[s.user.id]?.score || ""}
                            onChange={(e) =>
                              setEvaluations((prev) => ({
                                ...prev,
                                [s.user.id]: { ...prev[s.user.id], score: e.target.value, comment: prev[s.user.id]?.comment || "" },
                              }))
                            }
                            placeholder="0-100"
                            className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-center focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
                          />
                        </td>
                        <td className="p-2">
                          <input
                            type="text"
                            value={evaluations[s.user.id]?.comment || ""}
                            onChange={(e) =>
                              setEvaluations((prev) => ({
                                ...prev,
                                [s.user.id]: { ...prev[s.user.id], comment: e.target.value, score: prev[s.user.id]?.score || "" },
                              }))
                            }
                            placeholder="توضیحات اختیاری"
                            className="w-full px-2 py-1.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <div className="flex items-center gap-3 mt-4 pt-4 border-t">
                <Button className="bg-[#2563EB] hover:bg-[#1D4ED8]" onClick={handleGradeSave} disabled={grading}>
                  {grading ? <Loader2 className="h-4 w-4 animate-spin ml-1" /> : <Save className="h-4 w-4 ml-1" />}
                  ذخیره نمرات
                </Button>
                {gradeMessage && (
                  <span className={`text-sm ${gradeMessage.includes("خطا") ? "text-red-600" : "text-green-600"}`}>
                    {gradeMessage}
                  </span>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Sidebar */}
        <div className="lg:col-span-1">
          <div className="sticky top-24 space-y-4">
            <div className="rounded-xl border bg-white p-5 space-y-4">
              <div className="text-center pb-4 border-b">
                <div className="text-2xl font-bold text-[#2563EB]">{Number(course.price).toLocaleString()} ریال</div>
              </div>

              <div className="space-y-3 text-sm">
                {course.onlineLink && (
                  <a href={course.onlineLink} target="_blank" rel="noopener noreferrer">
                    <Button className="w-full bg-[#2563EB] hover:bg-[#1D4ED8] flex items-center gap-2">
                      <Video className="h-4 w-4" />
                      ورود به کلاس آنلاین
                      <ExternalLink className="h-3.5 w-3.5" />
                    </Button>
                  </a>
                )}

                <div className="pt-4 border-t space-y-2">
                  {course.startDate && (
                    <div className="flex items-center gap-2 text-gray-600">
                      <CalendarDays className="h-4 w-4 text-gray-400 shrink-0" />
                      <span>شروع: {new Date(course.startDate).toLocaleDateString("fa-IR")}</span>
                    </div>
                  )}
                  {course.endDate && (
                    <div className="flex items-center gap-2 text-gray-600">
                      <Clock className="h-4 w-4 text-gray-400 shrink-0" />
                      <span>پایان: {new Date(course.endDate).toLocaleDateString("fa-IR")}</span>
                    </div>
                  )}
                  {course.location && (
                    <div className="flex items-center gap-2 text-gray-600">
                      <MapPin className="h-4 w-4 text-gray-400 shrink-0" />
                      <span>{course.location}</span>
                    </div>
                  )}
                  <div className="flex items-center gap-2 text-gray-600">
                    <Users className="h-4 w-4 text-gray-400 shrink-0" />
                    <span>ظرفیت: {course.capacity} نفر</span>
                  </div>
                </div>
              </div>
            </div>

            {mainCoach && (
              <div className="rounded-xl border bg-white p-4">
                <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                  <UserCheck className="h-4 w-4 text-[#2563EB]" />
                  مدرس دوره
                </h3>
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-cyan-400 flex items-center justify-center text-white font-bold shrink-0">
                    {mainCoach.coach.profile?.fullName?.charAt(0) || "?"}
                  </div>
                  <div className="text-sm font-medium text-gray-900">
                    {mainCoach.coach.profile?.fullName || "مربی"}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
