"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 CurrencySwitcherRedesignTwo({ 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" }),
  });

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

  useEffect(() => {
    try {
      setCurrencies(data?.data);
      const initialCurrency =
        data?.data?.find((item) => item.is_default == "1") ?? data?.data[0];
      setCurrency(initialCurrency.code);
      setCurrencyShortname(initialCurrency.shortname);
      setRate(Number(initialCurrency.rate));
      toggleCurrencies(initialCurrency.id);
    } catch {
      console.error("Failed to fetch currencies");
    }
  }, [data?.data, setCurrency, setCurrencyShortname, setRate]);

  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 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>
  );
}
