import React from 'react';
import { useQuery } from '@tanstack/react-query';

import { getEvents, type TenantEvent } from '../api';
import { useAuth } from '../auth/context';

const STORAGE_KEY = 'tenant-admin.active-event';

export interface EventContextValue {
  events: TenantEvent[];
  isLoading: boolean;
  isError: boolean;
  activeEvent: TenantEvent | null;
  selectEvent: (slug: string | null) => void;
  refetch: () => void;
}

const EventContext = React.createContext<EventContextValue | undefined>(undefined);

export function EventProvider({ children }: { children: React.ReactNode }) {
  const { status } = useAuth();
  const [storedSlug, setStoredSlug] = React.useState<string | null>(() => {
    if (typeof window === 'undefined') {
      return null;
    }
    return window.localStorage.getItem(STORAGE_KEY);
  });

  const authReady = status === 'authenticated';

  const {
    data: fetchedEvents = [],
    isLoading: queryLoading,
    isError,
    refetch,
  } = useQuery<TenantEvent[]>({
    queryKey: ['tenant-events'],
    queryFn: async () => {
      try {
        return await getEvents({ force: true });
      } catch (error) {
        console.warn('[EventContext] Failed to fetch events', error);
        throw error;
      }
    },
    staleTime: 60 * 1000,
    enabled: authReady,
    initialData: [],
  });

  const events = React.useMemo(() => (authReady ? fetchedEvents : []), [authReady, fetchedEvents]);
  const isLoading = authReady ? queryLoading : status === 'loading';

  React.useEffect(() => {
    if (!events.length || typeof window === 'undefined') {
      return;
    }

    const hasStored = Boolean(storedSlug);
    const slugExists = hasStored && events.some((event) => event.slug === storedSlug);
    const fallbackSlug = events[0]?.slug;

    if (!slugExists && fallbackSlug) {
      setStoredSlug(fallbackSlug);
      window.localStorage.setItem(STORAGE_KEY, fallbackSlug);
    }
  }, [events, storedSlug]);

  const activeEvent = React.useMemo(() => {
    if (!events.length) {
      return null;
    }

    const matched = events.find((event) => event.slug && event.slug === storedSlug);
    if (matched) {
      return matched;
    }

    // Fallback to the first event if the stored slug is missing or stale.
    return events[0];
  }, [events, storedSlug]);

  const selectEvent = React.useCallback((slug: string | null) => {
    setStoredSlug(slug);
    if (typeof window !== 'undefined') {
      if (slug) {
        window.localStorage.setItem(STORAGE_KEY, slug);
      } else {
        window.localStorage.removeItem(STORAGE_KEY);
      }
    }
  }, []);

  const value = React.useMemo<EventContextValue>(
    () => ({
      events,
      isLoading,
      isError,
      activeEvent,
      selectEvent,
      refetch,
    }),
    [events, isLoading, isError, activeEvent, selectEvent, refetch]
  );

  return <EventContext.Provider value={value}>{children}</EventContext.Provider>;
}

export function useEventContext(): EventContextValue {
  const ctx = React.useContext(EventContext);
  if (!ctx) {
    throw new Error('useEventContext must be used within an EventProvider');
  }
  return ctx;
}
