import React, {
  createContext,
  useContext,
  useState,
  useCallback,
  ReactNode,
} from "react";
import {
  TableRegistration,
  TableOptionsContextValue,
} from "@/types/table-options";

const TableOptionsContext = createContext<TableOptionsContextValue | undefined>(
  undefined
);

export const TableOptionsProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  const [registeredTables, setRegisteredTables] = useState<
    Map<string, TableRegistration>
  >(new Map());
  const [selectedTableId, setSelectedTableId] = useState<string | null>(null);

  /**
   * 테이블 등록
   */
  const registerTable = useCallback((registration: TableRegistration) => {
    setRegisteredTables((prev) => {
      const newMap = new Map(prev);
      newMap.set(registration.tableId, registration);

      // 첫 번째 테이블이면 자동 선택
      if (newMap.size === 1) {
        setSelectedTableId(registration.tableId);
      }

      return newMap;
    });

    console.log(
      `[TableOptions] 테이블 등록: ${registration.label} (${registration.tableId})`
    );
  }, []);

  /**
   * 테이블 등록 해제
   */
  const unregisterTable = useCallback(
    (tableId: string) => {
      setRegisteredTables((prev) => {
        const newMap = new Map(prev);
        const removed = newMap.delete(tableId);

        if (removed) {
          console.log(`[TableOptions] 테이블 해제: ${tableId}`);

          // 선택된 테이블이 제거되면 첫 번째 테이블 선택
          if (selectedTableId === tableId) {
            const firstTableId = newMap.keys().next().value;
            setSelectedTableId(firstTableId || null);
          }
        }

        return newMap;
      });
    },
    [selectedTableId]
  );

  /**
   * 특정 테이블 조회
   */
  const getTable = useCallback(
    (tableId: string) => {
      return registeredTables.get(tableId);
    },
    [registeredTables]
  );

  return (
    <TableOptionsContext.Provider
      value={{
        registeredTables,
        registerTable,
        unregisterTable,
        getTable,
        selectedTableId,
        setSelectedTableId,
      }}
    >
      {children}
    </TableOptionsContext.Provider>
  );
};

/**
 * Context Hook
 */
export const useTableOptions = () => {
  const context = useContext(TableOptionsContext);
  if (!context) {
    throw new Error("useTableOptions must be used within TableOptionsProvider");
  }
  return context;
};

