import { useState, useEffect } from 'react';
import { eventApi } from '../api/eventApi';
import type {
  EventDetail,
  GetEventsRequest,
  EventStatus,
  PageResponse,
} from './types';

/**
 * useEvents Hook
 * 이벤트 목록 조회 및 상태 관리
 */
export function useEvents(initialParams?: GetEventsRequest) {
  const [events, setEvents] = useState<EventDetail[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const [pageInfo, setPageInfo] = useState<Omit<PageResponse<EventDetail>, 'content'>>({
    page: 0,
    size: 20,
    totalElements: 0,
    totalPages: 0,
    first: true,
    last: true,
  });

  const fetchEvents = async (params?: GetEventsRequest) => {
    try {
      setLoading(true);
      setError(null);
      console.log('🔄 Fetching events with params:', params);

      const response = await eventApi.getEvents(params);
      console.log('✅ Events fetched:', response);

      if (response.success && response.data) {
        setEvents(response.data.content);
        setPageInfo({
          page: response.data.page,
          size: response.data.size,
          totalElements: response.data.totalElements,
          totalPages: response.data.totalPages,
          first: response.data.first,
          last: response.data.last,
        });
      }
    } catch (err) {
      console.error('❌ Error fetching events:', err);
      setError(err as Error);
    } finally {
      setLoading(false);
    }
  };

  // 초기 로드
  useEffect(() => {
    fetchEvents(initialParams);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return {
    events,
    loading,
    error,
    pageInfo,
    refetch: fetchEvents,
  };
}

/**
 * useEvent Hook
 * 단일 이벤트 조회 및 상태 관리
 */
export function useEvent(eventId: string) {
  const [event, setEvent] = useState<EventDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const fetchEvent = async () => {
    if (!eventId) return;

    try {
      setLoading(true);
      setError(null);
      console.log('🔄 Fetching event:', eventId);

      const response = await eventApi.getEvent(eventId);
      console.log('✅ Event fetched:', response);

      if (response.success && response.data) {
        setEvent(response.data);
      }
    } catch (err) {
      console.error('❌ Error fetching event:', err);
      setError(err as Error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEvent();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [eventId]);

  return {
    event,
    loading,
    error,
    refetch: fetchEvent,
  };
}

/**
 * useEventActions Hook
 * 이벤트 생성, 삭제, 배포 등의 액션 관리
 */
export function useEventActions() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const createEvent = async (objective: string) => {
    try {
      setLoading(true);
      setError(null);
      console.log('🔄 Creating event with objective:', objective);

      const response = await eventApi.createEvent({ objective: objective as any });
      console.log('✅ Event created:', response);

      return response.data;
    } catch (err) {
      console.error('❌ Error creating event:', err);
      setError(err as Error);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const deleteEvent = async (eventId: string) => {
    try {
      setLoading(true);
      setError(null);
      console.log('🔄 Deleting event:', eventId);

      await eventApi.deleteEvent(eventId);
      console.log('✅ Event deleted');
    } catch (err) {
      console.error('❌ Error deleting event:', err);
      setError(err as Error);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const publishEvent = async (eventId: string) => {
    try {
      setLoading(true);
      setError(null);
      console.log('🔄 Publishing event:', eventId);

      await eventApi.publishEvent(eventId);
      console.log('✅ Event published');
    } catch (err) {
      console.error('❌ Error publishing event:', err);
      setError(err as Error);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const endEvent = async (eventId: string) => {
    try {
      setLoading(true);
      setError(null);
      console.log('🔄 Ending event:', eventId);

      await eventApi.endEvent(eventId);
      console.log('✅ Event ended');
    } catch (err) {
      console.error('❌ Error ending event:', err);
      setError(err as Error);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  return {
    createEvent,
    deleteEvent,
    publishEvent,
    endEvent,
    loading,
    error,
  };
}
