import { useState } from 'react';
import {
    Area,
    AreaChart,
    Bar,
    BarChart,
    CartesianGrid,
    PolarAngleAxis,
    RadialBar,
    RadialBarChart,
    ReferenceLine,
    Tooltip,
    XAxis,
    YAxis,
} from 'recharts';
import { ChartContainer, ChartTooltipContent } from '@/components/ui/chart';
import type { ChartConfig } from '@/components/ui/chart';
import type { GrowthAnalysis } from '@/types/growth-score';

const financialChartConfig = {
    revenue: {
        label: 'Revenue',
        color: 'var(--chart-1)',
    },
    netIncome: {
        label: 'Net income',
        color: 'var(--chart-2)',
    },
} satisfies ChartConfig;

const scoreRadialConfig = {
    score: {
        label: 'Growth Score',
        color: 'var(--chart-1)',
    },
} satisfies ChartConfig;

const trendChartConfig = {
    score: {
        label: 'Growth Score',
        color: 'var(--chart-1)',
    },
} satisfies ChartConfig;

export function GrowthScoreRadial({
    score,
    color = 'var(--chart-1)',
}: {
    score: number | null;
    color?: string;
}) {
    const value = score ?? 0;

    return (
        <div className="relative mx-auto w-full max-w-44 shrink-0">
            <ChartContainer
                config={{
                    ...scoreRadialConfig,
                    score: { ...scoreRadialConfig.score, color },
                }}
                className="aspect-auto h-44 w-full max-w-44"
                aria-label={
                    score === null
                        ? 'Growth score is not available'
                        : `Growth score ${score} out of 100`
                }
            >
                <RadialBarChart
                    data={[{ score: value }]}
                    innerRadius="68%"
                    outerRadius="92%"
                    startAngle={90}
                    endAngle={-270}
                    barSize={14}
                >
                    <PolarAngleAxis
                        type="number"
                        domain={[0, 100]}
                        angleAxisId={0}
                        tick={false}
                    />
                    <RadialBar
                        dataKey="score"
                        background
                        cornerRadius={12}
                        fill="var(--color-score)"
                    />
                </RadialBarChart>
            </ChartContainer>
            <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
                <span className="text-3xl font-bold tracking-tight">
                    {score === null ? '—' : score.toFixed(1)}
                </span>
                <span className="text-xs text-muted-foreground">
                    out of 100
                </span>
            </div>
        </div>
    );
}

export function GrowthScoreSparkline({
    analysis,
}: {
    analysis: GrowthAnalysis;
}) {
    const data = analysis.transitions
        .filter((transition) => transition.growth_score !== null)
        .map((transition) => ({
            period: `${transition.from_year}–${transition.to_year}`,
            score: transition.growth_score ?? 0,
        }));

    if (data.length === 0) {
        return (
            <div className="flex h-20 items-center justify-center rounded-lg bg-muted/40 text-xs text-muted-foreground">
                Need more history
            </div>
        );
    }

    return (
        <ChartContainer
            config={trendChartConfig}
            className="aspect-auto h-20 w-full"
            aria-label="Recent growth score sparkline"
        >
            <AreaChart
                data={data}
                margin={{ top: 8, right: 2, bottom: 2, left: 2 }}
            >
                <defs>
                    <linearGradient
                        id="trendSparkFill"
                        x1="0"
                        y1="0"
                        x2="0"
                        y2="1"
                    >
                        <stop
                            offset="5%"
                            stopColor="var(--color-score)"
                            stopOpacity={0.3}
                        />
                        <stop
                            offset="95%"
                            stopColor="var(--color-score)"
                            stopOpacity={0}
                        />
                    </linearGradient>
                </defs>
                <Area
                    type="monotone"
                    dataKey="score"
                    stroke="var(--color-score)"
                    fill="url(#trendSparkFill)"
                    strokeWidth={2.5}
                    dot={false}
                />
            </AreaChart>
        </ChartContainer>
    );
}

