"use client";

import { useEffect, useState } from "react";
import useAddressStore from "@/global-store/address";
import LocationIcon from "@/assets/icons/location";
import { useMediaQuery } from "@/hook/use-media-query";
import { useT } from "@/context/translation-map";
import { Button } from "@/components/button";
import { usePathname } from "next/navigation";
import { getCookie, setCookie } from "cookies-next";

const CountryIndicator = () => {
  const t = useT();
  const [mounted, setMounted] = useState(false);
  const [showDialog, setShowDialog] = useState(false);
  const { openCountrySelectModal, city, area } = useAddressStore();
  const isMobile = useMediaQuery("(max-width: 1024px)");
  const pathname = usePathname();
  const locationTitle = area?.translation?.title || city?.translation?.title;

  useEffect(() => {
    setMounted(true);
    setShowDialog(getCookie("showCountryDialog") !== false);
  }, []);

  useEffect(() => {
    setCookie("showCountryDialog", showDialog);
  }, [showDialog]);

  if (!mounted || !city || isMobile) return null;

  return (
    <div className="relative">
      <button
        onClick={openCountrySelectModal}
        className="border border-footerBg px-4 py-2 rounded-button"
      >
        <div className="flex flex-row items-center gap-x-2">
          <LocationIcon />
          {locationTitle && (
            <span className="font-medium">{locationTitle}</span>
          )}
        </div>
      </button>
      {showDialog && pathname === "/" && (
        <div className="absolute dropdown-shadow bg-white px-4 py-5 max-w-[460px] w-96 rounded-button mt-2">
          <p className="font-medium text-sm mb-5">
            {`${t("showing.items.for.city")} ${locationTitle}. ${t(
              "change.city.to.see.other.items"
            )}`}
          </p>
          <div className="flex items-center justify-end gap-3">
            <Button
              color="white"
              size="small"
              className="border border-footerBg"
              onClick={() => setShowDialog(false)}
            >
              {t("dismiss")}
            </Button>
            <Button
              color="black"
              size="small"
              onClick={() => {
                setShowDialog(false);
                openCountrySelectModal();
              }}
            >
              {t("change.address")}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

export default CountryIndicator;
