import { StateCreator } from 'zustand';
import { TableUISlice } from '@/types/stores';

export interface TableState {
  key: string;
  path: string;
  searchValue: string;
}

function getPathGroup(path: string): string {
  const segments = path.split('/').filter(Boolean);
  const subPaths = ['add', 'detail', 'edit'];
  const lastSegment = segments[segments.length - 1];

  // If last segment is a sub-path or numeric ID, remove it
  if (
    lastSegment &&
    (subPaths.includes(lastSegment) || /^\d+$/.test(lastSegment))
  ) {
    segments.pop();
  }

  return segments.length > 0 ? '/' + segments.join('/') : path;
}

function isSamePathGroup(
  currentPath: string,
  previousPath: string | null
): boolean {
  if (!previousPath) return false;
  return getPathGroup(currentPath) === getPathGroup(previousPath);
}

export const createTableUISlice: StateCreator<
  TableUISlice,
  [],
  [],
  TableUISlice
> = (set) => ({
  // Initial state
  key: '',
  path: '',
  searchValue: '',
  previousPath: null,

  // Actions
  setSearchValue: (value) => set({ searchValue: value }),

  resetSearchValue: () => {
    return set({ searchValue: '' });
  },

  setTableState: (key, path, searchValue = '') => {
    set((state) => {
      const isSameGroup = isSamePathGroup(path, state.path);

      return {
        key,
        path,
        previousPath: state.path,
        // Reset search if path group changed, otherwise keep existing search
        searchValue: isSameGroup ? state.searchValue : searchValue,
      };
    });
  },

  resetTableState: () => {
    set({
      key: '',
      path: '',
      searchValue: '',
      previousPath: null,
    });
  },
});
