import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { createUserStorage } from './utils/userStorage';

interface PageColumnSettings {
  columnWidths: Record<string, number>;
  hiddenColumns: string[];
}

interface TableColumnState {
  pageSettings: Record<string, PageColumnSettings>;
  setColumnWidth: (pageId: string, columnKey: string, width: number) => void;
  toggleColumnVisibility: (pageId: string, columnKey: string) => void;
  resetPageSettings: (pageId: string) => void;
  getPageSettings: (pageId: string) => PageColumnSettings;
}

const DEFAULT_PAGE_SETTINGS: PageColumnSettings = {
  columnWidths: {},
  hiddenColumns: [],
};

export const useTableColumnStore = create<TableColumnState>()(
  persist(
    (set, get) => ({
      pageSettings: {},

      setColumnWidth: (pageId: string, columnKey: string, width: number) => {
        const { pageSettings } = get();
        const current = pageSettings[pageId] || { ...DEFAULT_PAGE_SETTINGS };
        set({
          pageSettings: {
            ...pageSettings,
            [pageId]: {
              ...current,
              columnWidths: { ...current.columnWidths, [columnKey]: width },
            },
          },
        });
      },

      toggleColumnVisibility: (pageId: string, columnKey: string) => {
        const { pageSettings } = get();
        const current = pageSettings[pageId] || { ...DEFAULT_PAGE_SETTINGS };
        const hidden = current.hiddenColumns.includes(columnKey)
          ? current.hiddenColumns.filter((k) => k !== columnKey)
          : [...current.hiddenColumns, columnKey];
        set({
          pageSettings: {
            ...pageSettings,
            [pageId]: { ...current, hiddenColumns: hidden },
          },
        });
      },

      resetPageSettings: (pageId: string) => {
        const { pageSettings } = get();
        const { [pageId]: _, ...rest } = pageSettings;
        set({ pageSettings: rest });
      },

      getPageSettings: (pageId: string) => {
        return get().pageSettings[pageId] || DEFAULT_PAGE_SETTINGS;
      },
    }),
    {
      name: 'sam-table-columns',
      storage: createUserStorage('sam-table-columns'),
    }
  )
);

// ===== 셀렉터 훅 =====

/** 특정 페이지의 컬럼 설정만 구독 */
export const usePageColumnSettings = (pageId: string) =>
  useTableColumnStore((state) => state.pageSettings[pageId] ?? DEFAULT_PAGE_SETTINGS);

/** 특정 페이지의 숨김 컬럼만 구독 */
export const useHiddenColumns = (pageId: string) =>
  useTableColumnStore((state) => state.pageSettings[pageId]?.hiddenColumns ?? []);

/** 특정 페이지의 컬럼 너비만 구독 */
export const useColumnWidths = (pageId: string) =>
  useTableColumnStore((state) => state.pageSettings[pageId]?.columnWidths ?? {});
