import { useMemo } from "react";
import { RefreshCw } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Skeleton } from "@/Components/ui/skeleton";
import { cn } from "@/lib/utils";

/* ── Formatters ─────────────────────────────────────────── */

const fmtNum = (v) =>
    v == null ? "-" : Number(v).toLocaleString("pt-BR");

const fmtPct = (v) =>
    v == null
        ? "-"
        : Number(v).toLocaleString("pt-BR", {
              minimumFractionDigits: 1,
              maximumFractionDigits: 1,
          }) + "%";

/* ── Component ──────────────────────────────────────────── */

/**
 * Horizontal bar chart for GA4 drill-down views.
 *
 * Props:
 * - rows            - data rows
 * - loading         - show skeleton
 * - error / refetch - error state
 * - labelKey        - field name for bar labels (e.g. "channel")
 * - activeMetric    - currently selected metric key
 * - metrics         - [{ key, label, format: "number"|"percent" }]
 * - onMetricChange  - callback when user selects a metric
 * - emptyIcon       - Lucide icon for empty state
 * - emptyMessage    - text for empty state
 * - totalRecords    - total from meta (for "showing X of Y")
 */
export default function Ga4BarView({
    rows = [],
    loading = false,
    error,
    refetch,
    labelKey,
    activeMetric,
    metrics,
    onMetricChange,
    emptyIcon: EmptyIcon,
    emptyMessage = "Nenhum dado no período.",
    totalRecords,
    hiddenNote,
}) {
    const meta = metrics.find((m) => m.key === activeMetric) ?? metrics[0];
    const fmt = meta?.format === "percent" ? fmtPct : fmtNum;
    const isPct = meta?.format === "percent";

    const maxVal = useMemo(() => {
        if (isPct) return 100;
        return Math.max(...rows.map((r) => Number(r[activeMetric]) || 0), 1);
    }, [rows, activeMetric, isPct]);

    const total = useMemo(() => {
        if (isPct) return null;
        return rows.reduce((s, r) => s + (Number(r[activeMetric]) || 0), 0);
    }, [rows, activeMetric, isPct]);

    /* ── Error ──────────────────────────────────────────── */

    if (error) {
        return (
            <div className="rounded-md border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive flex items-center justify-between gap-2">
                <span>{error}</span>
                <Button variant="outline" size="sm" className="shrink-0" onClick={refetch}>
                    <RefreshCw className="h-3.5 w-3.5 mr-1" /> Tentar novamente
                </Button>
            </div>
        );
    }

    /* ── Render ─────────────────────────────────────────── */

    return (
        <div className="space-y-3">
            {/* Metric selector (segmented control style) */}
            {metrics.length > 1 && (
                <div className="inline-flex flex-wrap rounded-lg bg-muted p-0.5 gap-0.5">
                    {metrics.map((m) => (
                        <button
                            key={m.key}
                            type="button"
                            className={cn(
                                "rounded-md px-2.5 py-1 text-xs font-medium transition-all",
                                activeMetric === m.key
                                    ? "bg-background text-foreground shadow-sm"
                                    : "text-muted-foreground hover:text-foreground",
                            )}
                            onClick={() => onMetricChange?.(m.key)}
                        >
                            {m.label}
                        </button>
                    ))}
                </div>
            )}

            {/* Bars / Loading / Empty */}
            {loading ? (
                <div className="space-y-2">
                    {Array.from({ length: 6 }).map((_, i) => (
                        <div key={i} className="flex items-center gap-2 px-1.5 py-1.5">
                            <Skeleton className="h-3 w-4" />
                            <Skeleton className="h-3 w-28" />
                            <Skeleton className="h-8 flex-1 rounded-md" />
                        </div>
                    ))}
                </div>
            ) : rows.length === 0 ? (
                <div className="flex flex-col items-center justify-center gap-2 py-16 text-muted-foreground">
                    {EmptyIcon && <EmptyIcon className="h-8 w-8 opacity-50" />}
                    <span className="text-sm">{emptyMessage}</span>
                </div>
            ) : (
                <div className="space-y-0.5">
                    {rows.map((r, i) => {
                        const val = Number(r[activeMetric]) || 0;
                        const w = maxVal > 0 ? (val / maxVal) * 100 : 0;
                        return (
                            <div
                                key={String(r[labelKey]) + i}
                                className="group flex items-center gap-2 rounded-lg px-1.5 py-1.5 transition-colors hover:bg-muted/50"
                            >
                                <span className="text-[11px] text-muted-foreground/60 w-4 text-right tabular-nums shrink-0">
                                    {i + 1}
                                </span>
                                <span
                                    className="text-sm truncate w-[110px] sm:w-[180px] lg:w-[220px] shrink-0"
                                    title={r[labelKey] || "(not set)"}
                                >
                                    {r[labelKey] || "(not set)"}
                                </span>
                                <div className="flex-1 min-w-0 h-8 bg-muted/30 rounded-md overflow-hidden relative">
                                    <div
                                        className="h-full rounded-md bg-blue-500/75 dark:bg-blue-400/60 transition-all duration-500 ease-out"
                                        style={{ width: `${Math.max(w, 0.5)}%` }}
                                    />
                                    <span className="absolute right-2.5 top-1/2 -translate-y-1/2 text-xs font-semibold tabular-nums">
                                        {fmt(val)}
                                    </span>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {/* Footer */}
            {!loading && rows.length > 0 && (
                <div className="flex items-center justify-between border-t pt-2.5 px-1.5 text-xs text-muted-foreground">
                    <span>
                        {totalRecords != null && totalRecords > rows.length
                            ? `Mostrando top ${rows.length} de ${fmtNum(totalRecords)}`
                            : `${rows.length} registros`}
                        {hiddenNote && <span className="ml-1 opacity-70">({hiddenNote})</span>}
                    </span>
                    {total != null && (
                        <span className="font-semibold text-foreground">
                            Total: {fmtNum(total)}
                        </span>
                    )}
                </div>
            )}
        </div>
    );
}
