/**
 * useCheckout Hook
 * TanStack Query hooks for checkout and subscription operations
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { marketplaceService } from '../../../services/marketplace.service';
import type {
  UserSubscription,
  ConsultationBooking,
} from '../../../types/marketplace.types';

// ============================================================================
// Query Keys
// ============================================================================

export const checkoutKeys = {
  all: ['checkout'] as const,
  subscriptions: () => [...checkoutKeys.all, 'subscriptions'] as const,
  subscription: (id: string) => [...checkoutKeys.subscriptions(), id] as const,
  bookings: () => [...checkoutKeys.all, 'bookings'] as const,
  booking: (id: string) => [...checkoutKeys.bookings(), id] as const,
};

// ============================================================================
// Subscription Hooks
// ============================================================================

/**
 * Hook for fetching user's subscriptions
 */
export function useMySubscriptions() {
  return useQuery<UserSubscription[], Error>({
    queryKey: checkoutKeys.subscriptions(),
    queryFn: () => marketplaceService.getMySubscriptions(),
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for fetching a single subscription
 */
export function useSubscription(id: string) {
  return useQuery<UserSubscription, Error>({
    queryKey: checkoutKeys.subscription(id),
    queryFn: () => marketplaceService.getSubscriptionById(id),
    enabled: !!id,
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for subscribing to a signal pack
 */
export function useSubscribeToSignalPack() {
  const queryClient = useQueryClient();

  return useMutation<
    UserSubscription,
    Error,
    { packId: string; pricingId: string }
  >({
    mutationFn: ({ packId, pricingId }) =>
      marketplaceService.subscribeToSignalPack(packId, pricingId),
    onSuccess: () => {
      // Invalidate subscriptions cache
      queryClient.invalidateQueries({ queryKey: checkoutKeys.subscriptions() });
    },
  });
}

/**
 * Hook for cancelling a subscription
 */
export function useCancelSubscription() {
  const queryClient = useQueryClient();

  return useMutation<UserSubscription, Error, string>({
    mutationFn: (id) => marketplaceService.cancelSubscription(id),
    onSuccess: (data, id) => {
      // Update cache with cancelled subscription
      queryClient.setQueryData<UserSubscription[]>(
        checkoutKeys.subscriptions(),
        (old) => old?.map((s) => (s.id === id ? data : s))
      );
    },
  });
}

/**
 * Hook for renewing a subscription
 */
export function useRenewSubscription() {
  const queryClient = useQueryClient();

  return useMutation<
    UserSubscription,
    Error,
    { id: string; pricingId: string }
  >({
    mutationFn: ({ id, pricingId }) =>
      marketplaceService.renewSubscription(id, pricingId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: checkoutKeys.subscriptions() });
    },
  });
}

// ============================================================================
// Booking Hooks
// ============================================================================

/**
 * Hook for fetching user's consultation bookings
 */
export function useMyBookings() {
  return useQuery<ConsultationBooking[], Error>({
    queryKey: checkoutKeys.bookings(),
    queryFn: () => marketplaceService.getMyBookings(),
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for fetching a single booking
 */
export function useBooking(id: string) {
  return useQuery<ConsultationBooking, Error>({
    queryKey: checkoutKeys.booking(id),
    queryFn: () => marketplaceService.getBookingById(id),
    enabled: !!id,
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for booking a consultation
 */
export function useBookConsultation() {
  const queryClient = useQueryClient();

  return useMutation<
    ConsultationBooking,
    Error,
    {
      advisoryId: string;
      data: {
        serviceTypeId: string;
        scheduledAt: string;
        notes?: string;
      };
    }
  >({
    mutationFn: ({ advisoryId, data }) =>
      marketplaceService.bookConsultation(advisoryId, data),
    onSuccess: () => {
      // Invalidate bookings cache
      queryClient.invalidateQueries({ queryKey: checkoutKeys.bookings() });
    },
  });
}

/**
 * Hook for cancelling a booking
 */
export function useCancelBooking() {
  const queryClient = useQueryClient();

  return useMutation<ConsultationBooking, Error, string>({
    mutationFn: (id) => marketplaceService.cancelBooking(id),
    onSuccess: (data, id) => {
      // Update cache with cancelled booking
      queryClient.setQueryData<ConsultationBooking[]>(
        checkoutKeys.bookings(),
        (old) => old?.map((b) => (b.id === id ? data : b))
      );
    },
  });
}

// ============================================================================
// Checkout State Hook
// ============================================================================

interface CheckoutState {
  productId: string | null;
  productType: 'signals' | 'advisory' | 'courses' | null;
  pricingId: string | null;
  couponCode: string | null;
  discountAmount: number;
}

/**
 * Custom hook for managing checkout state
 * Uses React state internally - could be moved to context if needed across components
 */
export function useCheckoutState(initialState?: Partial<CheckoutState>) {
  const defaultState: CheckoutState = {
    productId: null,
    productType: null,
    pricingId: null,
    couponCode: null,
    discountAmount: 0,
    ...initialState,
  };

  return defaultState;
}
