'use client';

import { useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';

import { useUIStore } from '@/stores/ui-store';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { Port } from '@/lib/db/schema/ports';

interface PortSwitcherProps {
  ports: Port[];
}

export function PortSwitcher({ ports }: PortSwitcherProps) {
  const router = useRouter();
  const queryClient = useQueryClient();
  const currentPortId = useUIStore((s) => s.currentPortId);
  const setPort = useUIStore((s) => s.setPort);

  // Hidden when user has access to only one port
  if (ports.length <= 1) return null;

  function handlePortChange(portId: string) {
    const port = ports.find((p) => p.id === portId);
    if (!port) return;

    setPort(port.id, port.slug);

    // Invalidate all cached queries - they are port-scoped
    queryClient.invalidateQueries();

    // Navigate to the selected port's dashboard
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    router.push(`/${port.slug}/dashboard` as any);
  }

  return (
    <Select value={currentPortId ?? undefined} onValueChange={handlePortChange}>
      <SelectTrigger className="w-40 h-8 text-sm">
        <SelectValue placeholder="Select port..." />
      </SelectTrigger>
      <SelectContent>
        {ports.map((port) => (
          <SelectItem key={port.id} value={port.id}>
            {port.name}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
