"use client";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useCurrency } from "@/stores/currency-state";
import { useLocale } from "next-intl";
import { useEffect, useState } from "react";
import FallbackImage from "./FallbackImage";

export default function CurrencySwitcher({ response }) {
  const locale = useLocale();
  const { currency, setCurrency, setCurrencyShortname, setRate } =
    useCurrency();
  const [currencies, setCurrencies] = useState([]);

  useEffect(() => {
    if (response?.data) {
      if (!currency) {
        setCurrencies(response?.data);
        const initialCurrency = response?.data.find((item) => item.is_default == '1') ?? response?.data[0];
        setCurrency(initialCurrency.code);
        setCurrencyShortname(initialCurrency.shortname);
        setRate(Number(initialCurrency.rate));
      }
    }
  }, [currency, response?.data, response.status, setCurrency, setCurrencyShortname, setRate]);

  return (
    <Select
      dir={locale == "en" ? "ltr" : "rtl"}
      value={currency}
      onValueChange={(value) => {
        const selectedCurrency = currencies?.find(
          (item) => item.code === value
        );
        setCurrency(selectedCurrency.code);
        setCurrencyShortname(selectedCurrency.shortname);
        setRate(Number(selectedCurrency.rate));
      }}
    >
      <SelectTrigger className="p-0 gap-0 border-none text-xs bg-transparent hover:text-main focus:ring-0 focus:ring-transparent focus:ring-offset-0">
        <SelectValue />
      </SelectTrigger>
      <SelectContent className="w-[100px] z-[101]">
        {currencies?.map((item) => (
          <SelectItem value={item.code} key={item.id}>
            <div className="flex items-center gap-2 hover:text-main">
              <FallbackImage
                src={item.flag}
                width={20}
                height={20}
                alt={item.name}
                className=""
              />
              {item.shortname}
            </div>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}