"use client";

import Link from "next/link";
import { TrendingDown, TrendingUp } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { ProductImage } from "@/components/dashboard/product-image";
import { DemoBadge } from "@/components/dashboard/demo-badge";
import { useLanguage } from "@/lib/i18n/context";

interface TrendRow {
  product: {
    id: string;
    canonicalName: string;
    category: string;
    imageUrl: string | null;
    isDemo: boolean;
    store: { name: string } | null;
    score: { opportunityScore: number; growthVelocityScore: number | null; demandAccelerationScore: number | null } | null;
  };
  latest: { unitsSold: number | null; revenue: number | null; views: number | null; capturedAt: Date };
  momentum: { status: "ok" | "insufficient"; score: number | null; changeRate: number | null; reason?: string };
  acceleration: { status: "ok" | "insufficient"; score: number | null; accelerationRate: number | null; reason?: string };
}

const COPY = {
  en: {
    title: "Trend Intelligence",
    description: "Momentum and acceleration derived from real product metric snapshots. Thin history is labeled, not estimated.",
    count: "{count} trend signals",
    empty: "There is not enough product history to calculate trends yet.",
    product: "Product",
    momentum: "Momentum",
    acceleration: "Acceleration",
    opportunity: "Opportunity",
    latest: "Latest signal",
    insufficient: "Insufficient history",
  },
  es: {
    title: "Inteligencia de tendencias",
    description: "Momentum y aceleración derivados de snapshots reales de métricas. El historial insuficiente se etiqueta, no se estima.",
    count: "{count} señales de tendencia",
    empty: "Aún no hay suficiente historial de productos para calcular tendencias.",
    product: "Producto",
    momentum: "Momentum",
    acceleration: "Aceleración",
    opportunity: "Oportunidad",
    latest: "Última señal",
    insufficient: "Historial insuficiente",
  },
} as const;

function formatPercent(value: number | null, locale: "en" | "es") {
  if (value === null) return "—";
  return new Intl.NumberFormat(locale === "es" ? "es-US" : "en-US", {
    style: "percent",
    maximumFractionDigits: 1,
  }).format(value);
}

function SignalBadge({ value, label }: { value: number | null; label: string }) {
  if (value === null) return <Badge variant="outline">{label}</Badge>;
  const positive = value >= 50;
  return (
    <Badge variant="outline" className={positive ? "border-success/30 bg-success/10 text-success" : "border-warning/30 bg-warning/10 text-warning"}>
      {positive ? <TrendingUp className="size-3.5" /> : <TrendingDown className="size-3.5" />}
      {value}
    </Badge>
  );
}

export function TrendsPageContent({ rows, loadError = false }: { rows: TrendRow[]; loadError?: boolean }) {
  const { locale, t } = useLanguage();
  const copy = COPY[locale];

  return (
    <div className="flex w-full max-w-[1500px] flex-col gap-4 pb-8">
      <div className="pt-0.5">
        <h1 className="text-[26px] font-semibold tracking-tight text-foreground sm:text-[28px]">{copy.title}</h1>
        <p className="mt-1 max-w-2xl text-sm text-muted-foreground">{copy.description}</p>
      </div>

      <Card className="gap-0 overflow-hidden rounded-2xl py-0">
        <div className="border-b px-5 py-4">
          <p className="text-[15px] font-bold text-foreground">{copy.count.replace("{count}", new Intl.NumberFormat(locale).format(rows.length))}</p>
        </div>
        {loadError || rows.length === 0 ? (
          <div className="flex min-h-56 flex-col items-center justify-center gap-1 px-5 text-center">
            <p className="text-sm font-semibold text-foreground">{loadError ? t.errors.generic : copy.empty}</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[820px] table-fixed border-collapse text-left text-sm">
              <colgroup>
                <col className="w-[34%]" />
                <col className="w-[16%]" />
                <col className="w-[16%]" />
                <col className="w-[14%]" />
                <col className="w-[20%]" />
              </colgroup>
              <thead>
                <tr className="border-b border-border text-xs text-muted-foreground">
                  <th className="px-5 py-3 font-medium">{copy.product}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.momentum}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.acceleration}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.opportunity}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.latest}</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((row) => (
                  <tr key={row.product.id} className="border-b border-border last:border-0 hover:bg-secondary/30">
                    <td className="px-5 py-3">
                      <Link href={`/dashboard/products/${row.product.id}`} className="flex items-center gap-3">
                        <ProductImage src={row.product.imageUrl} alt={row.product.canonicalName} className="size-12 shrink-0 rounded-lg border" sizes="48px" />
                        <span className="min-w-0">
                          <span className="block truncate font-semibold text-foreground">{row.product.canonicalName}</span>
                          <span className="flex min-w-0 items-center gap-1.5">
                            <span className="truncate text-xs text-muted-foreground">{row.product.category}</span>
                            {row.product.isDemo && <DemoBadge className="shrink-0" />}
                          </span>
                        </span>
                      </Link>
                    </td>
                    <td className="px-5 py-3 text-center">
                      <SignalBadge value={row.momentum.score} label={copy.insufficient} />
                      <div className="mt-1 text-xs text-muted-foreground">{formatPercent(row.momentum.changeRate, locale)}</div>
                    </td>
                    <td className="px-5 py-3 text-center">
                      <SignalBadge value={row.acceleration.score} label={copy.insufficient} />
                      <div className="mt-1 text-xs text-muted-foreground">{formatPercent(row.acceleration.accelerationRate, locale)}</div>
                    </td>
                    <td className="px-5 py-3 text-center tabular-nums">{row.product.score?.opportunityScore ?? "—"}</td>
                    <td className="px-5 py-3 text-center text-muted-foreground">
                      {row.latest.unitsSold !== null
                        ? `${new Intl.NumberFormat(locale).format(row.latest.unitsSold)} sold`
                        : row.latest.views !== null
                          ? `${new Intl.NumberFormat(locale).format(row.latest.views)} views`
                          : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}
