import { useEffect } from 'react';
import { fetchUserHospitalName } from '../utils/userHospital';

export type HospitalFormField =
  | 'company'
  | 'custom_hospital_name'
  | 'hospital'
  | 'asset_owner_company';

interface UseDefaultHospitalOptions {
  enabled?: boolean;
  fields: HospitalFormField[];
}

export function useDefaultHospital(
  setFormData: React.Dispatch<React.SetStateAction<Record<string, any>>>,
  { enabled = true, fields }: UseDefaultHospitalOptions
): void {
  const fieldsKey = fields.join('|');

  useEffect(() => {
    if (!enabled) {
      return;
    }

    let cancelled = false;

    fetchUserHospitalName().then((hospitalName) => {
      if (cancelled || !hospitalName) {
        return;
      }

      setFormData((prev) => {
        const updates: Partial<Record<HospitalFormField, string>> = {};

        for (const field of fields) {
          if (!prev[field]) {
            updates[field] = hospitalName;
          }
        }

        if (Object.keys(updates).length === 0) {
          return prev;
        }

        return { ...prev, ...updates };
      });
    });

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

export default useDefaultHospital;
