import { useEffect, useState } from 'react';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { fg } from '@atlaskit/platform-feature-flags';
import { useSmartCardActions as useSmartLinkActions } from '../actions';
import { useSmartLinkConfig } from '../config';
import { useSmartLinkRenderers } from '../renderers';
import { useSmartCardState as useSmartLinkState } from '../store';

/**
 * Hook for smart link state and actions.
 * @param id - Unique identifier for the smart link
 * @param url - The URL to resolve
 * @param appearance - Card appearance hint for ORS to optimize response payload.
 *                     When 'inline', ORS returns minimal data (title, status).
 *                     When 'block' or 'embed', ORS returns full data including summary.
 */
export function useSmartLink(id, url, appearance) {
  const state = useSmartLinkState(url);
  const {
    store,
    isPreviewPanelAvailable,
    openPreviewPanel
  } = useSmartLinkContext();
  const actions = useSmartLinkActions(id, url);
  const config = useSmartLinkConfig();
  const renderers = useSmartLinkRenderers();

  // NB: used to propagate errors from hooks to error boundaries.
  const [error, setError] = useState(null);
  // Register the current card with appearance hint for optimized ORS response.
  const register = () => {
    actions.register(fg('platform_smartlink_inline_resolve_optimization') ? appearance : undefined).catch(err => setError(err));
  };
  // AFP-2511 TODO: Fix automatic suppressions below
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(register, [url, store]);

  // Provide the state and card actions to consumers.
  return {
    state,
    actions,
    config,
    renderers,
    error,
    isPreviewPanelAvailable,
    openPreviewPanel
  };
}