"use client";

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

interface WidgetHeight {
  screenId: number;
  componentId: string;
  height: number;
  originalHeight: number; // 디자이너에서 설정한 원래 높이
}

interface TableSearchWidgetHeightContextValue {
  widgetHeights: Map<string, WidgetHeight>;
  setWidgetHeight: (screenId: number, componentId: string, height: number, originalHeight: number) => void;
  getWidgetHeight: (screenId: number, componentId: string) => WidgetHeight | undefined;
  getHeightDiff: (screenId: number, componentId: string) => number; // 실제 높이 - 원래 높이
}

const TableSearchWidgetHeightContext = createContext<TableSearchWidgetHeightContextValue | undefined>(
  undefined
);

export function TableSearchWidgetHeightProvider({ children }: { children: React.ReactNode }) {
  const [widgetHeights, setWidgetHeights] = useState<Map<string, WidgetHeight>>(new Map());

  const setWidgetHeight = useCallback(
    (screenId: number, componentId: string, height: number, originalHeight: number) => {
      const key = `${screenId}_${componentId}`;
      
      setWidgetHeights((prev) => {
        const newMap = new Map(prev);
        newMap.set(key, {
          screenId,
          componentId,
          height,
          originalHeight,
        });
        
        return newMap;
      });
    },
    []
  );

  const getWidgetHeight = useCallback(
    (screenId: number, componentId: string): WidgetHeight | undefined => {
      const key = `${screenId}_${componentId}`;
      return widgetHeights.get(key);
    },
    [widgetHeights]
  );

  const getHeightDiff = useCallback(
    (screenId: number, componentId: string): number => {
      const widgetHeight = getWidgetHeight(screenId, componentId);
      if (!widgetHeight) return 0;
      
      const diff = widgetHeight.height - widgetHeight.originalHeight;
      return diff;
    },
    [getWidgetHeight]
  );

  return (
    <TableSearchWidgetHeightContext.Provider
      value={{
        widgetHeights,
        setWidgetHeight,
        getWidgetHeight,
        getHeightDiff,
      }}
    >
      {children}
    </TableSearchWidgetHeightContext.Provider>
  );
}

export function useTableSearchWidgetHeight() {
  const context = useContext(TableSearchWidgetHeightContext);
  if (!context) {
    throw new Error(
      "useTableSearchWidgetHeight must be used within TableSearchWidgetHeightProvider"
    );
  }
  return context;
}

