import {
    Line,
    LineChart,
    PolarAngleAxis,
    PolarGrid,
    Radar,
    RadarChart,
    Tooltip,
    XAxis,
    YAxis,
} from 'recharts';
import { InfoButton } from '@/components/grow-better/help-tip';
import { ChartContainer, ChartTooltipContent } from '@/components/ui/chart';
import type {
    GrowBetterAlert,
    GrowBetterAssessment,
    GrowBetterHelp,
    GrowBetterTrendPoint,
} from '@/types/grow-better';

const trendConfig = {
    score: { label: 'Your score', color: 'var(--chart-1)' },
    prior: { label: 'Prior period', color: 'var(--muted-foreground)' },
};

const radarConfig = {
    score: { label: 'Pillar score', color: 'var(--chart-1)' },
};

function radarLabel(name: string): string {
    return name
        .replace(' Management', '')
        .replace(' Growth', '')
        .replace('Customer & ', '');
}

export function GrowBetterTrajectory({
    assessment,
    trend,
    historyPending,
    fixHelp,
}: {
    assessment: GrowBetterAssessment;
    trend: GrowBetterTrendPoint[];
    historyPending: boolean;
    fixHelp: GrowBetterHelp;
}) {
    const movement =
        trend.length > 1
            ? trend[trend.length - 1].score - trend[0].score
            : null;
    const radar = assessment.pillars
        .filter((pillar) => pillar.weight > 0)
        .map((pillar) => ({
            name: radarLabel(pillar.name),
            score: pillar.display_score ?? 0,
        }));

    return (
        <div className="grid gap-4 lg:grid-cols-2">
            <section className="rounded-xl border p-5">
                <div className="mb-4 flex items-start justify-between gap-3">
                    <div>
                        <h3 className="text-sm font-semibold">
                            Growth Score Trend
                        </h3>
                        <p className="text-xs text-muted-foreground">
                            Recent months, compared with the prior month
                        </p>
                    </div>
                    <p className="text-xs font-semibold text-emerald-600 dark:text-emerald-400">
                        {movement === null
                            ? 'Building history'
                            : `${movement >= 0 ? '↑' : '↓'} ${movement > 0 ? '+' : ''}${movement} in view`}
                    </p>
                </div>
                {trend.length === 0 ? (
                    <p className="flex h-56 items-center text-sm text-muted-foreground">
                        A score point is saved each month this page is opened.
                    </p>
                ) : (
                    <ChartContainer
                        config={trendConfig}
                        className="aspect-auto h-56"
                    >
                        <LineChart data={trend}>
                            <XAxis
                                dataKey="label"
                                tickLine={false}
                                axisLine={false}
                            />
                            <YAxis
                                tickLine={false}
                                axisLine={false}
                                width={36}
                            />
                            <Tooltip content={<ChartTooltipContent />} />
                            <Line
                                dataKey="score"
                                name="Your score"
                                stroke="var(--color-score)"
                                strokeWidth={2}
                                dot={false}
                                type="monotone"
                            />
                            <Line
                                dataKey="prior"
                                name="Prior period"
                                stroke="var(--color-prior)"
                                strokeDasharray="4 4"
                                strokeWidth={1.5}
                                dot={false}
                                connectNulls={false}
                            />
                        </LineChart>
                    </ChartContainer>
                )}
                {historyPending && (
                    <p className="mt-3 text-xs text-muted-foreground">
                        Earlier months are still being scored.
                    </p>
                )}
            </section>
            <section className="rounded-xl border p-5">
                <h3 className="mb-4 flex items-center gap-1.5 text-sm font-semibold">
                    What to Fix Next
                    <InfoButton
                        title="What to Fix Next"
                        help={fixHelp}
                        direction="higher"
                    />
                </h3>
                {assessment.actions.length === 0 ? (
                    <p className="text-sm text-muted-foreground">
                        Add KPI values to see the biggest opportunities.
                    </p>
                ) : (
                    <ol>
                        {assessment.actions.map((action) => (
                            <li
                                key={action.key}
                                className="flex items-center gap-3 border-b py-3 last:border-b-0"
                            >
                                <span className="w-5 text-center text-xs font-semibold text-muted-foreground tabular-nums">
                                    {action.rank}
                                </span>
                                <div className="min-w-0">
                                    <p className="flex items-center gap-1 text-sm font-medium">
                                        {action.name}
                                        <InfoButton
                                            title={action.name}
                                            help={action.help}
                                            direction={action.direction}
                                        />
                                    </p>
                                    <p className="text-xs text-muted-foreground">
                                        {action.pillar} · now {action.display}
                                    </p>
                                </div>
                                <span className="ml-auto text-xs font-semibold text-emerald-600 tabular-nums dark:text-emerald-400">
                                    +{action.gain} pts
                                </span>
                            </li>
                        ))}
                    </ol>
                )}
            </section>
            <section className="rounded-xl border p-5">
                <h3 className="text-sm font-semibold">Pillar Balance</h3>
                <p className="mb-4 text-xs text-muted-foreground">
                    Where you&apos;re strong vs where to invest
                </p>
                {radar.length === 0 ? (
                    <p className="text-sm text-muted-foreground">
                        Turn a pillar weight above zero to see the balance.
                    </p>
                ) : (
                    <ChartContainer
                        config={radarConfig}
                        className="aspect-auto h-56"
                    >
                        <RadarChart data={radar}>
                            <PolarGrid />
                            <PolarAngleAxis dataKey="name" />
                            <Tooltip content={<ChartTooltipContent />} />
                            <Radar
                                dataKey="score"
                                name="Pillar score"
                                stroke="var(--color-score)"
                                fill="var(--color-score)"
                                fillOpacity={0.15}
                            />
                        </RadarChart>
                    </ChartContainer>
                )}
            </section>
            <section className="rounded-xl border p-5">
                <h3 className="mb-2 text-sm font-semibold">Smart Alerts</h3>
                <ul>
                    {assessment.alerts.map((alert) => (
                        <AlertRow
                            key={`${alert.tone}-${alert.text}`}
                            alert={alert}
                        />
                    ))}
                </ul>
            </section>
        </div>
    );
}

function AlertRow({ alert }: { alert: GrowBetterAlert }) {
    const tone = {
        red: 'bg-destructive',
        amber: 'bg-amber-500',
        green: 'bg-emerald-500',
    }[alert.tone];

    return (
        <li className="flex items-start gap-3 border-b py-3 last:border-b-0">
            <span className={`mt-1 size-2 shrink-0 rounded-full ${tone}`} />
            <div>
                <p className="text-sm">{alert.text}</p>
                <p className="text-[11px] text-muted-foreground">
                    {alert.context}
                </p>
            </div>
        </li>
    );
}
