import { GrowthDashboardBackdrop } from '@/components/growth-score/growth-dashboard-backdrop';
import { GrowthScoreRadial } from '@/components/growth-score/growth-score-charts';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { formatMoney, formatPercent } from '@/lib/growth-format';
import { GRADE_LABELS, GRADE_STYLES, isGrowthGrade } from '@/lib/growth-grade';
import { cn } from '@/lib/utils';
import type { GrowthAnalysis } from '@/types/growth-score';

function MomentumCard({
    label,
    value,
    fallback,
}: {
    label: string;
    value: number | null;
    fallback: string;
}) {
    const isPositive = value !== null && value > 0;
    const isNegative = value !== null && value < 0;
    const status = isPositive
        ? 'Growing'
        : isNegative
          ? 'Declining'
          : 'Needs context';

    return (
        <div className="rounded-xl border bg-card/80 p-3">
            <p className="text-xs font-medium text-muted-foreground">{label}</p>
            <div className="mt-2 flex items-end justify-between gap-2">
                <p
                    className={cn(
                        'text-lg font-semibold',
                        isPositive
                            ? 'text-emerald-600 dark:text-emerald-400'
                            : isNegative
                              ? 'text-red-600 dark:text-red-400'
                              : 'text-muted-foreground',
                    )}
                >
                    {value === null ? fallback : formatPercent(value)}
                </p>
                <Badge
                    variant="outline"
                    className={cn(
                        'text-[10px] font-semibold',
                        isPositive &&
                            'border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400',
                        isNegative &&
                            'border-red-500/40 bg-red-500/10 text-red-700 dark:text-red-400',
                    )}
                >
                    {status}
                </Badge>
            </div>
        </div>
    );
}

export function GrowthScoreSummaryCard({
    analysis,
    currency = 'USD',
}: {
    analysis: GrowthAnalysis;
    currency?: string;
}) {
    const grade = isGrowthGrade(analysis.grade) ? analysis.grade : null;
    const scoreColor =
        analysis.trend === 'declining'
            ? 'var(--destructive)'
            : analysis.trend === 'improving'
              ? 'var(--chart-2)'
              : 'var(--chart-1)';

    return (
        <Card className="relative h-full overflow-hidden border-primary/20 shadow-sm">
            <GrowthDashboardBackdrop className="opacity-70" />
            <CardHeader className="relative">
                <CardTitle className="text-xl font-bold tracking-tight">
                    Growth Score
                </CardTitle>
            </CardHeader>
            <CardContent className="relative flex flex-1 flex-col gap-5">
                <div className="flex items-center gap-4">
                    <GrowthScoreRadial
                        score={analysis.growth_score}
                        color={scoreColor}
                    />
                    <div className="min-w-0">
                        <div
                            className={cn(
                                'flex size-14 items-center justify-center rounded-xl border text-3xl font-extrabold',
                                grade
                                    ? GRADE_STYLES[grade]
                                    : 'border-border bg-muted text-muted-foreground',
                            )}
                        >
                            {grade ?? '—'}
                        </div>
                        <p className="mt-2 text-sm font-semibold">
                            {grade ? GRADE_LABELS[grade] : 'No grade yet'}
                        </p>
                    </div>
                </div>

                <div className="space-y-2">
                    <div className="flex justify-between text-xs text-muted-foreground">
                        <span>Score weighting</span>
                        <span>60 / 40</span>
                    </div>
                    <div
                        className="flex h-2 overflow-hidden rounded-full bg-muted"
                        aria-label="Revenue 60 percent, net income 40 percent"
                    >
                        <div className="w-3/5 bg-primary" />
                        <div className="w-2/5 bg-foreground/30" />
                    </div>
                    <div className="flex justify-between text-xs text-muted-foreground">
                        <span>Revenue</span>
                        <span>Net income</span>
                    </div>
                </div>

                <div className="grid gap-3 sm:grid-cols-2">
                    <MomentumCard
                        label="Revenue momentum"
                        value={analysis.metrics.revenue_growth_pct}
                        fallback="No data"
                    />
                    <MomentumCard
                        label="Net income momentum"
                        value={analysis.metrics.net_income_growth_pct}
                        fallback={
                            analysis.metrics.net_income_delta !== null
                                ? formatMoney(
                                      analysis.metrics.net_income_delta,
                                      currency,
                                  )
                                : 'No data'
                        }
                    />
                </div>

                <div className="mt-auto space-y-2 rounded-xl border bg-muted/30 p-3">
                    <div className="flex items-center justify-between text-xs font-medium">
                        <span>Score interpretation</span>
                        <span className="text-muted-foreground">
                            0–100 scale
                        </span>
                    </div>
                    <div className="relative pt-1">
                        <div className="flex h-2 overflow-hidden rounded-full">
                            <div className="w-[45%] bg-red-500/70" />
                            <div className="w-[10%] bg-amber-500/70" />
                            <div className="w-[45%] bg-emerald-500/70" />
                        </div>
                        {analysis.growth_score !== null && (
                            <span
                                className="absolute top-0 size-4 -translate-x-1/2 rounded-full border-2 border-background bg-foreground shadow-sm"
                                style={{
                                    left: `${Math.min(
                                        Math.max(analysis.growth_score, 0),
                                        100,
                                    )}%`,
                                }}
                                aria-label={`Current score ${analysis.growth_score} out of 100`}
                            />
                        )}
                    </div>
                    <div className="flex justify-between text-[11px] text-muted-foreground">
                        <span>Declining &lt; 45</span>
                        <span>Stable 45–55</span>
                        <span>Improving &gt; 55</span>
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}
