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

export function useUserDashboardFilters() {
  const [filterHospital, setFilterHospital] = useState(() => getStoredHospitalName());
  const [filterSiteName, setFilterSiteName] = useState(() => getStoredPhccSiteName());
  const [hospitalLocked, setHospitalLocked] = useState(false);
  const [siteLocked, setSiteLocked] = useState(() => !!getStoredPhccSiteName());
  const [allowedHospitals, setAllowedHospitals] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

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

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

        setAllowedHospitals(allowed);
        setHospitalLocked(isLocked);

        if (hospital) {
          setFilterHospital(hospital);
        }

        if (siteName) {
          setFilterSiteName(siteName);
          setSiteLocked(true);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

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

  const handleHospitalChange = useCallback(
    (value: string) => {
      if (hospitalLocked) return;

      setFilterHospital(value);
      if (!isSiteEnabledHospital(value)) {
        setFilterSiteName('');
      }
    },
    [hospitalLocked]
  );

  const handleSiteChange = useCallback(
    (value: string) => {
      if (siteLocked) return;
      setFilterSiteName(value);
    },
    [siteLocked]
  );

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

  return {
    filterHospital,
    filterSiteName,
    hospitalLocked,
    siteLocked,
    allowedHospitals,
    hospitalLinkFilters,
    /** @deprecated use hospitalLocked — hospital filter readonly when user has one permitted hospital */
    filtersLocked: hospitalLocked,
    loading,
    handleHospitalChange,
    handleSiteChange,
    setFilterSiteName: handleSiteChange,
  };
}

export default useUserDashboardFilters;
