import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { ChartConfig, ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent } from '@/components/ui/chart';
import { cn } from '@/lib/utils';
import { CalendarRange, Minus, TrendingDown, TrendingUp } from 'lucide-react';
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from 'recharts';
import { formatTnd, type KpiComparison, type KpiComparisonMetric } from './kpi-types';

interface YoyComparisonProps {
    comparison: KpiComparison;
    locale: string;
    t: (ns: string, key: string, fallback?: string) => string;
}

/** Short, localized month label from a 1-12 month number. */
function monthLabel(month: number, locale: string): string {
    return new Date(2000, month - 1, 1).toLocaleString(locale === 'fr' ? 'fr-FR' : 'en-US', { month: 'short' });
}

/** Up/down/flat badge for a year-over-year percentage change. */
function DeltaBadge({ delta, t }: { delta: number | null; t: YoyComparisonProps['t'] }) {
    if (delta === null) {
        return (
            <span className="inline-flex items-center gap-1 rounded-full bg-sky-50 px-2 py-0.5 text-xs font-semibold text-sky-700">
                {t('properties.kpi', 'yoy_new')}
            </span>
        );
    }
    const positive = delta > 0;
    const flat = delta === 0;
    const Icon = flat ? Minus : positive ? TrendingUp : TrendingDown;
    const tone = flat ? 'bg-slate-100 text-slate-600' : positive ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700';
    return (
        <span className={cn('inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold', tone)}>
            <Icon className="h-3.5 w-3.5" />
            {positive ? '+' : ''}
            {delta}%
        </span>
    );
}

function DeltaTile({
    label,
    metric,
    formatted,
    previousYear,
    formatter,
    t,
}: {
    label: string;
    metric: KpiComparisonMetric;
    formatted?: string;
    previousYear: number;
    formatter: (v: number) => string;
    t: YoyComparisonProps['t'];
}) {
    return (
        <div className="rounded-xl border bg-white/90 p-4 shadow-sm">
            <div className="text-muted-foreground text-xs font-medium">{label}</div>
            <div className="mt-2 flex items-center gap-2">
                <span className="text-2xl font-semibold tabular-nums">{formatted ?? formatter(metric.current)}</span>
                <DeltaBadge delta={metric.delta_pct} t={t} />
            </div>
            <div className="text-muted-foreground mt-1 text-xs">
                {t('properties.kpi', 'yoy_vs')} {formatter(metric.previous)} ({previousYear})
            </div>
        </div>
    );
}

/** One YoY line chart: current year (solid) vs previous year (dashed). */
function YoyLineChart({
    data,
    currentYear,
    previousYear,
    formatter,
}: {
    data: { label: string; current: number; previous: number }[];
    currentYear: number;
    previousYear: number;
    formatter: (v: number) => string;
}) {
    const config = {
        current: { label: `${currentYear}`, color: '#31B08F' },
        previous: { label: `${previousYear}`, color: '#94a3b8' },
    } satisfies ChartConfig;

    return (
        <ChartContainer config={config} className="aspect-auto h-[240px] w-full">
            <LineChart accessibilityLayer data={data} margin={{ left: 4, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="label" tickLine={false} axisLine={false} tickMargin={8} />
                <YAxis tickLine={false} axisLine={false} width={48} tickFormatter={(v) => formatter(Number(v))} />
                <ChartTooltip content={<ChartTooltipContent formatter={(value) => formatter(Number(value))} />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Line dataKey="previous" stroke="#94a3b8" strokeWidth={2} strokeDasharray="5 4" dot={false} />
                <Line dataKey="current" stroke="#31B08F" strokeWidth={2.5} dot={false} />
            </LineChart>
        </ChartContainer>
    );
}

/**
 * "Comparaison annuelle" section: YoY delta tiles + two monthly curves (revenue
 * and reservations), current year vs previous. Shown by default on the KPI page.
 */
export default function YoyComparison({ comparison, locale, t }: YoyComparisonProps) {
    const { current_year, previous_year, months, totals } = comparison;
    const intFmt = (v: number) => Math.round(v).toLocaleString(locale || 'fr');
    const tndFmt = (v: number) => formatTnd(v, locale);

    const revenueData = months.map((m) => ({
        label: monthLabel(m.month, locale),
        current: m.revenue_current,
        previous: m.revenue_previous,
    }));
    const reservationsData = months.map((m) => ({
        label: monthLabel(m.month, locale),
        current: m.reservations_current,
        previous: m.reservations_previous,
    }));

    return (
        <Card className="mt-4">
            <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                    <CalendarRange className="text-secondary h-4 w-4" />
                    {t('properties.kpi', 'comparison_title')}
                </CardTitle>
                <CardDescription>
                    {current_year} {t('properties.kpi', 'yoy_vs')} {previous_year} — {t('properties.kpi', 'comparison_caption')}
                </CardDescription>
            </CardHeader>
            <CardContent>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
                    <DeltaTile
                        label={t('properties.kpi', 'total_revenue')}
                        metric={totals.revenue}
                        formatted={totals.revenue.current_formatted}
                        previousYear={previous_year}
                        formatter={tndFmt}
                        t={t}
                    />
                    <DeltaTile
                        label={t('properties.kpi', 'total_reservations')}
                        metric={totals.reservations}
                        previousYear={previous_year}
                        formatter={intFmt}
                        t={t}
                    />
                    <DeltaTile
                        label={t('properties.kpi', 'total_nights')}
                        metric={totals.nights}
                        previousYear={previous_year}
                        formatter={intFmt}
                        t={t}
                    />
                </div>

                <div className="mt-5 grid grid-cols-1 gap-6 lg:grid-cols-2">
                    <div>
                        <div className="text-muted-foreground mb-1 text-sm font-medium">{t('properties.kpi', 'comparison_revenue')}</div>
                        <YoyLineChart data={revenueData} currentYear={current_year} previousYear={previous_year} formatter={tndFmt} />
                    </div>
                    <div>
                        <div className="text-muted-foreground mb-1 text-sm font-medium">{t('properties.kpi', 'comparison_reservations')}</div>
                        <YoyLineChart data={reservationsData} currentYear={current_year} previousYear={previous_year} formatter={intFmt} />
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}
