"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Calendar, MapPin, Users, Loader2, CheckCircle } from "lucide-react";

interface Sport {
  id: string;
  name: string;
}

interface Registration {
  userId: string;
  status: string;
}

interface Competition {
  id: string;
  title: string;
  description: string;
  sport: Sport;
  type: string;
  location: string;
  startDate: string;
  endDate: string;
  capacity: number;
  price: number;
  status: string;
  image?: string;
  registrations: Registration[];
  _count: { registrations: number };
}

function getUserIdFromToken(): string | null {
  const token = localStorage.getItem("auth_token");
  if (!token) return null;
  try {
    const payload = JSON.parse(atob(token));
    return payload.id;
  } catch {
    return null;
  }
}

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 default function AthleteCompetitions() {
  const router = useRouter();
  const [competitions, setCompetitions] = useState<Competition[]>([]);
  const [loading, setLoading] = useState(true);
  const [registering, setRegistering] = useState<string | null>(null);
  const userId = getUserIdFromToken();

  const fetchCompetitions = async () => {
    try {
      const res = await fetch("/api/competitions", {
        headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
      });
      if (res.ok) setCompetitions(await res.json());
    } catch {
      /* ignore */
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCompetitions();
  }, []);

  const isRegistered = (competition: Competition) =>
    competition.registrations?.some((r) => r.userId === userId);

  const handleRegister = async (competitionId: string) => {
    setRegistering(competitionId);
    try {
      const res = await fetch(`/api/competitions/${competitionId}/register`, {
        method: "POST",
        headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        alert(err.message || "خطا در ثبت‌نام");
        return;
      }
      await fetchCompetitions();
    } catch {
      alert("خطا در ثبت‌نام");
    } finally {
      setRegistering(null);
    }
  };

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

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">مسابقات</h1>

      {competitions.length === 0 ? (
        <div className="text-center py-12 bg-white rounded-xl border">
          <p className="text-gray-500">هیچ مسابقه‌ای یافت نشد</p>
        </div>
      ) : (
        <div className="grid gap-4">
          {competitions.map((c) => {
            const registered = isRegistered(c);
            return (
              <div
                key={c.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">
                  {c.image && (
                    <div className="sm:w-48 aspect-video sm:aspect-auto bg-gray-100 shrink-0">
                      <img
                        src={c.image}
                        alt=""
                        className="w-full h-full object-cover"
                      />
                    </div>
                  )}
                  <div className="p-5 flex-1 flex flex-col justify-between gap-4">
                    <div>
                      <h3 className="font-semibold text-gray-900">{c.title}</h3>
                      {c.description && (
                        <p className="text-sm text-gray-500 mt-1 line-clamp-2">
                          {c.description}
                        </p>
                      )}
                      <div className="flex flex-wrap items-center gap-3 mt-3 text-xs text-gray-500">
                        <span className="bg-blue-50 text-[#2563EB] px-2 py-0.5 rounded">
                          {c.sport?.name}
                        </span>
                        <span
                          className={`text-xs px-2 py-0.5 rounded-full ${
                            statusColors[c.status] || "bg-gray-100 text-gray-600"
                          }`}
                        >
                          {statusLabels[c.status] || c.status}
                        </span>
                        {c.location && (
                          <span className="flex items-center gap-1">
                            <MapPin className="h-3 w-3" />
                            {c.location}
                          </span>
                        )}
                        {c.startDate && (
                          <span className="flex items-center gap-1">
                            <Calendar className="h-3 w-3" />
                            {new Date(c.startDate).toLocaleDateString("fa-IR")}
                          </span>
                        )}
                        <span className="flex items-center gap-1">
                          <Users className="h-3 w-3" />
                          {c._count?.registrations ?? 0}
                          {c.capacity > 0 && ` / ${c.capacity}`}
                        </span>
                      </div>
                    </div>
                    <div className="flex items-center justify-between">
                      {c.price > 0 && (
                        <span className="text-sm font-medium text-gray-700">
                           {c.price.toLocaleString()} ریال
                        </span>
                      )}
                      {c.price === 0 && (
                        <span className="text-sm text-green-600 font-medium">
                          رایگان
                        </span>
                      )}
                      <div>
                        {registered ? (
                          <span className="inline-flex items-center gap-1 text-xs bg-green-50 text-green-700 px-3 py-1.5 rounded-full font-medium">
                            <CheckCircle className="h-3.5 w-3.5" />
                            ثبت‌نام شده
                          </span>
                        ) : (
                          <Button
                            size="xs"
                            className="bg-[#2563EB] hover:bg-[#1D4ED8]"
                            disabled={registering === c.id}
                            onClick={() => handleRegister(c.id)}
                          >
                            {registering === c.id ? (
                              <>
                                <Loader2 className="h-3 w-3 animate-spin ml-1" />
                                ثبت‌نام...
                              </>
                            ) : (
                              "ثبت‌نام"
                            )}
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
