import { Link } from '@inertiajs/react';
import {
    Activity,
    AlertTriangle,
    ArrowRight,
    Bot,
    CheckCircle2,
    Database,
    RefreshCw,
    Sparkles,
    TrendingDown,
    TrendingUp,
} from 'lucide-react';
import { DashboardEmptyState } from '@/components/dashboard/dashboard-empty-state';
import { DashboardKpiCard } from '@/components/dashboard/dashboard-kpi-card';
import {
    GrowthScoreCharts,
    GrowthScoreRadial,
    GrowthScoreSparkline,
} from '@/components/growth-score/growth-score-charts';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { index as agent } from '@/routes/agent';
import {
    mine as growthScore,
    refresh as refreshGrowthScore,
} from '@/routes/growth-score';
import type { DashboardProps } from '@/types/dashboard';
import type { GrowthAnalysis } from '@/types/growth-score';

function money(value: number | null, currency: string): string {
    if (value === null) {
        return '—';
    }

    return new Intl.NumberFormat(undefined, {
        style: 'currency',
        currency,
        notation: 'compact',
        maximumFractionDigits: 1,
    }).format(value);
}

function percent(value: number | null): string {
    if (value === null) {
        return 'No comparison';
    }

    return `${value > 0 ? '+' : ''}${value.toFixed(1)}% vs prior period`;
}

function formatDate(value?: string | null): string {
    if (!value) {
        return 'Not synced yet';
    }

    return new Intl.DateTimeFormat(undefined, {
        dateStyle: 'medium',
        timeStyle: 'short',
    }).format(new Date(value));
}

function trendLabel(trend: string): string {
    return trend === 'insufficient_data' ? 'Awaiting history' : trend;
}

function trendTone(
    trend: string,
): 'positive' | 'warning' | 'negative' | 'neutral' {
    if (trend === 'improving') {
        return 'positive';
    }

    if (trend === 'declining') {
        return 'negative';
    }

    if (trend === 'stable') {
        return 'warning';
    }

    return 'neutral';
}

function HealthCard({ dashboard }: { dashboard: DashboardProps }) {
    const { data_health: health } = dashboard;
    const isHealthy = health.status === 'healthy';
    const HealthIcon = isHealthy ? CheckCircle2 : AlertTriangle;
    const healthClass = isHealthy
        ? 'text-emerald-600 dark:text-emerald-400'
        : health.status === 'error'
          ? 'text-red-600 dark:text-red-400'
          : 'text-amber-600 dark:text-amber-400';

    return (
        <Card className="h-full">
            <CardHeader>
                <div className="flex items-start justify-between gap-3">
                    <div>
                        <CardTitle className="flex items-center gap-2 text-lg">
                            <Database className="size-5 text-primary" />
                            Data health
                        </CardTitle>
                        <CardDescription>
                            Trust signals behind this dashboard.
                        </CardDescription>
                    </div>
                    <HealthIcon className={`size-5 ${healthClass}`} />
                </div>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="flex items-center justify-between gap-3 rounded-xl border bg-muted/30 p-3">
                    <div>
                        <p className="text-xs font-medium text-muted-foreground">
                            Current status
                        </p>
                        <p className="mt-1 font-semibold capitalize">
                            {health.status.replaceAll('_', ' ')}
                        </p>
                    </div>
                    <Badge variant={isHealthy ? 'secondary' : 'outline'}>
                        {health.coverage_years ?? 0} year
                        {(health.coverage_years ?? 0) === 1 ? '' : 's'} covered
                    </Badge>
                </div>
                <dl className="grid gap-3 text-sm sm:grid-cols-2">
                    <div>
                        <dt className="text-muted-foreground">Last synced</dt>
                        <dd className="mt-1 font-medium">
                            {formatDate(health.synced_at)}
                        </dd>
                    </div>
                    <div>
                        <dt className="text-muted-foreground">Data quality</dt>
                        <dd className="mt-1 font-medium">
                            {health.missing_years?.length
                                ? `${health.missing_years.length} gap${health.missing_years.length === 1 ? '' : 's'}`
                                : health.has_sign_flips
                                  ? 'Review sign changes'
                                  : 'No critical flags'}
                        </dd>
                    </div>
                </dl>
                {health.last_error && (
                    <p className="text-sm text-destructive" role="alert">
                        {health.last_error}
                    </p>
                )}
            </CardContent>
        </Card>
    );
}

