import { getCurrencyRate } from "@/lib/currency-scraper" import { formatCurrency } from "@/lib/utils" import { format, startOfDay } from "date-fns" import { Loader2 } from "lucide-react" import { useEffect, useState } from "react" export const FormConvertCurrency = ({ originalTotal, originalCurrencyCode, targetCurrencyCode, date, onChange, }: { originalTotal: number originalCurrencyCode: string targetCurrencyCode: string date?: Date | undefined onChange?: (value: number) => void }) => { if ( originalTotal === 0 || !originalCurrencyCode || !targetCurrencyCode || originalCurrencyCode === targetCurrencyCode ) { return <>> } const normalizedDate = startOfDay(date || new Date(Date.now() - 24 * 60 * 60 * 1000)) const [exchangeRate, setExchangeRate] = useState(0) const [isLoading, setIsLoading] = useState(false) useEffect(() => { const fetchData = async () => { try { setIsLoading(true) const exchangeRate = await getCurrencyRate(originalCurrencyCode, targetCurrencyCode, normalizedDate) setExchangeRate(exchangeRate) onChange?.(originalTotal * exchangeRate) } catch (error) { console.error("Error fetching currency rates:", error) setExchangeRate(0) onChange?.(0) } finally { setIsLoading(false) } } fetchData() }, [originalCurrencyCode, targetCurrencyCode, format(normalizedDate, "LLLL-mm-dd")]) return (