import { useEffect, useState } from 'react';
import {
  fetchUserLocationFilters,
  getStoredPhccSiteName,
} from '../utils/userHospital';

export function useUserPhccSiteFilter() {
  const [userPhccSiteName, setUserPhccSiteName] = useState(() => getStoredPhccSiteName());
  const [loading, setLoading] = useState(!getStoredPhccSiteName());

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

    fetchUserLocationFilters()
      .then(({ siteName }) => {
        if (cancelled || !siteName) return;
        setUserPhccSiteName(siteName);
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

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

  return {
    userPhccSiteName,
    siteLocked: !!userPhccSiteName,
    loading,
  };
}

export default useUserPhccSiteFilter;