function ActionCenter({ dashboard }: { dashboard: DashboardProps }) {
    const item =
        dashboard.actions.advice?.critical_must_do?.[0] ??
        dashboard.actions.advice?.areas_needing_focus?.[0];

    return (
        <Card className="h-full border-primary/20 bg-gradient-to-br from-primary/10 via-card to-card">
            <CardHeader>
                <div className="flex items-start justify-between gap-3">
                    <div>
                        <CardTitle className="flex items-center gap-2 text-lg">
                            <Sparkles className="size-5 text-primary" />
                            Next best action
                        </CardTitle>
                        <CardDescription>
                            Turn the latest signals into a practical move.
                        </CardDescription>
                    </div>
                    <Badge variant="outline">
                        {dashboard.actions.has_advice
                            ? 'Advisor ready'
                            : 'Insight'}
                    </Badge>
                </div>
            </CardHeader>
            <CardContent className="flex h-[calc(100%-7rem)] flex-col justify-between gap-5">
                {item ? (
                    <div className="space-y-2">
                        <p className="font-semibold">{item.title}</p>
                        <p className="text-sm leading-relaxed text-muted-foreground">
                            {item.description}
                        </p>
                        <Badge variant="outline" className="capitalize">
                            {item.impact} impact
                        </Badge>
                    </div>
                ) : (
                    <div className="space-y-2">
                        <p className="font-semibold">
                            Ask Monily for a focused plan
                        </p>
                        <p className="text-sm leading-relaxed text-muted-foreground">
                            Generate advisor recommendations grounded in your
                            latest profitability, liquidity, and efficiency
                            signals.
                        </p>
                    </div>
                )}
                <div className="flex flex-wrap gap-2">
                    <Button asChild size="sm">
                        <Link href={growthScore()}>
                            {item ? 'View full analysis' : 'Generate advice'}
                            <ArrowRight />
                        </Link>
                    </Button>
                    <Button asChild size="sm" variant="outline">
                        <Link href={agent()}>
                            <Bot />
                            Ask Monily
                        </Link>
                    </Button>
                </div>
            </CardContent>
        </Card>
    );
}

function ChangeSummary({ analysis }: { analysis: GrowthAnalysis }) {
    const latestTransition = analysis.transitions.at(-1);
    const scoredTransitions = analysis.transitions.filter(
        (transition) => transition.growth_score !== null,
    );
    const best = scoredTransitions.at(-1)?.growth_score ?? null;
    const strongest = scoredTransitions.reduce(
        (current, transition) =>
            (transition.growth_score ?? -Infinity) >
            (current?.growth_score ?? -Infinity)
                ? transition
                : current,
        scoredTransitions[0],
    );

    return (
        <Card>
            <CardHeader>
                <CardTitle className="text-lg">What changed</CardTitle>
                <CardDescription>
                    The clearest signals from your latest comparable period.
                </CardDescription>
            </CardHeader>
            <CardContent className="grid gap-3 sm:grid-cols-3">
                <div className="rounded-xl border bg-muted/30 p-4">
                    <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                        Latest score movement
                    </p>
                    <p className="mt-2 flex items-center gap-2 text-lg font-semibold capitalize">
                        {analysis.trend === 'improving' ? (
                            <TrendingUp className="size-5 text-emerald-600" />
                        ) : (
                            <TrendingDown className="size-5 text-red-600" />
                        )}
                        {trendLabel(analysis.trend)}
                    </p>
                    <p className="mt-1 text-xs text-muted-foreground">
                        {latestTransition
                            ? `${latestTransition.from_year} → ${latestTransition.to_year}`
                            : 'Need adjacent years'}
                    </p>
                </div>
                <div className="rounded-xl border bg-muted/30 p-4">
                    <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                        Strongest period
                    </p>
                    <p className="mt-2 text-lg font-semibold">
                        {strongest
                            ? `${strongest.from_year} → ${strongest.to_year}`
                            : 'Not available'}
                    </p>
                    <p className="mt-1 text-xs text-emerald-600 dark:text-emerald-400">
                        {best === null
                            ? 'Need scored history'
                            : `${best.toFixed(1)} / 100`}
                    </p>
                </div>
                <div className="rounded-xl border bg-muted/30 p-4">
                    <p className="text-xs font-semibold tracking-wide text-muted-foreground uppercase">
                        Data quality
                    </p>
                    <p className="mt-2 text-lg font-semibold">
                        {analysis.data_quality.missing_years.length === 0
                            ? 'Complete coverage'
                            : `${analysis.data_quality.missing_years.length} year gap`}
                    </p>
                    <p className="mt-1 text-xs text-muted-foreground">
                        {analysis.data_quality.has_sign_flips
                            ? 'Sign change needs context'
                            : `${analysis.metrics.coverage_years} years synced`}
                    </p>
                </div>
            </CardContent>
        </Card>
    );
}

