import {
    AlertTriangle,
    CalendarDays,
    Minus,
    ShieldCheck,
    Target,
    TrendingDown,
    TrendingUp,
} from 'lucide-react';
import { GrowthScoreSparkline } 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 { cn } from '@/lib/utils';
import type { GrowthAnalysis, GrowthTransition } from '@/types/growth-score';

function trendLabel(trend: string): string {
    return trend.replaceAll('_', ' ');
}

function trendPresentation(trend: string): {
    icon: typeof TrendingUp;
    className: string;
    wordClassName: string;
    summary: string;
} {
    if (trend === 'improving') {
        return {
            icon: TrendingUp,
            className:
                'border-emerald-500/40 bg-emerald-500/15 text-emerald-700 dark:text-emerald-400',
            wordClassName: 'text-emerald-600 dark:text-emerald-400',
            summary:
                'The overall 0–100 score sits above 55, which we classify as improving.',
        };
    }

    if (trend === 'declining') {
        return {
            icon: TrendingDown,
            className:
                'border-red-500/40 bg-red-500/15 text-red-700 dark:text-red-400',
            wordClassName: 'text-red-600 dark:text-red-400',
            summary:
                'The overall 0–100 score sits below 45, which we classify as declining.',
        };
    }

    if (trend === 'stable') {
        return {
            icon: Minus,
            className:
                'border-amber-500/40 bg-amber-500/15 text-amber-800 dark:text-amber-400',
            wordClassName: 'text-amber-700 dark:text-amber-400',
            summary:
                'The overall 0–100 score is between 45 and 55, which we classify as stable.',
        };
    }

    return {
        icon: Minus,
        className: 'border-border bg-muted text-muted-foreground',
        wordClassName: 'text-muted-foreground',
        summary:
            'Not enough comparable years to classify a trend. Adjacent years without gaps are required.',
    };
}

function TrendOutlook({
    analysis,
    scoredTransitions,
}: {
    analysis: GrowthAnalysis;
    scoredTransitions: GrowthTransition[];
}) {
    const latestScored =
        scoredTransitions[scoredTransitions.length - 1] ?? null;
    const previousScored =
        scoredTransitions[scoredTransitions.length - 2] ?? null;
    const scoreDelta =
        latestScored && previousScored
            ? (latestScored.growth_score ?? 0) -
              (previousScored.growth_score ?? 0)
            : null;
    const MomentumIcon =
        scoreDelta === null || Math.abs(scoreDelta) < 1
            ? Minus
            : scoreDelta > 0
              ? TrendingUp
              : TrendingDown;
    const momentumLabel =
        scoreDelta === null
            ? latestScored
                ? 'Baseline established'
                : 'Awaiting scored history'
            : Math.abs(scoreDelta) < 1
              ? 'Momentum stable'
              : scoreDelta > 0
                ? 'Momentum improving'
                : 'Momentum weakening';
    const momentumClass =
        scoreDelta === null || Math.abs(scoreDelta) < 1
            ? 'text-muted-foreground'
            : scoreDelta > 0
              ? 'text-emerald-600 dark:text-emerald-400'
              : 'text-red-600 dark:text-red-400';
    const currentScore = analysis.growth_score;
    const milestoneLabel =
        currentScore === null
            ? 'Need scored history'
            : currentScore > 55
              ? 'Above improving threshold'
              : currentScore >= 45
                ? `${(55 - currentScore).toFixed(1)} points to improving`
                : `${(45 - currentScore).toFixed(1)} points to stable`;
    const coverageNeedsReview =
        analysis.data_quality.has_sign_flips ||
        analysis.data_quality.missing_years.length > 0;
    const coverageLabel = coverageNeedsReview
        ? 'Review data quality'
        : analysis.metrics.scored_transition_count >= 2
          ? 'Strong signal'
          : 'Limited history';
    const CoverageIcon = coverageNeedsReview ? AlertTriangle : ShieldCheck;

    return (
        <div className="mt-auto space-y-3 border-t pt-4">
            <div className="flex items-center justify-between gap-3">
                <p className="text-sm font-semibold">Trend outlook</p>
                {latestScored && (
                    <Badge variant="secondary" className="gap-1">
                        <CalendarDays className="size-3.5" />
                        {latestScored.from_year} → {latestScored.to_year}
                    </Badge>
                )}
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
                <div className="rounded-xl border bg-card/80 p-3">
                    <div className="flex items-center gap-2">
                        <MomentumIcon className={cn('size-4', momentumClass)} />
                        <p className="text-xs font-medium text-muted-foreground">
                            Momentum signal
                        </p>
                    </div>
                    <p
                        className={cn(
                            'mt-2 text-sm font-semibold',
                            momentumClass,
                        )}
                    >
                        {momentumLabel}
                    </p>
                </div>
                <div className="rounded-xl border bg-card/80 p-3">
                    <div className="flex items-center gap-2">
                        <Target className="size-4 text-primary" />
                        <p className="text-xs font-medium text-muted-foreground">
                            Next milestone
                        </p>
                    </div>
                    <p className="mt-2 text-sm font-semibold">
                        {milestoneLabel}
                    </p>
                </div>
            </div>

            <div className="flex items-center justify-between gap-3 rounded-xl border bg-muted/30 p-3">
                <div className="flex items-center gap-2">
                    <CoverageIcon
                        className={cn(
                            'size-4',
                            coverageNeedsReview
                                ? 'text-amber-600 dark:text-amber-400'
                                : 'text-emerald-600 dark:text-emerald-400',
                        )}
                    />
                    <span className="text-xs font-semibold">
                        Signal coverage
                    </span>
                </div>
                <Badge
                    variant="outline"
                    className={cn(
                        !coverageNeedsReview &&
                            coverageLabel === 'Strong signal' &&
                            'border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400',
                    )}
                >
                    {coverageLabel}
                </Badge>
            </div>
        </div>
    );
}

