'use client';

import { useCallback, useEffect, useState } from 'react';
import { usePathname } from '@/i18n/navigation';
import { notificationsApi } from '@/lib/api/notifications';
import {
  tabBadgesChangedEventName,
  tabFromPathname,
  type TabBadgeCounts,
} from '@/lib/tabBadgeUtils';
import { useAuth } from '@/lib/hooks/useAuth';

const EMPTY_COUNTS: TabBadgeCounts = {};

export function useTabBadgeCounts(): TabBadgeCounts {
  const pathname = usePathname();
  const { currentOrganization } = useAuth();
  const [counts, setCounts] = useState<TabBadgeCounts>(EMPTY_COUNTS);

  const fetchCounts = useCallback(async () => {
    if (!currentOrganization?.id) {
      setCounts(EMPTY_COUNTS);
      return;
    }

    try {
      const res = await notificationsApi.tabCounts();
      setCounts(res.data ?? EMPTY_COUNTS);
    } catch {
      setCounts(EMPTY_COUNTS);
    }
  }, [currentOrganization?.id]);

  useEffect(() => {
    void fetchCounts();
  }, [fetchCounts, pathname]);

  useEffect(() => {
    const onChanged = () => void fetchCounts();
    window.addEventListener(tabBadgesChangedEventName(), onChanged);
    return () => window.removeEventListener(tabBadgesChangedEventName(), onChanged);
  }, [fetchCounts]);

  return counts;
}

export function useMarkTabReadOnVisit() {
  const pathname = usePathname();
  const { currentOrganization } = useAuth();

  useEffect(() => {
    const tab = tabFromPathname(pathname);
    // Cases and Treatment tab badges clear per opened case (mark-case-read), not on tab visit.
    if (!tab || tab === 'CASES' || tab === 'TREATMENT' || !currentOrganization?.id) return;

    void notificationsApi.markTabRead(tab).then(() => {
      window.dispatchEvent(new Event(tabBadgesChangedEventName()));
    });
  }, [pathname, currentOrganization?.id]);
}
