import React from "react"
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import {
    ChartContainer,
    ChartTooltip,
    ChartTooltipContent,
} from "@/components/ui/chart"
import { ExchangeRateType } from "@/types/dashboard/currency"

type Rates = Record<string, number>

export default function ExchangeRateGraph({
    latest,
    history,
    currency_settings,
}: {
    latest: ExchangeRateType
    history: ExchangeRateType[]
    currency_settings: any
}) {

    // 📌 currencies from settings
    const currencies: string[] = React.useMemo(() => {
        try {
            return JSON.parse(currency_settings.website_currency_types || "[]").map((c: any) => c.code)
        } catch {
            return []
        }
    }, [currency_settings])



    // 🎯 ACTIVE currency (default first)
    const [activeCurrency, setActiveCurrency] = React.useState<string | null>(null)

    React.useEffect(() => {
        if (currencies.length > 0 && !activeCurrency) {
            setActiveCurrency(currencies[0])
        }
    }, [currencies])

    // 📅 sort history
    const sortedHistory = React.useMemo(() => {
        return [...history].sort(
            (a, b) =>
                new Date(a.recorded_at).getTime() -
                new Date(b.recorded_at).getTime()
        )
    }, [history])

    // 📊 chart data
    const chartData = React.useMemo(() => {
        return sortedHistory.map((h) => {
            const row: any = {
                date: h.recorded_at,
            }

            Object.entries(h.rates || {}).forEach(([key, value]) => {
                row[key] = Number(value) || 0
            })

            return row
        })
    }, [sortedHistory])

    // 💰 latest rates
    const latestRates = React.useMemo(() => {
        const normalized: Record<string, number> = {}

        Object.entries(latest?.rates || {}).forEach(([key, value]) => {
            normalized[key] = Number(value) || 0
        })

        return normalized
    }, [latest])

    const chartConfig = React.useMemo(() => {
        if (!activeCurrency) return {}

        return {
            [activeCurrency]: {
                label: activeCurrency,
                color: "var(--chart-1)",
            },
        }
    }, [activeCurrency])

    return (
        <Card className="rounded-sm py-4 sm:py-0">

            {/* HEADER */}
            <CardHeader className="flex flex-col items-stretch border-b p-0 sm:flex-row">

                <div className="flex flex-1 flex-col justify-center gap-1 px-6 pb-3 sm:pb-0">
                    <CardTitle>Exchange Rates</CardTitle>

                    <CardDescription>
                        Base: {latest?.base_currency} |{" "}
                        {new Date(latest?.recorded_at).toLocaleDateString()}
                    </CardDescription>
                </div>

                {/* 🎯 CLICKABLE CURRENCY BUTTONS */}
                <div className="flex">
                    {currencies.map(code => (
                        <button
                            key={code}
                            onClick={() => setActiveCurrency(code)}
                            className={`flex flex-1 flex-col justify-center gap-1 border-t px-6 py-4 text-left sm:border-t-0 sm:border-l
                                ${activeCurrency === code ? "bg-muted/50" : ""}
                            `}
                        >
                            <span className="text-xs text-muted-foreground">
                                {code}
                            </span>
                            <span className="text-lg font-bold sm:text-xl">
                                {Number(latestRates[code] ?? 0).toFixed(4)}
                            </span>
                        </button>
                    ))}
                </div>
            </CardHeader>

            {/* CHART */}
            <CardContent className="px-2 sm:p-6">
                <ChartContainer className="h-64 w-full" config={chartConfig}>

                    <LineChart data={chartData}>
                        <CartesianGrid vertical={false} />

                        <XAxis
                            dataKey="date"
                            tickLine={false}
                            axisLine={false}
                            tickMargin={8}
                            minTickGap={32}
                            tickFormatter={(value) =>
                                new Date(value).toLocaleDateString("en-US", {
                                    month: "short",
                                    day: "numeric",
                                })
                            }
                        />

                        <YAxis
                            tickLine={false}
                            axisLine={false}
                            tickMargin={4}
                            tickFormatter={(value) => value.toFixed(4)}
                        // label={{ value: activeCurrency, angle: -90, position: 'insideLeft' }}
                        />

                        <ChartTooltip
                            content={
                                <ChartTooltipContent
                                    labelFormatter={(value) =>
                                        new Date(value).toLocaleDateString("en-US", {
                                            month: "short",
                                            day: "numeric",
                                            year: "numeric",
                                        })
                                    }
                                />
                            }
                        />

                        {/* 🎯 ONLY ACTIVE CURRENCY */}
                        {activeCurrency && (
                            <Line
                                type="monotone"
                                dataKey={activeCurrency}
                                stroke="var(--chart-1)"
                                strokeWidth={3}
                                dot={false}
                            />
                        )}
                    </LineChart>

                </ChartContainer>
            </CardContent>
        </Card>
    )
}