"use client";

import React, { createContext, useContext, useEffect, useMemo, useReducer } from "react";
import { useSearchParams } from "next/navigation";
import { formatSearchDate } from "@/utils/jalali";
import { InitialStateType, SearchActions, Types, searchReducer } from "./search.reducer";

const initialState: InitialStateType = {
  category: {},
  location: {
    status: "",
  },
  date: {},
  searchTime: { time: null },
};

const SearchContext = createContext<{
  state: InitialStateType;
  dispatch: React.Dispatch<SearchActions>;
}>({ state: initialState, dispatch: () => null });

function stateFromParams(searchParams: URLSearchParams): InitialStateType {
  const dateFromUrl = searchParams.get("date");
  const dateQuery = dateFromUrl ? formatSearchDate(dateFromUrl) || dateFromUrl : undefined;
  return {
    date: { ...(dateQuery && { query: dateQuery }) },
    location: {
      status: "",
      ...(searchParams.has("location") && { query: searchParams.get("location") as string }),
      ...(searchParams.has("latitude") &&
        searchParams.has("longitude") && {
          geolocation: {
            longitude: searchParams.get("longitude") as string,
            latitude: searchParams.get("latitude") as string,
          },
        }),
    },
    category: {
      ...(searchParams.has("revenue") && { query: searchParams.get("revenue") as string }),
      ...(searchParams.has("category_id") && {
        categoryId: searchParams.get("category_id") as string,
      }),
    },
    searchTime: {
      time:
        searchParams.has("timeFrom") && searchParams.has("timeTo")
          ? {
              from: searchParams.get("timeFrom") as string,
              to: searchParams.get("timeTo") as string,
            }
          : null,
    },
  };
}

const SearchProvider = ({ children }: { children: React.ReactNode }) => {
  const searchParams = useSearchParams();
  // همیشه state خالی برای SSR/hydrate — بعد از mount از URL پر می‌شود (رفع #418)
  const [state, dispatch] = useReducer(searchReducer, initialState);

  const searchKey = searchParams.toString();

  useEffect(() => {
    dispatch({ type: Types.Replace, payload: stateFromParams(searchParams) });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchKey]);

  const memoizedValue = useMemo(() => ({ state, dispatch }), [state]);
  return <SearchContext.Provider value={memoizedValue}>{children}</SearchContext.Provider>;
};

export default SearchProvider;
export const useSearch = () => {
  const searchContext = useContext(SearchContext);

  if (!searchContext) {
    throw new Error("useSearch has to be used within <Search.Provider>");
  }

  return searchContext;
};
