"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";

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

interface GymSelectorProps {
  currentGymId?: string;
  userRole: string;
}

export function GymSelector({ userRole }: GymSelectorProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [gyms, setGyms] = useState<Gym[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Only fetch gyms for superAdmin
    if (userRole !== "superAdmin") {
      setLoading(false);
      return;
    }

    async function fetchGyms() {
      try {
        const response = await fetch("/api/gyms");
        const data = await response.json();

        // API returns array directly
        if (Array.isArray(data)) {
          setGyms(data);
        }
      } catch (error) {
        console.error("Failed to fetch gyms:", error);
      } finally {
        setLoading(false);
      }
    }

    fetchGyms();
  }, [userRole]);

  const handleGymChange = (gymId: string) => {
    const params = new URLSearchParams(searchParams.toString());

    if (gymId === "all") {
      params.delete("gymId");
    } else {
      params.set("gymId", gymId);
    }

    router.push(`?${params.toString()}`);
  };

  // Only show for superAdmin
  if (userRole !== "superAdmin") {
    return null;
  }

  const selectedGymId = searchParams.get("gymId") ?? "all";

  if (loading) {
    return (
      <div className="flex items-center gap-2">
        <div className="h-9 w-40 animate-pulse rounded-md bg-muted" />
      </div>
    );
  }

  return (
    <div className="flex items-center gap-2">
      <select
        value={selectedGymId}
        onChange={(e) => handleGymChange(e.target.value)}
        className="h-9 rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
      >
        <option value="all">All Gyms</option>
        {gyms.map((gym) => (
          <option key={gym.id} value={gym.id}>
            {gym.name}
          </option>
        ))}
      </select>
    </div>
  );
}
