import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { chartColorAt } from '@/features/dashboard/lib/chart-colors';
import type { DashboardChart } from '@/features/dashboard/types';
import { useId } from 'react';
import {
    Area,
    AreaChart,
    CartesianGrid,
    Cell,
    Legend,
    Pie,
    PieChart,
    PolarAngleAxis,
    PolarGrid,
    PolarRadiusAxis,
    Radar,
    RadarChart,
    ResponsiveContainer,
    Tooltip,
    XAxis,
    YAxis,
} from 'recharts';

type Row = { label: string; value: number };

function buildRows(chart: DashboardChart): Row[] {
    const ds = chart.datasets[0];
    if (!ds) {
        return [];
    }

    return chart.labels.map((label, i) => ({
        label,
        value: ds.data[i] ?? 0,
    }));
}

const tooltipStyle = {
    borderRadius: 10,
    border: '1px solid hsl(var(--border))',
    background: 'hsl(var(--card))',
    boxShadow: '0 8px 24px hsl(var(--foreground) / 0.08)',
};

type Props = {
    chart: DashboardChart;
    title: string;
    subtitle?: string;
    formatXLabel: (raw: string) => string;
    formatStatusLabel: (status: string) => string;
};

export function DashboardChartCard({
    chart,
    title,
    subtitle,
    formatXLabel,
    formatStatusLabel,
}: Props) {
    const gradientId = useId().replace(/:/g, '');
    const rows = buildRows(chart);
    const axisColor = 'hsl(var(--muted-foreground))';
    const gridColor = 'hsl(var(--border) / 0.45)';
    const strokePrimary =
        chart.id === 'validations_trend' ? 'hsl(var(--chart-2))' : 'hsl(var(--chart-1))';

    const pieRows = rows.map((row, index) => ({
        ...row,
        name: formatStatusLabel(row.label),
        fill: chartColorAt(index),
    }));

    const radarRows = rows.map((row) => ({
        subject: formatStatusLabel(row.label),
        value: row.value,
    }));

    const radarMax = Math.max(...rows.map((r) => r.value), 1);
    const isEmpty = rows.every((r) => r.value === 0);

    return (
        <Card className="group relative flex h-full min-h-[340px] flex-col overflow-hidden border-border/80 bg-gradient-to-b from-card via-card to-card/80 shadow-sm transition-shadow hover:shadow-md">
            <div className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent opacity-0 transition-opacity group-hover:opacity-100" aria-hidden />
            <CardHeader className="pb-0">
                <CardTitle className="text-base font-semibold tracking-tight">{title}</CardTitle>
                {subtitle ? (
                    <CardDescription className="text-xs leading-relaxed">{subtitle}</CardDescription>
                ) : null}
            </CardHeader>
            <CardContent className="flex flex-1 flex-col pt-4">
                {isEmpty ? (
                    <div className="flex min-h-[280px] flex-1 items-center justify-center rounded-xl border border-dashed border-border/70 bg-muted/20 text-sm text-muted-foreground">
                        —
                    </div>
                ) : (
                <div className="min-h-[280px] w-full flex-1">
                    <ResponsiveContainer width="100%" height="100%">
                        {chart.type === 'line' ? (
                            <AreaChart data={rows} margin={{ top: 12, right: 12, left: 0, bottom: 0 }}>
                                <defs>
                                    <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="0%" stopColor={strokePrimary} stopOpacity={0.45} />
                                        <stop offset="100%" stopColor={strokePrimary} stopOpacity={0.02} />
                                    </linearGradient>
                                </defs>
                                <CartesianGrid stroke={gridColor} strokeDasharray="3 6" vertical={false} />
                                <XAxis
                                    dataKey="label"
                                    tick={{ fill: axisColor, fontSize: 11 }}
                                    tickFormatter={(v) => formatXLabel(String(v))}
                                    tickLine={false}
                                    axisLine={{ stroke: gridColor }}
                                />
                                <YAxis
                                    width={32}
                                    allowDecimals={false}
                                    tick={{ fill: axisColor, fontSize: 11 }}
                                    tickLine={false}
                                    axisLine={{ stroke: gridColor }}
                                />
                                <Tooltip contentStyle={tooltipStyle} />
                                <Area
                                    type="monotone"
                                    dataKey="value"
                                    stroke={strokePrimary}
                                    strokeWidth={2.5}
                                    fill={`url(#${gradientId})`}
                                    dot={{ r: 3, fill: strokePrimary, strokeWidth: 0 }}
                                    activeDot={{ r: 6, strokeWidth: 2, stroke: 'hsl(var(--card))' }}
                                />
                            </AreaChart>
                        ) : null}

                        {chart.type === 'pie' ? (
                            <PieChart>
                                <Pie
                                    data={pieRows}
                                    dataKey="value"
                                    nameKey="name"
                                    cx="50%"
                                    cy="46%"
                                    innerRadius="52%"
                                    outerRadius="76%"
                                    paddingAngle={3}
                                    cornerRadius={6}
                                >
                                    {pieRows.map((entry, index) => (
                                        <Cell key={entry.label} fill={chartColorAt(index)} />
                                    ))}
                                </Pie>
                                <Tooltip contentStyle={tooltipStyle} />
                                <Legend
                                    verticalAlign="bottom"
                                    height={52}
                                    formatter={(value) => (
                                        <span className="text-xs text-muted-foreground">{value}</span>
                                    )}
                                />
                            </PieChart>
                        ) : null}

                        {chart.type === 'radar' ? (
                            <RadarChart data={radarRows} cx="50%" cy="50%" outerRadius="72%">
                                <PolarGrid stroke={gridColor} />
                                <PolarAngleAxis
                                    dataKey="subject"
                                    tick={{ fill: axisColor, fontSize: 10 }}
                                />
                                <PolarRadiusAxis
                                    angle={90}
                                    domain={[0, radarMax]}
                                    tick={{ fill: axisColor, fontSize: 10 }}
                                    axisLine={false}
                                />
                                <Radar
                                    name="value"
                                    dataKey="value"
                                    stroke="hsl(var(--chart-3))"
                                    fill="hsl(var(--chart-3))"
                                    fillOpacity={0.35}
                                    strokeWidth={2}
                                />
                                <Tooltip contentStyle={tooltipStyle} />
                            </RadarChart>
                        ) : null}
                    </ResponsiveContainer>
                </div>
                )}
            </CardContent>
        </Card>
    );
}
