'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import SearchableSelect, { type Option } from '@/components/SearchableSelect';

// Client filter dropdown for the dashboard banner. Picking a client navigates
// to /dashboard?client=<id> (no reload); picking "All Clients (Global)" or
// clearing restores the global dashboard. Renders nothing when the user can't
// list clients (the /clients/ call 403s) or there are none.
interface ClientFilterSelectProps {
  clientId?: string;
  /**
   * Pre-fetched client list. When supplied the component skips its own request
   * — used by dashboards that already load the options as part of a single
   * consolidated call. Omit it and the behaviour is exactly as before.
   */
  clients?: { id: number; name: string }[];
  /**
   * Called with the chosen client id instead of navigating. Lets a dashboard
   * treat the client as an in-place filter; omit it and picking a client still
   * navigates to /dashboard?client=<id> exactly as before.
   */
  onChange?: (clientId: string) => void;
}

export default function ClientFilterSelect({ clientId, clients: providedClients, onChange }: ClientFilterSelectProps) {
  const router = useRouter();
  const [fetched, setFetched] = useState<{ id: number; name: string }[] | null>(null);
  const supplied = providedClients !== undefined;

  useEffect(() => {
    if (supplied) return; // options already provided — no request needed
    api.get('/clients/?page_size=200')
      .then((res: any) => {
        const d = res?.data;
        const list = Array.isArray(d) ? d : Array.isArray(d?.results) ? d.results : Array.isArray(res?.results) ? res.results : [];
        setFetched(list.map((c: any) => ({ id: c.id, name: c.name })));
      })
      .catch(() => setFetched(null));
  }, [supplied]);

  const clients = supplied ? providedClients! : fetched;

  if (!clients || clients.length === 0) return null;

  const options: Option[] = [
    { value: '', label: 'All Clients (Global)' },
    ...clients.map((c) => ({ value: String(c.id), label: c.name })),
  ];

  return (
    <div className="flex items-center gap-2 w-full sm:w-64">
      <i className="fa-solid fa-building text-[#405189] dark:text-indigo-400 text-sm shrink-0" title="Filter dashboard by client"></i>
      <SearchableSelect
        options={options}
        value={clientId ?? ''}
        onChange={(v: any) => {
          const id = v === null || v === undefined ? '' : String(v);
          if (onChange) {
            onChange(id); // in-place filter — no navigation, no request
            return;
          }
          router.push(id ? `/dashboard?client=${id}` : '/dashboard');
        }}
        placeholder="All Clients (Global)"
        controlBgClass="bg-white dark:bg-slate-900"
      />
    </div>
  );
}
