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 }) => { const normalizedDate = startOfDay(date || new Date(Date.now() - 24 * 60 * 60 * 1000)) const normalizedDateString = format(normalizedDate, "yyyy-MM-dd") 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, normalizedDateString, originalTotal]) if (!originalTotal || !originalCurrencyCode || !targetCurrencyCode || originalCurrencyCode === targetCurrencyCode) { return <> } return (
{isLoading ? (
Loading exchange rates...
) : (
{formatCurrency(originalTotal * 100, originalCurrencyCode)}
=
{formatCurrency(originalTotal * 100 * exchangeRate, targetCurrencyCode).slice(0, 1)}
onChange?.(parseFloat(e.target.value))} className="w-32 rounded-md border border-input bg-transparent px-1" />
(exchange rate on {format(normalizedDate, "LLLL dd, yyyy")})
)}
) } async function getCurrencyRate(currencyCodeFrom: string, currencyCodeTo: string, date: Date): Promise { try { const formattedDate = format(date, "yyyy-MM-dd") const response = await fetch(`/api/currency?from=${currencyCodeFrom}&to=${currencyCodeTo}&date=${formattedDate}`) if (!response.ok) { const errorData = await response.json() console.error("Currency API error:", errorData.error) return 0 } const data = await response.json() return data.rate } catch (error) { console.error("Error fetching currency rate:", error) return 0 } }