export function TrendAnalysisCard({
    analysis,
    currency = 'USD',
}: {
    analysis: GrowthAnalysis;
    currency?: string;
}) {
    const latestTransition =
        analysis.transitions.length > 0
            ? analysis.transitions[analysis.transitions.length - 1]
            : null;
    const scoredTransitions = analysis.transitions.filter(
        (transition) => transition.growth_score !== null,
    );
    const trend = trendPresentation(analysis.trend);
    const TrendIcon = trend.icon;
    const latestRevenueClass =
        (latestTransition?.revenue_growth_pct ?? 0) < 0
            ? 'text-red-600 dark:text-red-400'
            : (latestTransition?.revenue_growth_pct ?? 0) > 0
              ? 'text-emerald-600 dark:text-emerald-400'
              : 'text-foreground';
    const latestIncomeClass =
        (latestTransition?.net_income_growth_pct ?? 0) < 0
            ? 'text-red-600 dark:text-red-400'
            : (latestTransition?.net_income_growth_pct ?? 0) > 0
              ? 'text-emerald-600 dark:text-emerald-400'
              : 'text-foreground';

    return (
        <Card className="h-full overflow-hidden shadow-sm">
            <CardHeader>
                <div className="flex items-start justify-between gap-3">
                    <CardTitle className="text-xl font-bold tracking-tight">
                        Trend
                    </CardTitle>
                    <div
                        className={cn(
                            'flex size-11 shrink-0 items-center justify-center rounded-xl border',
                            trend.className,
                        )}
                    >
                        <TrendIcon className="size-5" />
                    </div>
                </div>
            </CardHeader>
            <CardContent className="flex flex-1 flex-col gap-4">
                <div>
                    <p
                        className={cn(
                            'text-3xl font-bold tracking-tight capitalize md:text-4xl',
                            trend.wordClassName,
                        )}
                    >
                        {trendLabel(analysis.trend)}
                    </p>
                    <p className="mt-1 text-sm text-muted-foreground">
                        {trend.summary}
                    </p>
                </div>

                <GrowthScoreSparkline analysis={analysis} />

                <div className="grid grid-cols-2 gap-3">
                    <div className="rounded-xl border bg-muted/40 px-3 py-2">
                        <p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
                            Latest revenue
                        </p>
                        <p
                            className={cn(
                                'mt-1 text-lg font-semibold',
                                latestRevenueClass,
                            )}
                        >
                            {formatPercent(
                                latestTransition?.revenue_growth_pct ?? null,
                            )}
                        </p>
                    </div>
                    <div className="rounded-xl border bg-muted/40 px-3 py-2">
                        <p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
                            Latest net income
                        </p>
                        <p
                            className={cn(
                                'mt-1 text-lg font-semibold',
                                latestIncomeClass,
                            )}
                        >
                            {latestTransition?.net_income_growth_pct === null &&
                            latestTransition?.net_income_delta !== null
                                ? formatMoney(
                                      latestTransition.net_income_delta,
                                      currency,
                                  )
                                : formatPercent(
                                      latestTransition?.net_income_growth_pct ??
                                          null,
                                  )}
                        </p>
                    </div>
                </div>

                <TrendOutlook
                    analysis={analysis}
                    scoredTransitions={scoredTransitions}
                />
            </CardContent>
        </Card>
    );
}
