"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/lib/stores/auth-store";
import { getCourseGradient } from "@/lib/placeholder-image";
import {
  CalendarDays,
  MapPin,
  Users,
  Clock,
  Medal,
  Loader2,
  CheckCircle,
  Trophy,
  User,
} from "lucide-react";
import type { CompetitionDetail } from "./page";

const statusLabels: Record<string, string> = {
  UPCOMING: "پیش‌رو",
  REGISTERING: "ثبت‌نام",
  ONGOING: "درحال برگزاری",
  FINISHED: "تمام شده",
  CANCELLED: "لغو شده",
};

const statusColors: Record<string, string> = {
  UPCOMING: "bg-blue-50 text-blue-700",
  REGISTERING: "bg-amber-50 text-amber-700",
  ONGOING: "bg-green-50 text-green-700",
  FINISHED: "bg-gray-100 text-gray-600",
  CANCELLED: "bg-red-50 text-red-700",
};

export function CompetitionDetailClient({ competition }: { competition: CompetitionDetail }) {
  const router = useRouter();
  const { isAuthenticated } = useAuth();
  const [registering, setRegistering] = useState(false);
  const [registered, setRegistered] = useState(false);

  const gradient = getCourseGradient(competition.id);

  const sortedRegistrations = [...competition.registrations]
    .sort((a, b) => (a.rank ?? 999) - (b.rank ?? 999));

  const hasRanking = competition.status === "FINISHED" && sortedRegistrations.some((r) => r.score != null);

  const handleRegister = async () => {
    if (!isAuthenticated) {
      router.push("/auth");
      return;
    }
    setRegistering(true);
    try {
      const token = localStorage.getItem("auth_token");
      const res = await fetch(`/api/competitions/${competition.id}/register`, {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        alert(err.error || "خطا در ثبت‌نام");
        return;
      }
      setRegistered(true);
    } catch {
      alert("خطا در ثبت‌نام");
    } finally {
      setRegistering(false);
    }
  };

  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="/competitions" className="text-sm text-[#2563EB] hover:underline">
                مسابقات
              </Link>
              <span className="text-gray-300">/</span>
              <span className="text-sm text-gray-500">{competition.sport.name}</span>
            </div>

            <h1 className="text-2xl md:text-3xl font-bold text-gray-900 mb-3">
              {competition.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 ${statusColors[competition.status]}`}>
                {statusLabels[competition.status]}
              </span>
              <span className="text-xs bg-blue-50 text-[#2563EB] px-2.5 py-1 rounded-full">
                {competition.sport.name}
              </span>
              <span className="text-xs bg-gray-100 text-gray-600 px-2.5 py-1 rounded-full">
                {competition.type === "ONLINE" ? "آنلاین" : "حضوری"}
              </span>
            </div>

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

          {competition.judge && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <Medal className="h-5 w-5 text-[#2563EB]" />
                داور مسابقه
              </h2>
              <div className="flex items-center gap-4 p-4 rounded-xl border bg-white">
                <div className="w-14 h-14 rounded-full bg-gradient-to-br from-amber-500 to-orange-400 flex items-center justify-center text-white font-bold text-lg">
                  {competition.judge.profile?.fullName?.charAt(0) || "?"}
                </div>
                <div>
                  <div className="font-semibold text-gray-900">
                    {competition.judge.profile?.fullName || "داور"}
                  </div>
                  <div className="text-sm text-gray-500">{competition.judge.phone}</div>
                </div>
              </div>
            </div>
          )}

          {hasRanking && (
            <div>
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <Trophy className="h-5 w-5 text-amber-500" />
                رتبه‌بندی نهایی
              </h2>
              <div className="rounded-xl border bg-white overflow-hidden">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-gray-50">
                      <th className="text-right px-4 py-3 font-medium text-gray-600 w-12">#</th>
                      <th className="text-right px-4 py-3 font-medium text-gray-600">ورزشکار</th>
                      <th className="text-center px-4 py-3 font-medium text-gray-600 w-24">امتیاز</th>
                    </tr>
                  </thead>
                  <tbody>
                    {sortedRegistrations
                      .filter((r) => r.score != null)
                      .map((r, i) => (
                        <tr key={r.id} className="border-b last:border-0 hover:bg-gray-50 transition-colors">
                          <td className="px-4 py-3">
                            {r.rank ? (
                              <span className={`inline-flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${
                                r.rank === 1
                                  ? "bg-amber-100 text-amber-700"
                                  : r.rank === 2
                                  ? "bg-gray-100 text-gray-600"
                                  : r.rank === 3
                                  ? "bg-orange-100 text-orange-700"
                                  : "bg-gray-50 text-gray-500"
                              }`}>
                                {r.rank}
                              </span>
                            ) : (
                              <span className="text-gray-400">{i + 1}</span>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-3">
                              <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-cyan-400 flex items-center justify-center text-white text-xs font-bold">
                                {r.user.profile?.fullName?.charAt(0) || <User className="h-4 w-4" />}
                              </div>
                              <span className="font-medium text-gray-900">
                                {r.user.profile?.fullName || r.user.phone}
                              </span>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-center">
                            <span className="font-bold text-[#2563EB]">{r.score}</span>
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            </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`}>
              <Medal className="text-white/80 h-10 w-10" />
              <span className="text-white/60 text-xs">{competition.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(competition.price) > 0
                    ? `${Number(competition.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>شروع: {competition.startDate ? new Date(competition.startDate).toLocaleDateString("fa-IR") : "اعلام می‌شود"}</span>
                </div>
                {competition.endDate && (
                  <div className="flex items-center gap-2 text-gray-600">
                    <Clock className="h-4 w-4 text-gray-400" />
                    <span>پایان: {new Date(competition.endDate).toLocaleDateString("fa-IR")}</span>
                  </div>
                )}
                {competition.location && (
                  <div className="flex items-center gap-2 text-gray-600">
                    <MapPin className="h-4 w-4 text-gray-400" />
                    <span>{competition.location}</span>
                  </div>
                )}
                <div className="flex items-center gap-2 text-gray-600">
                  <Users className="h-4 w-4 text-gray-400" />
                  <span>ظرفیت: {competition.capacity || "نامحدود"} نفر</span>
                </div>
                <div className="flex items-center gap-2 text-gray-600">
                  <Medal className="h-4 w-4 text-gray-400" />
                  <span>{competition._count.registrations} ثبت‌نام</span>
                </div>
              </div>

              {competition.status === "REGISTERING" && (
                <div className="pt-4 border-t space-y-2">
                  {registered ? (
                    <div className="flex items-center justify-center gap-2 text-sm bg-green-50 text-green-700 px-4 py-2.5 rounded-lg font-medium">
                      <CheckCircle className="h-4 w-4" />
                      ثبت‌نام با موفقیت انجام شد
                    </div>
                  ) : (
                    <Button
                      className="w-full bg-[#2563EB] hover:bg-[#1D4ED8] h-11"
                      onClick={handleRegister}
                      disabled={registering}
                    >
                      {registering ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin ml-2" />
                          ثبت‌نام...
                        </>
                      ) : (
                        "ثبت‌نام در مسابقه"
                      )}
                    </Button>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
