/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable spellcheck/spell-checker */
import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { getProjectOptionsByCity } from '@/app/lead-routing/service';
import { useRoles } from '@/hooks/useRoles';

export interface CityProjectOption { value: number, label: string }

// Enough to take a whole city in one call (a city has ~1.6k projects).
const ALL_PROJECTS_PAGE_SIZE = 5000;

// One request per city per page load, shared by every dropdown that asks for it.
const cache = new Map<number, CityProjectOption[]>();
const inflight = new Map<number, Promise<CityProjectOption[]>>();

const loadCity = (cityId: number): Promise<CityProjectOption[]> => {
  const hit = cache.get(cityId);
  if (hit) return Promise.resolve(hit);
  let p = inflight.get(cityId);
  if (!p) {
    // Same GET /api/v1/projects/by-city the lead-routing Add Rotation project dropdown uses.
    p = getProjectOptionsByCity({ cityId, page: 1, pageSize: ALL_PROJECTS_PAGE_SIZE })
      .then((list) => {
        const options = list.map((x) => ({ value: x.id, label: x.name }));
        cache.set(cityId, options);
        return options;
      })
      .finally(() => {
 inflight.delete(cityId);
});
    inflight.set(cityId, p);
  }
  return p;
};

// Super admin keeps the launch-wise project list; every other role gets the projects of the
// city (cities) they belong to - all launches of a city carry the same projects - fetched once
// and filtered on the client.
export function useCityProjects() {
  const { data: session } = useSession();
  const { getRoleByName } = useRoles();
  const user = (session as any)?.user;
  const roleId = user?.role?.id;
  const isCityScoped = !!roleId && roleId !== getRoleByName('super_admin')?.id;
  const cityKey = ((user?.cities || []) as { city_id: number }[]).map((c) => Number(c.city_id)).filter(Boolean).join(',');

  const [options, setOptions] = useState<CityProjectOption[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!isCityScoped || !cityKey) return;
    let cancelled = false;
    setLoading(true);
    Promise.all(cityKey.split(',').map((id) => loadCity(Number(id))))
      .then((lists) => {
        if (cancelled) return;
        const seen = new Set<number>();
        setOptions(lists.flat().filter((o) => !seen.has(o.value) && seen.add(o.value)));
      })
      .catch(() => {
 if (!cancelled) setOptions([]);
})
      .finally(() => {
 if (!cancelled) setLoading(false);
});
    return () => {
 cancelled = true;
};
  }, [isCityScoped, cityKey]);

  return { isCityScoped, options, loading };
}

export const filterProjectOptions = (options: CityProjectOption[], term: string): CityProjectOption[] => {
  const t = term.trim().toLowerCase();
  return t ? options.filter((o) => o.label.toLowerCase().includes(t)) : options;
};
