"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { getCourseImage, getCourseGradient } from "@/lib/placeholder-image";
import { Button } from "@/components/ui/button";

interface CourseFile {
  id: string;
  title: string;
  type: string;
  filePath: string;
  fileSize: number | null;
  section: string | null;
}

interface Registration {
  id: string;
  status: string;
  createdAt: string;
  course: {
    id: string;
    title: string;
    slug: string;
    type: string;
    status: string;
    image?: string;
    surveyTemplateId: string | null;
    sport: { name: string };
  };
}

export default function AthleteCourses() {
  const router = useRouter();
  const [registrations, setRegistrations] = useState<Registration[]>([]);
  const [activeFiles, setActiveFiles] = useState<{ courseSlug: string; courseTitle: string; files: CourseFile[] } | null>(null);
  const [loadingFiles, setLoadingFiles] = useState(false);

  useEffect(() => {
    fetch("/api/registrations", {
      headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
    })
      .then((r) => r.json())
      .then(setRegistrations)
      .catch(() => {});
  }, []);

  const loadFiles = async (slug: string, title: string) => {
    setLoadingFiles(true);
    try {
      const res = await fetch(`/api/courses/${slug}/files`, {
        headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
      });
      if (!res.ok) throw new Error();
      const files = await res.json();
      setActiveFiles({ courseSlug: slug, courseTitle: title, files });
    } catch {
      setActiveFiles({ courseSlug: slug, courseTitle: title, files: [] });
    } finally {
      setLoadingFiles(false);
    }
  };

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

      {registrations.length === 0 ? (
        <div className="text-center py-12 bg-white rounded-xl border">
          <p className="text-gray-500 mb-4">هنوز در دوره‌ای ثبت‌نام نکرده‌اید</p>
          <Link href="/courses" className="text-[#2563EB] hover:underline text-sm">
            مشاهده دوره‌ها
          </Link>
        </div>
      ) : (
        <div className="grid gap-4">
          {registrations.map((reg) => {
            const c = reg.course;
            const imgSrc = getCourseImage(c);
            const gradient = getCourseGradient(c.id);
            return (
              <div key={reg.id} className="rounded-xl border bg-white overflow-hidden hover:border-[#2563EB]/30 hover:shadow-md transition-all">
                <div className="flex flex-col sm:flex-row">
                  <div className="sm:w-48 aspect-video sm:aspect-auto bg-gray-100 relative overflow-hidden shrink-0">
                    {imgSrc ? (
                      <img src={imgSrc} alt="" className="w-full h-full object-cover" />
                    ) : (
                      <div className={`w-full h-full bg-gradient-to-br ${gradient} flex items-center justify-center`}>
                        <span className="text-white/80 text-3xl font-bold">{c.title.charAt(0)}</span>
                      </div>
                    )}
                  </div>
                  <div className="p-5 flex-1 flex items-center justify-between">
                    <div>
                      <Link href={`/dashboard/athlete/courses/${c.slug}`} className="font-semibold text-gray-900 hover:text-[#2563EB] transition-colors">
                        {c.title}
                      </Link>
                      <div className="flex items-center gap-2 text-xs text-gray-500 mt-1.5">
                        <span className="bg-blue-50 text-[#2563EB] px-2 py-0.5 rounded">{c.sport.name}</span>
                        <span>{c.type === "ONLINE" ? "آنلاین" : c.type === "IN_PERSON" ? "حضوری" : "ترکیبی"}</span>
                      </div>
                    </div>
                    <div className="text-left shrink-0 flex items-center gap-2">
                      <Button
                        size="xs"
                        variant="outline"
                        onClick={() => loadFiles(c.slug, c.title)}
                      >
                        فایل‌ها
                      </Button>
                      {reg.status === "COMPLETED" && c.status === "COMPLETED" && c.surveyTemplateId && (
                        <Button
                          size="xs"
                          variant="outline"
                          onClick={() => router.push(`/courses/${c.slug}/survey`)}
                        >
                          نظرسنجی
                        </Button>
                      )}
                      <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${
                        reg.status === "CONFIRMED" ? "bg-green-50 text-green-700" :
                        reg.status === "COMPLETED" ? "bg-blue-50 text-blue-700" :
                        reg.status === "CANCELLED" ? "bg-red-50 text-red-700" :
                        "bg-amber-50 text-amber-700"
                      }`}>
                        {reg.status === "PENDING" ? "در انتظار" :
                         reg.status === "CONFIRMED" ? "تأیید شده" :
                         reg.status === "COMPLETED" ? "تکمیل شده" :
                         reg.status === "CANCELLED" ? "لغو شده" : reg.status}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Files Modal */}
      {activeFiles && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={() => setActiveFiles(null)}>
          <div className="bg-white rounded-2xl w-full max-w-lg mx-4 max-h-[80vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <div className="sticky top-0 bg-white border-b px-6 py-4 flex items-center justify-between rounded-t-2xl">
              <h3 className="font-bold text-gray-900">فایل‌های {activeFiles.courseTitle}</h3>
              <button onClick={() => setActiveFiles(null)} className="text-gray-400 hover:text-gray-600 text-xl leading-none">&times;</button>
            </div>
            <div className="p-6">
              {loadingFiles ? (
                <p className="text-gray-500 text-center py-8">در حال بارگذاری...</p>
              ) : activeFiles.files.length === 0 ? (
                <p className="text-gray-500 text-center py-8">هیچ فایلی برای این دوره موجود نیست</p>
              ) : (
                <div className="space-y-2">
                  {activeFiles.files.map((file) => (
                    <a
                      key={file.id}
                      href={file.filePath}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center justify-between p-3 rounded-lg border hover:border-[#2563EB] transition-colors group"
                    >
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center shrink-0">
                          <svg className="h-4 w-4 text-[#2563EB]" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
                        </div>
                        <div className="min-w-0">
                          <div className="font-medium text-sm text-gray-900 truncate group-hover:text-[#2563EB]">{file.title}</div>
                          <div className="text-xs text-gray-500">
                            {file.type.toUpperCase()}
                            {file.fileSize && ` - ${(file.fileSize / 1024).toFixed(0)} KB`}
                          </div>
                        </div>
                      </div>
                      <svg className="h-4 w-4 text-gray-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>
                    </a>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
