import {
  type Action,
  ActionType,
  type InitState,
  type State,
} from "@/types/components/form/bookingwidget"
import type { Locations } from "@/types/trpc/routers/hotel/locations"

export const localStorageKey = "searchHistory"
export const sessionStorageKey = "searchData"

export function init(initState: InitState): State {
  return {
    defaultLocations: initState.defaultLocations,
    locations: [],
    search: "",
    searchData: undefined,
    searchHistory: null,
  }
}

export function reducer(state: State, action: Action) {
  const type = action.type
  switch (type) {
    case ActionType.CLEAR_HISTORY_LOCATIONS: {
      return {
        ...state,
        locations: [],
        search: "",
        searchHistory: null,
      }
    }
    case ActionType.CLEAR_SEARCH_LOCATIONS:
      return {
        ...state,
        locations: [],
        search: "",
      }
    case ActionType.SEARCH_LOCATIONS: {
      const matchesMap = new Map()
      const search = action.payload.search.toLowerCase()
      state.defaultLocations.forEach((location) => {
        const locationName = location.name.toLowerCase()
        const keyWords = location.keyWords?.map((l) => l.toLowerCase())
        if (locationName.includes(search.trim())) {
          matchesMap.set(location.name, location)
        }
        if (keyWords?.find((keyWord) => keyWord.includes(search.trim()))) {
          matchesMap.set(location.name, location)
        }
      })

      const matches: Locations = []
      matchesMap.forEach((value) => {
        matches.push(value)
      })

      return {
        ...state,
        locations: matches,
        search: action.payload.search,
      }
    }
    case ActionType.SELECT_ITEM: {
      return {
        ...state,
        searchData: action.payload.location,
        searchHistory: action.payload.searchHistory,
      }
    }
    case ActionType.SET_STORAGE_DATA: {
      return {
        ...state,
        searchData: action.payload.searchData,
        searchHistory: action.payload.searchHistory,
      }
    }
    default:
      const unhandledActionType: never = type
      console.info(`Unhandled type: ${unhandledActionType}`)
      return state
  }
}
