import { useReducer } from 'react';

import type { WebhookDelivery, WebhookEndpoint } from '@/types';

/**
 * State shape for the webhooks settings page.
 * Consolidates 7 useState hooks into a single reducer.
 */
export interface WebhooksState {
  endpoints: WebhookEndpoint[];
  loading: boolean;
  showCreate: boolean;
  selectedEndpoint: WebhookEndpoint | null;
  showSecret: number | null;
  deliveries: WebhookDelivery[];
  deleteTarget: WebhookEndpoint | null;
}

/**
 * Action types for the webhooks reducer.
 * Using discriminated union for type-safe dispatch.
 */
export type WebhooksAction =
  | { type: 'SET_ENDPOINTS'; payload: WebhookEndpoint[] }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'TOGGLE_CREATE' }
  | { type: 'SELECT_ENDPOINT'; payload: WebhookEndpoint | null }
  | { type: 'TOGGLE_SECRET'; payload: number | null }
  | { type: 'SET_DELIVERIES'; payload: WebhookDelivery[] }
  | { type: 'SET_DELETE_TARGET'; payload: WebhookEndpoint | null }
  | { type: 'RESET_STATE' };

/**
 * Initial state for the webhooks reducer.
 */
const initialState: WebhooksState = {
  endpoints: [],
  loading: true,
  showCreate: false,
  selectedEndpoint: null,
  showSecret: null,
  deliveries: [],
  deleteTarget: null,
};

/**
 * Reducer function for webhooks state management.
 * Handles all state transitions for the webhooks settings page.
 */
function webhooksReducer(state: WebhooksState, action: WebhooksAction): WebhooksState {
  switch (action.type) {
    case 'SET_ENDPOINTS':
      return { ...state, endpoints: action.payload };

    case 'SET_LOADING':
      return { ...state, loading: action.payload };

    case 'TOGGLE_CREATE':
      return { ...state, showCreate: !state.showCreate };

    case 'SELECT_ENDPOINT':
      return { ...state, selectedEndpoint: action.payload };

    case 'TOGGLE_SECRET':
      return { ...state, showSecret: action.payload };

    case 'SET_DELIVERIES':
      return { ...state, deliveries: action.payload };

    case 'SET_DELETE_TARGET':
      return { ...state, deleteTarget: action.payload };

    case 'RESET_STATE':
      return initialState;

    default:
      return state;
  }
}

/**
 * Custom hook for managing webhooks page state with useReducer.
 *
 * Consolidates 7 useState hooks into a single reducer for better state management.
 * This improves code organization and makes state transitions more predictable.
 *
 * @returns {[WebhooksState, React.Dispatch<WebhooksAction>]} State and dispatch function
 *
 * @example
 * ```tsx
 * const [state, dispatch] = useWebhooksState();
 *
 * // Set endpoints
 * dispatch({ type: "SET_ENDPOINTS", payload: endpoints });
 *
 * // Toggle create dialog
 * dispatch({ type: "TOGGLE_CREATE" });
 *
 * // Show/hide secret
 * dispatch({ type: "TOGGLE_SECRET", payload: endpointId });
 * ```
 */
export function useWebhooksState() {
  return useReducer(webhooksReducer, initialState);
}
