import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { produce } from 'immer';

type TableKey = string;

interface TablePagination {
  page: number; // 0-based untuk MUI DataGrid
  pageSize: number;
}

interface PaginationState {
  tables: Record<TableKey, TablePagination>;
}

interface PaginationActions {
  setPagination: (table: TableKey, next: Partial<TablePagination>) => void;
  resetPagination: (table: TableKey) => void;
  resetAllPaginations: () => void;
  getPagination: (table: TableKey) => TablePagination;
  removePagination: (table: TableKey) => void;
}

type PaginationStore = PaginationState & PaginationActions;

// ✅ Default untuk MUI DataGrid (0-based)
const DEFAULT_PAGINATION: Readonly<TablePagination> = Object.freeze({
  page: 0, // 0-based untuk MUI
  pageSize: 10,
});

const STORAGE_KEY = 'pagination-storage';

export const usePaginationStore = create<PaginationStore>()(
  devtools(
    persist(
      (set, get) => ({
        tables: {},

        setPagination: (table, next) => {
          set(
            produce<PaginationStore>((draft) => {
              const current = draft.tables[table] ?? { ...DEFAULT_PAGINATION };

              draft.tables[table] = {
                page: next.page ?? current.page,
                pageSize: next.pageSize ?? current.pageSize,
              };
            }),
            false,
            { type: 'SET_PAGINATION', table, next }
          );
        },

        resetPagination: (table) => {
          set(
            produce<PaginationStore>((draft) => {
              const currentPageSize = draft.tables[table]?.pageSize ?? DEFAULT_PAGINATION.pageSize;

              draft.tables[table] = {
                page: DEFAULT_PAGINATION.page,
                pageSize: currentPageSize,
              };
            }),
            false,
            { type: 'RESET_PAGINATION', table }
          );
        },

        resetAllPaginations: () => {
          set({ tables: {} }, false, { type: 'RESET_ALL_PAGINATIONS' });
        },

        getPagination: (table) => {
          const state = get();
          return state.tables[table] ?? { ...DEFAULT_PAGINATION };
        },

        removePagination: (table) => {
          set(
            produce<PaginationStore>((draft) => {
              delete draft.tables[table];
            }),
            false,
            { type: 'REMOVE_PAGINATION', table }
          );
        },
      }),
      {
        name: STORAGE_KEY,
        partialize: (state) => ({ tables: state.tables }),
      }
    ),
    { name: 'PaginationStore', enabled: process.env.NODE_ENV === 'development' }
  )
);

// ============================================================================
// CUSTOM HOOKS WITH 1-BASED CONVERSION
// ============================================================================

/**
 * ✅ Hook dengan konversi otomatis ke 1-based untuk backend
 * MUI DataGrid: 0-based (page 0, 1, 2, ...)
 * Backend API: 1-based (page 1, 2, 3, ...)
 */
export const useTablePagination = (tableKey: TableKey) => {
  const pagination = usePaginationStore((s) => s.tables[tableKey] ?? DEFAULT_PAGINATION);
  const setPagination = usePaginationStore((s) => s.setPagination);
  const resetPagination = usePaginationStore((s) => s.resetPagination);

  return [
    pagination, // untuk MUI DataGrid (0-based)
    (next: Partial<TablePagination>) => setPagination(tableKey, next),
    () => resetPagination(tableKey),
  ] as const;
};

/**
 * ✅ Hook khusus yang return page dalam format 1-based untuk API
 */
export const useTablePaginationForAPI = (tableKey: TableKey) => {
  const pagination = usePaginationStore((s) => s.tables[tableKey] ?? DEFAULT_PAGINATION);

  return {
    page: pagination.page + 1, // Convert to 1-based
    pageSize: pagination.pageSize,
    limit: pagination.pageSize, // alias
  };
};

export const useTablePage = (tableKey: TableKey) =>
  usePaginationStore((s) => s.tables[tableKey]?.page ?? DEFAULT_PAGINATION.page);

export const useTablePageSize = (tableKey: TableKey) =>
  usePaginationStore((s) => s.tables[tableKey]?.pageSize ?? DEFAULT_PAGINATION.pageSize);

export const createTableKey = (...parts: string[]): TableKey => parts.filter(Boolean).join('-');

export type { TableKey, TablePagination, PaginationStore };
export { DEFAULT_PAGINATION };
