import React, { createContext, useContext } from "react";

export interface CardContext {
  /**
   * If true, the card will always be in edit mode.
   * Does not requires, and indeed overrides, the `isEditable` prop.
   * Does not affect `isDisabled` or `isOpen`.
   * Keeps the card in `edit` mode even after submitting.
   */
  alwaysEditable: boolean;
  /**
   * Enables `edit` mode and the toggle in `CardHeader` if true.
   * Use `alwaysEditable` to keep the card in `edit` mode permanently.
   * Use `defaultEditing` to set the default state of the card.
   */
  isEditable: boolean;
  /**
   * If true, the card is in `editMode`
   */
  isEditing: boolean;
  /**
   * Sets the `isEditing` state
   */
  setIsEditing: React.Dispatch<React.SetStateAction<boolean>>;
  /**
   * Number of columns to use in the grid.
   */
  columns: number;
  /**
   * If the card has changes that need to be saved.
   */
  hasChanges: boolean;
  /**
   * Sets the `hasChanges` state
   */
  setHasChanges: React.Dispatch<React.SetStateAction<boolean>>;
  /**
   * If true, the card is disabled and cannot be edited.
   */
  isDisabled: boolean;
  /**
   * Uses compact layout for card and all fields if true.
   */
  isCompact: boolean;
  /**
   * If true, the card is collapsible.
   */
  isCollapsible: boolean;
  /**
   * If true, the card is open. Only makes sense if `isCollapsible` is true.
   */
  isOpen: boolean;
  /**
   * Sets the `isOpen` state.
   */
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
}

export const CardContext = createContext<CardContext>(undefined as unknown as CardContext);

export const useCardContext = () => {
  const context = useContext(CardContext);
  if (context == null) {
    throw new Error(
      "useCardContext must be used within a CardProvider. You are most likely not using the correct <Card> parent component.",
    );
  }

  return context;
};
