import Link from "next/link";
import { Button } from "@/components/ui/button";
import { ChevronLeft, Users, BookOpen, Building2, Phone } from "lucide-react";
import { apiGet } from "@/lib/api/server";
import Image from "next/image";

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

interface BoardMember {
  id: string;
  role: string;
  firstName: string;
  lastName: string;
  position?: string;
  phone?: string;
  email?: string;
}

interface SportItem {
  id: string;
  name: string;
  description?: string;
  boardMembers: BoardMember[];
  boards: { board: BoardRef }[];
  _count?: { courses: number; coachSports: number };
}

interface BoardMemberRef {
  id: string;
  role: string;
  position?: string;
  phone?: string;
  firstName: string;
  lastName: string;
}

interface Board {
  id: string;
  name: string;
  image?: string | null;
  boardMembers?: BoardMemberRef[];
  _count: { sports: number };
}

export default async function SportsPage({
  searchParams,
}: {
  searchParams: Promise<{ boardId?: string }>;
}) {
  const { boardId } = await searchParams;
  const [sports, boards] = await Promise.all([
    apiGet<SportItem[]>(`/api/sports${boardId ? `?boardId=${boardId}` : ""}`).catch(() => []),
    apiGet<Board[]>("/api/boards").catch(() => []),
  ]);

  const currentBoard = boardId ? boards.find((b) => b.id === boardId) : null;

  function getAdminPhone(board: Board): string | null {
    if (!board.boardMembers) return null;
    const admin = board.boardMembers.find(
      (m) =>
        m.role.includes("head") ||
        m.role.includes("secretary") ||
        (m.position && m.position.includes("آموزش"))
    );
    return admin?.phone || null;
  }

  const sportsByBoard = boards.map((b) => ({
    board: b,
    sports: sports.filter((s) => s.boards.some((sb) => sb.board.id === b.id)),
  }));

  const ungroupedSports = boardId
    ? sports
    : sports.filter((s) => s.boards.length === 0);

  return (
    <div>
      <div className="container mx-auto px-4 py-12">
        <div className="mb-10">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">رشته‌های ورزشی</h1>
          <p className="text-gray-500 mb-6">لیست رشته‌های ورزشی به تفکیک هیئت</p>
        </div>

        {/* Sticky Board Cards */}
        <div className="sticky top-0 z-10 bg-white/95 backdrop-blur-sm border-b border-gray-100 -mx-4 px-4 py-4 mb-8">
          <div className="flex gap-3 overflow-x-auto pb-2 scrollbar-hide">
            <Link
              href="/sports"
              className={`shrink-0 flex items-center gap-2 px-5 py-3 rounded-xl text-sm font-medium transition-all border ${
                !boardId
                  ? "bg-[#2563EB] text-white border-[#2563EB] shadow-lg shadow-blue-500/20"
                  : "bg-white text-gray-600 border-gray-200 hover:border-[#2563EB]/30 hover:shadow-md"
              }`}
            >
              <Building2 className="h-4 w-4" />
              همه هیئت‌ها
            </Link>
            {boards.map((b) => {
              const adminPhone = getAdminPhone(b);
              return (
                <Link
                  key={b.id}
                  href={`/sports?boardId=${b.id}`}
                  className={`shrink-0 flex items-center gap-3 px-5 py-3 rounded-xl text-sm font-medium transition-all border ${
                    boardId === b.id
                      ? "bg-[#2563EB] text-white border-[#2563EB] shadow-lg shadow-blue-500/20"
                      : "bg-white text-gray-600 border-gray-200 hover:border-[#2563EB]/30 hover:shadow-md"
                  }`}
                >
                  {b.image ? (
                    <div className="w-8 h-8 rounded-lg overflow-hidden shrink-0 bg-gray-100">
                      <img src={b.image} alt={b.name} className="w-full h-full object-cover" />
                    </div>
                  ) : (
                    <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center text-white text-xs font-bold shrink-0">
                      {b.name.charAt(0)}
                    </div>
                  )}
                  <div className="text-right">
                    <div className="whitespace-nowrap">{b.name}</div>
                    {adminPhone && (
                      <div className={`text-[10px] mt-0.5 flex items-center gap-1 ${boardId === b.id ? "text-blue-200" : "text-gray-400"}`} dir="ltr">
                        <Phone className="h-2.5 w-2.5" />
                        {adminPhone}
                      </div>
                    )}
                  </div>
                </Link>
              );
            })}
          </div>
        </div>

        {currentBoard && (
          <p className="text-sm text-gray-500 mb-6">
            {sports.length} رشته ورزشی در هیئت {currentBoard.name}
          </p>
        )}

        <div className="grid gap-6">
          {boardId
            ? sports.map((sport, index) => (
                <SportCard key={sport.id} sport={sport} index={index} />
              ))
            : sportsByBoard.map(({ board, sports: boardSports }) =>
                boardSports.length > 0 ? (
                  <div key={board.id} id={`board-${board.id}`}>
                    <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                      <Building2 className="h-5 w-5 text-[#2563EB]" />
                      {board.name}
                    </h2>
                    <div className="grid gap-4">
                      {boardSports.map((sport, index) => (
                        <SportCard key={sport.id} sport={sport} index={index} />
                      ))}
                    </div>
                  </div>
                ) : null
              )}
        </div>

        {sports.length === 0 && (
          <div className="text-center py-16 text-gray-500">
            <Building2 className="h-12 w-12 mx-auto mb-3 text-gray-300" />
            <p>رشته ورزشی یافت نشد</p>
          </div>
        )}
      </div>
    </div>
  );
}

