"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Plus, Edit, Trash2 } from "lucide-react";
import { useAuth } from "@/lib/stores/auth-store";

interface BoardSport {
  id: string;
  sport: { id: string; name: string };
}

interface Board {
  id: string;
  name: string;
  isActive: boolean;
  sports: BoardSport[];
}

export default function AdminBoards() {
  const { user } = useAuth();
  const router = useRouter();
  const [boards, setBoards] = useState<Board[]>([]);

  const load = () => {
    const token = localStorage.getItem("auth_token");
    fetch("/api/admin/boards", {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((data) => { if (Array.isArray(data)) setBoards(data); })
      .catch(() => {});
  };

  useEffect(load, []);

  const handleDelete = async (id: string) => {
    if (!confirm("حذف شود؟")) return;
    const token = localStorage.getItem("auth_token");
    const res = await fetch(`/api/boards/${id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) setBoards((prev) => prev.filter((b) => b.id !== id));
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">مدیریت هیئت‌ها</h1>
        {user?.role === "SUPER_ADMIN" && (
          <Button className="bg-[#2563EB] hover:bg-[#1D4ED8]" onClick={() => router.push("/dashboard/admin/boards/new")}>
            <Plus className="h-4 w-4 ml-1" />
            هیئت جدید
          </Button>
        )}
      </div>

      <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-5 py-3 font-medium text-gray-600">نام هیئت</th>
              <th className="text-right px-5 py-3 font-medium text-gray-600">تعداد رشته‌ها</th>
              <th className="text-right px-5 py-3 font-medium text-gray-600">وضعیت</th>
              <th className="text-left px-5 py-3 font-medium text-gray-600">عملیات</th>
            </tr>
          </thead>
          <tbody>
            {boards.map((board) => (
              <tr key={board.id} className="border-b last:border-0 hover:bg-gray-50/50">
                <td className="px-5 py-4 font-medium text-gray-900">{board.name}</td>
                <td className="px-5 py-4 text-gray-600">{board.sports.length}</td>
                <td className="px-5 py-4">
                  <span className={`text-xs px-2 py-0.5 rounded-full ${board.isActive ? "bg-green-50 text-green-700" : "bg-gray-100 text-gray-600"}`}>
                    {board.isActive ? "فعال" : "غیرفعال"}
                  </span>
                </td>
                <td className="px-5 py-4">
                  <div className="flex items-center gap-2 justify-end">
                    <Button variant="ghost" size="icon-xs" onClick={() => router.push(`/dashboard/admin/boards/${board.id}`)}>
                      <Edit className="h-3.5 w-3.5" />
                    </Button>
                    {user?.role === "SUPER_ADMIN" && (
                      <Button variant="ghost" size="icon-xs" onClick={() => handleDelete(board.id)}>
                        <Trash2 className="h-3.5 w-3.5 text-red-500" />
                      </Button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {boards.length === 0 && (
        <div className="text-center py-12 bg-white rounded-xl border mt-4">
          <p className="text-gray-500">هیئتی تعریف نشده است</p>
        </div>
      )}
    </div>
  );
}