export function GrowthScoreCharts({
    analysis,
    currency = 'USD',
}: {
    analysis: GrowthAnalysis;
    currency?: string;
}) {
    const scoreData = analysis.transitions
        .filter((transition) => transition.growth_score !== null)
        .map((transition) => ({
            period: `${transition.from_year}–${transition.to_year}`,
            score: transition.growth_score ?? 0,
        }));
    const financialData = analysis.years.map((year) => ({
        year: String(year.year),
        revenue: year.revenue,
        netIncome: year.net_income,
    }));
    const [view, setView] = useState<'score' | 'financials'>('score');
    const currencyFormatter = new Intl.NumberFormat(undefined, {
        style: 'currency',
        currency,
        notation: 'compact',
        maximumFractionDigits: 1,
    });

    return (
        <section className="rounded-2xl border bg-card p-4 shadow-sm md:p-6">
            <div className="mb-5 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                <div>
                    <p className="text-xs font-semibold tracking-widest text-primary uppercase">
                        Performance analytics
                    </p>
                    <h3 className="mt-1 text-lg font-semibold">
                        See what is driving the score
                    </h3>
                    <p className="mt-1 text-sm text-muted-foreground">
                        Explore score momentum and the underlying financial
                        history.
                    </p>
                </div>
                <div
                    className="flex rounded-lg border bg-muted/40 p-1"
                    role="tablist"
                >
                    {[
                        ['score', 'Score trend'],
                        ['financials', 'Financials'],
                    ].map(([key, label]) => (
                        <button
                            key={key}
                            type="button"
                            role="tab"
                            aria-selected={view === key}
                            onClick={() =>
                                setView(key as 'score' | 'financials')
                            }
                            className={`rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${
                                view === key
                                    ? 'bg-background text-foreground shadow-sm'
                                    : 'text-muted-foreground hover:text-foreground'
                            }`}
                        >
                            {label}
                        </button>
                    ))}
                </div>
            </div>

            {view === 'score' &&
                (scoreData.length === 0 ? (
                    <div className="flex h-64 items-center justify-center rounded-xl bg-muted/40 text-center text-sm text-muted-foreground">
                        Comparable year-to-year scores are not available yet.
                    </div>
                ) : (
                    <ChartContainer
                        config={trendChartConfig}
                        className="aspect-auto h-72 w-full"
                        aria-label="Growth score trend chart"
                    >
                        <AreaChart
                            data={scoreData}
                            margin={{ left: 8, right: 8 }}
                        >
                            <defs>
                                <linearGradient
                                    id="scoreFill"
                                    x1="0"
                                    y1="0"
                                    x2="0"
                                    y2="1"
                                >
                                    <stop
                                        offset="5%"
                                        stopColor="var(--color-score)"
                                        stopOpacity={0.35}
                                    />
                                    <stop
                                        offset="95%"
                                        stopColor="var(--color-score)"
                                        stopOpacity={0.02}
                                    />
                                </linearGradient>
                            </defs>
                            <CartesianGrid vertical={false} />
                            <XAxis
                                dataKey="period"
                                tickLine={false}
                                axisLine={false}
                            />
                            <YAxis
                                domain={[0, 100]}
                                ticks={[0, 25, 50, 75, 100]}
                                tickLine={false}
                                axisLine={false}
                            />
                            <ReferenceLine
                                y={55}
                                stroke="var(--chart-2)"
                                strokeDasharray="4 4"
                            />
                            <ReferenceLine
                                y={45}
                                stroke="var(--chart-3)"
                                strokeDasharray="4 4"
                            />
                            <Tooltip
                                content={
                                    <ChartTooltipContent
                                        valueFormatter={(value) =>
                                            `${Number(value).toFixed(1)} / 100`
                                        }
                                    />
                                }
                            />
                            <Area
                                type="monotone"
                                dataKey="score"
                                name="Growth Score"
                                stroke="var(--color-score)"
                                fill="url(#scoreFill)"
                                strokeWidth={3}
                                dot={{ fill: 'var(--color-score)', r: 4 }}
                            />
                        </AreaChart>
                    </ChartContainer>
                ))}

            {view === 'financials' &&
                (financialData.length === 0 ? (
                    <div className="flex h-64 items-center justify-center rounded-xl bg-muted/40 text-center text-sm text-muted-foreground">
                        No financial history is available yet.
                    </div>
                ) : (
                    <ChartContainer
                        config={financialChartConfig}
                        className="aspect-auto h-72 w-full"
                        aria-label="Revenue and net income by year"
                    >
                        <BarChart
                            data={financialData}
                            margin={{ left: 8, right: 8 }}
                        >
                            <CartesianGrid vertical={false} />
                            <XAxis
                                dataKey="year"
                                tickLine={false}
                                axisLine={false}
                            />
                            <YAxis
                                tickLine={false}
                                axisLine={false}
                                tickFormatter={currencyFormatter.format}
                            />
                            <Tooltip
                                content={
                                    <ChartTooltipContent
                                        valueFormatter={(value) =>
                                            currencyFormatter.format(
                                                Number(value),
                                            )
                                        }
                                    />
                                }
                            />
                            <Bar
                                dataKey="revenue"
                                name="Revenue"
                                fill="var(--color-revenue)"
                                radius={[4, 4, 0, 0]}
                            />
                            <Bar
                                dataKey="netIncome"
                                name="Net income"
                                fill="var(--color-netIncome)"
                                radius={[4, 4, 0, 0]}
                            />
                        </BarChart>
                    </ChartContainer>
                ))}
        </section>
    );
}