export function DashboardOverview({
    dashboard,
}: {
    dashboard: DashboardProps;
}) {
    if (
        !dashboard.connected ||
        !dashboard.company ||
        !dashboard.analysis ||
        !dashboard.summary ||
        dashboard.data_health.status === 'insufficient_history'
    ) {
        return (
            <DashboardEmptyState
                status={dashboard.data_health.status}
                companyName={dashboard.company?.name}
                message={dashboard.data_health.message}
            />
        );
    }

    const { analysis, summary, company } = dashboard;
    const currency = company?.base_currency ?? 'USD';
    const externalCompanyId = company?.external_company_id;
    const refreshAvailable = Boolean(
        externalCompanyId && company?.external_account_type,
    );

    return (
        <div className="flex flex-col gap-6">
            <Card className="overflow-hidden border-primary/20 bg-gradient-to-br from-primary/10 via-card to-card">
                <CardContent className="flex flex-col gap-5 p-5 md:flex-row md:items-center md:justify-between md:p-6">
                    <div className="space-y-2">
                        <div className="flex flex-wrap items-center gap-2">
                            <Badge variant="secondary">{company?.name}</Badge>
                            <Badge variant="outline" className="capitalize">
                                {analysis.account_type ?? 'Accounting'}
                            </Badge>
                            <span className="text-xs text-muted-foreground">
                                Updated {formatDate(analysis.sync.synced_at)}
                            </span>
                        </div>
                        <div>
                            <p className="text-sm font-medium text-primary">
                                Financial command center
                            </p>
                            <h1 className="text-2xl font-bold tracking-tight md:text-3xl">
                                Welcome back. Here’s your business pulse.
                            </h1>
                            <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
                                See what changed, understand why, and move on
                                the highest-impact opportunity.
                            </p>
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-2">
                        {refreshAvailable && (
                            <Button asChild variant="outline">
                                <Link
                                    href={refreshGrowthScore(
                                        externalCompanyId!,
                                    )}
                                    method="post"
                                    as="button"
                                    data={{
                                        account_type:
                                            company.external_account_type,
                                        company_name: company.name,
                                    }}
                                >
                                    <RefreshCw />
                                    Refresh data
                                </Link>
                            </Button>
                        )}
                        <Button asChild>
                            <Link href={growthScore()}>
                                View full score
                                <ArrowRight />
                            </Link>
                        </Button>
                    </div>
                </CardContent>
            </Card>

            {analysis.sync.last_error && (
                <div className="flex items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 p-4 text-sm">
                    <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
                    <div>
                        <p className="font-semibold">
                            Showing the last successful sync
                        </p>
                        <p className="mt-1 text-muted-foreground">
                            {analysis.sync.last_error}
                        </p>
                    </div>
                </div>
            )}

            <section aria-labelledby="dashboard-kpis">
                <div className="sr-only" id="dashboard-kpis">
                    Key financial indicators
                </div>
                <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    <DashboardKpiCard
                        label="Growth score"
                        value={
                            summary.growth_score === null
                                ? '—'
                                : `${summary.growth_score.toFixed(1)} / 100`
                        }
                        detail={`${summary.grade ?? 'No grade'} · ${trendLabel(summary.trend)}`}
                        icon={Activity}
                        tone={trendTone(summary.trend)}
                    />
                    <DashboardKpiCard
                        label="Latest revenue"
                        value={money(summary.latest_revenue, currency)}
                        detail={percent(summary.revenue_growth_pct)}
                        trend={summary.revenue_growth_pct}
                        icon={TrendingUp}
                        tone="primary"
                    />
                    <DashboardKpiCard
                        label="Net income"
                        value={money(summary.latest_net_income, currency)}
                        detail={percent(summary.net_income_growth_pct)}
                        trend={summary.net_income_growth_pct}
                        icon={
                            summary.net_income_growth_pct !== null &&
                            summary.net_income_growth_pct < 0
                                ? TrendingDown
                                : TrendingUp
                        }
                        tone={
                            summary.net_income_growth_pct !== null &&
                            summary.net_income_growth_pct < 0
                                ? 'negative'
                                : 'positive'
                        }
                    />
                    <DashboardKpiCard
                        label="Net margin"
                        value={
                            summary.latest_net_margin === null
                                ? '—'
                                : `${summary.latest_net_margin.toFixed(1)}%`
                        }
                        detail={`${summary.coverage_years} years of history`}
                        icon={Database}
                        tone="neutral"
                    />
                </div>
            </section>

            <div className="grid items-stretch gap-4 xl:grid-cols-[1.1fr_0.9fr]">
                <Card className="overflow-hidden border-primary/20">
                    <CardHeader className="flex flex-row items-start justify-between gap-3">
                        <div>
                            <CardTitle className="flex items-center gap-2 text-xl">
                                <Activity className="size-5 text-primary" />
                                Performance at a glance
                            </CardTitle>
                            <CardDescription>
                                Your score and momentum across comparable
                                periods.
                            </CardDescription>
                        </div>
                        <Badge variant="outline" className="capitalize">
                            {trendLabel(summary.trend)}
                        </Badge>
                    </CardHeader>
                    <CardContent className="grid items-center gap-5 sm:grid-cols-[12rem_1fr]">
                        <div className="rounded-2xl border bg-muted/20 p-2">
                            <GrowthScoreRadial score={summary.growth_score} />
                        </div>
                        <div className="min-w-0 space-y-4">
                            <div>
                                <p className="text-2xl font-bold capitalize">
                                    {trendLabel(summary.trend)}
                                </p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    {summary.score_volatility === null
                                        ? 'Build more history to establish momentum.'
                                        : `Score volatility is ±${summary.score_volatility.toFixed(1)} points.`}
                                </p>
                            </div>
                            <GrowthScoreSparkline analysis={analysis} />
                            <div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
                                <Badge variant="secondary">
                                    {summary.scored_transition_count} scored
                                    period
                                    {summary.scored_transition_count === 1
                                        ? ''
                                        : 's'}
                                </Badge>
                                <span>Improving above 55</span>
                                <span>Stable 45–55</span>
                            </div>
                        </div>
                    </CardContent>
                </Card>
                <HealthCard dashboard={dashboard} />
            </div>

            <ChangeSummary analysis={analysis} />

            <div className="grid items-stretch gap-4 xl:grid-cols-2">
                <ActionCenter dashboard={dashboard} />
                <Card className="h-full">
                    <CardHeader>
                        <CardTitle className="text-lg">
                            Recent financial snapshot
                        </CardTitle>
                        <CardDescription>
                            Latest available annual results in {currency}.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto">
                        <table className="w-full min-w-[28rem] text-left text-sm">
                            <thead>
                                <tr className="border-b text-muted-foreground">
                                    <th className="py-2 pr-4 font-medium">
                                        Year
                                    </th>
                                    <th className="py-2 pr-4 font-medium">
                                        Revenue
                                    </th>
                                    <th className="py-2 font-medium">
                                        Net income
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                {dashboard.recent_financials.map((year) => (
                                    <tr
                                        key={year.year}
                                        className="border-b last:border-0"
                                    >
                                        <td className="py-2 pr-4 font-medium">
                                            {year.year}
                                        </td>
                                        <td className="py-2 pr-4">
                                            {money(year.revenue, currency)}
                                        </td>
                                        <td className="py-2">
                                            {money(year.net_income, currency)}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </CardContent>
                </Card>
            </div>

            <GrowthScoreCharts analysis={analysis} currency={currency} />
        </div>
    );
}