function SportCard({ sport, index }: { sport: SportItem; index: number }) {
  const gradients = [
    "from-blue-500 to-cyan-400",
    "from-violet-500 to-purple-400",
    "from-emerald-500 to-teal-400",
    "from-orange-500 to-amber-400",
    "from-rose-500 to-pink-400",
    "from-indigo-500 to-blue-400",
    "from-fuchsia-500 to-pink-400",
    "from-teal-500 to-emerald-400",
  ];
  const g = gradients[index % gradients.length];

  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6 md:p-8 hover:border-[#2563EB]/20 hover:shadow-lg transition-all duration-200">
      <div className="flex items-start justify-between mb-6">
        <div className="flex items-center gap-4">
          <div className={`w-14 h-14 rounded-2xl bg-gradient-to-br ${g} flex items-center justify-center text-white font-bold text-xl shadow-lg`}>
            {sport.name.charAt(0)}
          </div>
          <div>
            <h2 className="text-xl font-bold text-gray-900">{sport.name}</h2>
            <div className="flex items-center gap-3 text-sm text-gray-500 mt-1">
              <span className="flex items-center gap-1">
                <BookOpen className="h-3.5 w-3.5" />
                {sport._count?.courses || 0} دوره
              </span>
              <span className="flex items-center gap-1">
                <Users className="h-3.5 w-3.5" />
                {sport._count?.coachSports || 0} مربی
              </span>
              {sport.boards.length > 0 && (
                <span className="flex items-center gap-1 text-[#2563EB]">
                  <Building2 className="h-3.5 w-3.5" />
                  {sport.boards.map((b) => b.board.name).join("، ")}
                </span>
              )}
            </div>
          </div>
        </div>
        <Link href={`/courses?sportId=${sport.id}`}>
          <Button variant="outline" size="sm" className="hidden sm:flex gap-1">
            دوره‌ها <ChevronLeft className="h-3.5 w-3.5" />
          </Button>
        </Link>
      </div>

      {sport.description && (
        <p className="text-gray-600 text-sm leading-relaxed mb-6">{sport.description}</p>
      )}

      {sport.boardMembers && sport.boardMembers.length > 0 && (
        <div className="pt-6 border-t border-gray-100">
          <h3 className="text-sm font-semibold text-gray-900 mb-4">اعضای هیئت</h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
            {sport.boardMembers.map((member) => (
              <div key={member.id} className="p-4 rounded-xl bg-gradient-to-br from-gray-50 to-white border border-gray-100">
                <div className="text-xs font-medium text-[#2563EB] mb-1.5">
                  {member.role === "head" ? "رئیس" : member.role === "secretary" ? "دبیر" : "مسئول آموزش"}
                </div>
                <div className="font-semibold text-gray-900 text-sm">
                  {member.firstName} {member.lastName}
                </div>
                {member.position && (
                  <div className="text-xs text-gray-500 mt-0.5">{member.position}</div>
                )}
                {member.phone && (
                  <div className="text-xs text-gray-400 mt-2 font-mono" dir="ltr">{member.phone}</div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
