import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  fetchUserLocationFilters,
  getStoredHospitalName,
} from '../utils/userHospital';
import { buildHospitalLinkFilters } from '../utils/hospitalUtils';

export function useUserHospitalFilter() {
  const [filterHospital, setFilterHospital] = useState(() => getStoredHospitalName());
  const [filtersLocked, setFiltersLocked] = useState(false);
  const [allowedHospitals, setAllowedHospitals] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;

    fetchUserLocationFilters()
      .then(({ hospital, isLocked, allowedHospitals: allowed }) => {
        if (cancelled) return;

        setAllowedHospitals(allowed);
        setFiltersLocked(isLocked);

        if (hospital) {
          setFilterHospital(hospital);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, []);

  const handleHospitalChange = useCallback(
    (value: string) => {
      if (filtersLocked) return;
      setFilterHospital(value);
    },
    [filtersLocked]
  );

  const hospitalLinkFilters = useMemo(
    () => buildHospitalLinkFilters(allowedHospitals),
    [allowedHospitals]
  );

  return {
    filterHospital,
    filtersLocked,
    allowedHospitals,
    hospitalLinkFilters,
    loading,
    handleHospitalChange,
  };
}

export default useUserHospitalFilter;
