"use client";

import { Button } from "@/components/button";
import { Translate } from "@/components/translate";
import SearchIcon from "@/assets/icons/search";
import { useT } from "@/context/translation-map";
import LocationIcon from "@/assets/icons/location";
import CalendarIcon from "@/assets/icons/calendar";
import ClockIcon from "@/assets/icons/clock";
import { Popover } from "@headlessui/react";
import clsx from "clsx";
import dayjs from "@/utils/dayjs";
import { useSearch } from "@/context/search";
import customParseFormat from "dayjs/plugin/customParseFormat";
import { useMediaQuery } from "@/hook/use-media-query";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { usePopper } from "react-popper";
import ReactDOM from "react-dom";
import { useHourFormat } from "@/hook/use-hour-format";
import { SearchFieldCore } from "../search-field-core";

dayjs.extend(customParseFormat);

interface SearchFieldSeparatorProps {
  isInHeader?: boolean;
}

interface SearchFieldProps extends SearchFieldSeparatorProps {
  withPadding?: boolean;
  withButton?: boolean;
}

const Separator = ({ isInHeader }: SearchFieldSeparatorProps) => (
  <div
    className={clsx("w-px bg-dark bg-opacity-20 shrink-0 self-stretch", isInHeader ? "h-7" : "h-10")}
  />
);

export const SearchField = ({
  isInHeader,
  withPadding = true,
  withButton = true,
}: SearchFieldProps) => {
  const t = useT();
  const { state } = useSearch();
  const isMobile = useMediaQuery("(max-width: 768px)");
  const router = useRouter();
  const { hourFormat } = useHourFormat();
  const [referenceElement, setReferenceElement] = useState<HTMLButtonElement | null>(null);
  const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(null);
  const [isDomReady, setIsDomReady] = useState(false);
  const { styles, attributes } = usePopper(referenceElement, popperElement, {
    placement: "bottom-start",
    modifiers: [
      {
        name: "offset",
        options: {
          offset: [0, 20],
        },
      },
    ],
  });

  useEffect(() => {
    setIsDomReady(true);
  }, []);

  // جلوگیری از React #418 — متن ترجمه‌شده/استور فقط بعد از mount
  if (!isDomReady) {
    return (
      <div
        className={clsx(
          isInHeader && "hidden xl:block",
          "w-full lg:w-auto dropdown-shadow rounded-button"
        )}
      >
        <div
          className={clsx(
            "rounded-button bg-white flex flex-row items-center gap-3 w-full h-14 animate-pulse",
            withPadding && "py-2 px-3 lg:px-5"
          )}
          aria-hidden
        />
      </div>
    );
  }

  return (
    <div
      className={clsx(
        isInHeader && "hidden xl:block",
        "w-full lg:w-auto dropdown-shadow rounded-button"
      )}
    >
      <SearchFieldCore>
        {({
          openServices,
          openPlaceModal,
          handleSearch,
          renderTimeSelectPanel,
          renderDateSelectPanel,
        }) => (
          <div
            className={clsx(
              "rounded-button bg-white flex flex-row items-center justify-between gap-2 md:gap-3 lg:gap-5 w-full lg:w-auto flex-nowrap overflow-x-auto",
              isInHeader && "border border-gray-link p-[5px]",
              withPadding && "py-2 px-3 lg:py-2 lg:px-5"
            )}
          >
            <div className="relative flex-1 min-w-[7rem] rounded-button">
              <span className="absolute left-0 top-1/2 -translate-y-1/2">
                <SearchIcon />
              </span>
              <button
                className={clsx(
                  "pl-6 py-2 text-sm outline-none w-full min-w-0 text-start whitespace-nowrap text-ellipsis overflow-hidden",
                  !state.category.query && "text-gray-field"
                )}
                onClick={() => (isMobile ? router.push("/search/service") : openServices())}
              >
                {state.category.query || t("any")}
              </button>
            </div>
            <Separator isInHeader={isInHeader} />
            <div className="relative flex-1 min-w-[7rem] max-w-[12rem] rounded-button">
              <span className="absolute left-0 top-1/2 -translate-y-1/2">
                <LocationIcon />
              </span>
              <button
                className={clsx(
                  "pl-6 py-2 text-sm outline-none w-full min-w-0 text-start whitespace-nowrap text-ellipsis overflow-hidden",
                  !state.location.query && "text-gray-field"
                )}
                onClick={() => (isMobile ? router.push("/search/location") : openPlaceModal())}
              >
                {state.location.query || t("where")}
              </button>
            </div>
            <Separator isInHeader={isInHeader} />
            <Popover className="md:relative flex-1 min-w-[7rem]">
              <Popover.Button
                ref={setReferenceElement}
                onClick={isMobile ? () => router.push("/search/date") : undefined}
                className="relative flex items-center justify-start w-full rounded-button outline-none"
              >
                <span className="absolute left-0 top-1/2 -translate-y-1/2">
                  <CalendarIcon />
                </span>
                <span
                  className={clsx(
                    "pl-6 py-2 text-sm outline-none whitespace-nowrap text-ellipsis overflow-hidden",
                    !state.date.query && "text-gray-field"
                  )}
                >
                  {state.date.query ? state.date.query : t("date")}
                </span>
              </Popover.Button>
              {!isMobile &&
                isDomReady &&
                ReactDOM.createPortal(
                  <Popover.Panel
                    ref={setPopperElement}
                    style={styles.popper}
                    {...attributes.popper}
                    unmount
                    className="z-[9] md:top-14 md:rounded-button bg-white drop-shadow-xl md:px-5 md:pt-5 pb-5 px-4 pt-20 min-w-full md:min-w-[326px]"
                  >
                    {renderDateSelectPanel()}
                  </Popover.Panel>,
                  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                  // @ts-expect-error
                  document.getElementById("portal")
                )}
            </Popover>
            <Separator isInHeader={isInHeader} />
            <Popover className="md:relative flex-1 min-w-[7rem]">
              <Popover.Button
                onClick={isMobile ? () => router.push("/search/time") : undefined}
                className="relative flex items-center justify-start w-full rounded-button outline-none"
              >
                <span className="absolute left-0 top-1/2 -translate-y-1/2">
                  <ClockIcon />
                </span>
                <span
                  className={clsx(
                    "pl-6 py-2 text-sm outline-none whitespace-nowrap",
                    !state.searchTime.time && "text-gray-field"
                  )}
                >
                  {state.searchTime.time ? (
                    <span>
                      {dayjs(state.searchTime.time.from, "HH:mm").format(hourFormat)} -{" "}
                      {dayjs(state.searchTime.time.to, "HH:mm").format(hourFormat)}
                    </span>
                  ) : (
                    t("time")
                  )}
                </span>
              </Popover.Button>
              {!isMobile &&
                isDomReady && (
                <Popover.Panel className="absolute z-[9] left-0 md:left-auto top-0 md:top-14 md:rounded-button bg-white drop-shadow-xl md:px-5 md:pt-5 pb-5 px-4 pt-20 min-w-full md:min-w-[326px]">
                  {renderTimeSelectPanel({ withButton })}
                </Popover.Panel>
              )}
            </Popover>
            {withButton && (
              <div className="shrink-0">
                <Button
                  onClick={() => handleSearch({ replace: false })}
                  size="small"
                  color="black"
                >
                  <Translate value="search" />
                </Button>
              </div>
            )}
          </div>
        )}
      </SearchFieldCore>
    </div>
  );
};
