"use client";
import fetchData from "@/api/fetch-data";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useCurrency } from "@/stores/currency-state";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useLocale } from "next-intl";
import { useEffect, useState } from "react";

export default function CurrencySwitcherRedesignThree({ profile }) {
  const locale = useLocale();
  const { currency, setCurrency, setCurrencyShortname, setRate } =
    useCurrency();
  const [currencies, setCurrencies] = useState([]);
  const queryClient = useQueryClient();
  const [togglePending, setTogglePending] = useState(false);

  const { data } = useQuery({
    queryKey: ["currencies", locale],
    queryFn: () => fetchData({ endPoint: "/currencies" }),
    enabled: !currency,
  });

  async function toggleCurrencies(id) {
    if (profile) {
      await fetchData({ endPoint: `/user/currency/${id}` });
      queryClient.refetchQueries({ queryKey: ["/cart/items"] });
    }
  }

  useEffect(() => {
    setCurrencies(data?.data);
    const initialCurrency =
      data?.data?.find((item) => item.is_default == "1") ??
      data?.data?.length > 0
        ? data?.data[0]
        : null;
    if (initialCurrency) {
      setCurrency(initialCurrency.code);
      setCurrencyShortname(initialCurrency.shortname);
      setRate(Number(initialCurrency.rate));
      toggleCurrencies(initialCurrency.id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data?.data]);

  return (
    <Select
      dir={locale == "en" ? "ltr" : "rtl"}
      value={currency}
      disabled={togglePending}
      onValueChange={(value) => {
        setTogglePending(true);
        const selectedCurrency = currencies?.find(
          (item) => item.code === value
        );
        setCurrency(selectedCurrency.code);
        setCurrencyShortname(selectedCurrency.shortname);
        toggleCurrencies(selectedCurrency.id);
        setRate(Number(selectedCurrency.rate));
        setTogglePending(false);
      }}
    >
      <SelectTrigger className=" text-lg hover:text-secondary text-white border-none bg-transparent w-fit focus:ring-0 focus:ring-transparent focus:ring-offset-0">
        <SelectValue />
      </SelectTrigger>
      <SelectContent className="z-[101] min-w-60">
        {currencies?.map((item) => (
          <SelectItem value={item.code} key={item.id} className="text-lg">
            <p>{item.name || item.code}</p>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
