import React from 'react';
import { fetchEvent, type EventData, FetchEventError } from '../services/eventApi';
import { isTaskModeEnabled } from '@/shared/guest/lib/engagement';

type EventDataStatus = 'idle' | 'loading' | 'ready' | 'error';

type EventDataContextValue = {
  event: EventData | null;
  status: EventDataStatus;
  error: string | null;
  token: string | null;
  tasksEnabled: boolean;
};

const EventDataContext = React.createContext<EventDataContextValue>({
  event: null,
  status: 'idle',
  error: null,
  token: null,
  tasksEnabled: true,
});

type EventDataProviderProps = {
  token?: string | null;
  tasksEnabledFallback?: boolean;
  children: React.ReactNode;
};

export function EventDataProvider({
  token,
  tasksEnabledFallback = true,
  children,
}: EventDataProviderProps) {
  const [event, setEvent] = React.useState<EventData | null>(null);
  const [status, setStatus] = React.useState<EventDataStatus>(token ? 'loading' : 'idle');
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    if (!token) {
      setEvent(null);
      setStatus('idle');
      setError(null);
      return;
    }

    let cancelled = false;

    const loadEvent = async () => {
      setStatus('loading');
      setError(null);

      try {
        const eventData = await fetchEvent(token);
        if (cancelled) {
          return;
        }
        setEvent(eventData);
        setStatus('ready');
      } catch (err) {
        if (cancelled) {
          return;
        }

        setEvent(null);
        setStatus('error');

        if (err instanceof FetchEventError) {
          setError(err.message);
        } else if (err instanceof Error) {
          setError(err.message || 'Event could not be loaded.');
        } else {
          setError('Event could not be loaded.');
        }
      }
    };

    loadEvent();

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

  const tasksEnabled = event ? isTaskModeEnabled(event) : tasksEnabledFallback;

  return (
    <EventDataContext.Provider
      value={{
        event,
        status,
        error,
        token: token ?? null,
        tasksEnabled,
      }}
    >
      {children}
    </EventDataContext.Provider>
  );
}

export function useEventData() {
  return React.useContext(EventDataContext);
}
