"use client";

import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/lib/stores/auth-store";
import { getCourseImage, getCourseGradient } from "@/lib/placeholder-image";
import {
  CalendarDays,
  MapPin,
  Users,
  Clock,
  ExternalLink,
  BookOpen,
  Video,
  UserCheck,
} from "lucide-react";
import type { Course } from "@/lib/types";

export function CourseDetailClient({ course }: { course: Course }) {
  const { isAuthenticated } = useAuth();
  const router = useRouter();

  const imgSrc = getCourseImage(course);
  const gradient = getCourseGradient(course.id);

  const handleRegister = () => {
    if (!isAuthenticated) {
      router.push("/auth");
      return;
    }
    router.push(`/checkout/${course.id}`);
  };

  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];

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="grid lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-8">
          <div>
            <div className="flex items-center gap-2 mb-3">
              <Link href="/courses" className="text-sm text-[#2563EB] hover:underline">
                دوره‌ها
              </Link>
              <span className="text-gray-300">/</span>
              <span className="text-sm text-gray-500">{course.sport.name}</span>
            </div>

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

            <div className="flex flex-wrap items-center gap-3 mb-4">
              <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${statusColor[course.status]}`}>
                {statusLabel[course.status]}
              </span>
              <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>
            </div>

            {course.description && (
              <p className="text-gray-600 leading-relaxed">{course.description}</p>
            )}
          </div>

          {mainCoach && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <UserCheck className="h-5 w-5 text-[#2563EB]" />
                مدرس دوره
              </h2>
              <Link href={`/coaches/${(mainCoach.coach as any).id}`} className="block p-4 rounded-xl border bg-white hover:border-[#2563EB]/30 hover:shadow-md transition-all group">
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 rounded-full bg-gradient-to-br from-blue-500 to-cyan-400 flex items-center justify-center text-white font-bold text-lg">
                    {mainCoach.coach.profile?.fullName?.charAt(0) || "?"}
                  </div>
                  <div>
                    <div className="font-semibold text-gray-900 group-hover:text-[#2563EB] transition-colors">
                      {mainCoach.coach.profile
                        ? mainCoach.coach.profile.fullName || "مربی"
                        : "مربی"}
                    </div>
                    {mainCoach.coach.coachSports?.[0] && (
                      <div className="text-sm text-gray-500">
                        {mainCoach.coach.coachSports[0].sport.name}
                        {mainCoach.coach.coachSports[0].coachLevel &&
                          ` - ${mainCoach.coach.coachSports[0].coachLevel}`}
                      </div>
                    )}
                  </div>
                </div>
              </Link>
            </div>
          )}
        </div>

        <div className="lg:col-span-1">
          <div className="sticky top-24 space-y-4">
            <div className={`aspect-video rounded-xl overflow-hidden bg-gradient-to-br ${gradient} flex flex-col items-center justify-center gap-1`}>
              <span className="text-white/90 text-4xl font-bold">{course.title.charAt(0)}</span>
              <span className="text-white/60 text-xs">{course.sport.name}</span>
            </div>

            <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">
                <div className="flex items-center gap-2 text-gray-600">
                  <CalendarDays className="h-4 w-4 text-gray-400" />
                  <span>شروع: {course.startDate ? 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" />
                    <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" />
                    <span>{course.location}</span>
                  </div>
                )}
                <div className="flex items-center gap-2 text-gray-600">
                  <Users className="h-4 w-4 text-gray-400" />
                  <span>ظرفیت: {course.capacity} نفر</span>
                </div>
                <div className="flex items-center gap-2 text-gray-600">
                  <BookOpen className="h-4 w-4 text-gray-400" />
                  <span>{course._count.registrations} ثبت‌نام</span>
                </div>
              </div>

              <div className="pt-4 border-t space-y-2">
                <Button
                  className="w-full bg-[#2563EB] hover:bg-[#1D4ED8]"
                  onClick={handleRegister}
                  disabled={course.status !== "ACTIVE"}
                >
                  ثبت‌نام در دوره
                </Button>
                {course.onlineLink && (
                  <a href={course.onlineLink} target="_blank" rel="noopener noreferrer">
                    <Button variant="outline" className="w-full flex items-center gap-1">
                      <Video className="h-4 w-4" />
                      ورود به کلاس آنلاین
                      <ExternalLink className="h-3.5 w-3.5" />
                    </Button>
                  </a>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
