"use client";

import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { ProductImage } from "@/components/dashboard/product-image";
import { useLanguage } from "@/lib/i18n/context";

interface VideoRow {
  capturedAt: Date;
  videoCount: number | null;
  views: number | null;
  likes: number | null;
  comments: number | null;
  shares: number | null;
  engagement: number | null;
  product: {
    id: string;
    canonicalName: string;
    category: string;
    imageUrl: string | null;
    isDemo: boolean;
    store: { name: string } | null;
    score: { opportunityScore: number; growthVelocityScore: number | null } | null;
  };
  creator: { id: string; displayName: string | null; handle: string | null } | null;
}

const COPY = {
  en: {
    title: "Video Intelligence",
    description:
      "Product-level video and engagement signals from synchronized metric snapshots. Individual video records appear when the provider supplies them.",
    count: "{count} product video signals",
    empty: "No video metrics have been synchronized yet.",
    scope: "Current schema stores product-level video metrics, not individual video posts.",
    product: "Product",
    creator: "Creator",
    videos: "Videos",
    views: "Views",
    engagement: "Engagement",
    trend: "Trend",
  },
  es: {
    title: "Inteligencia de videos",
    description:
      "Señales de videos y engagement a nivel producto desde snapshots sincronizados. Los videos individuales aparecerán cuando el proveedor los entregue.",
    count: "{count} señales de video",
    empty: "Aún no se han sincronizado métricas de video.",
    scope: "El esquema actual guarda métricas de video a nivel producto, no publicaciones individuales.",
    product: "Producto",
    creator: "Creador",
    videos: "Videos",
    views: "Vistas",
    engagement: "Engagement",
    trend: "Tendencia",
  },
} as const;

function numberOrDash(value: number | null, locale: "en" | "es") {
  return value === null ? "—" : new Intl.NumberFormat(locale).format(value);
}

function percentOrDash(value: number | null, locale: "en" | "es") {
  return value === null
    ? "—"
    : new Intl.NumberFormat(locale === "es" ? "es-US" : "en-US", {
        style: "percent",
        maximumFractionDigits: 2,
      }).format(value);
}

export function VideosPageContent({ rows, loadError = false }: { rows: VideoRow[]; 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="rounded-2xl p-4 shadow-xs">
        <p className="m-0 text-sm text-muted-foreground">{copy.scope}</p>
      </Card>

      <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-[30%]" />
                <col className="w-[20%]" />
                <col className="w-[12%]" />
                <col className="w-[14%]" />
                <col className="w-[14%]" />
                <col className="w-[10%]" />
              </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 font-medium">{copy.creator}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.videos}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.views}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.engagement}</th>
                  <th className="px-5 py-3 text-center font-medium">{copy.trend}</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="block truncate text-xs text-muted-foreground">{row.product.category}</span>
                        </span>
                      </Link>
                    </td>
                    <td className="truncate px-5 py-3 text-muted-foreground">
                      {row.creator ? row.creator.displayName ?? row.creator.handle ?? "—" : "—"}
                    </td>
                    <td className="px-5 py-3 text-center tabular-nums">{numberOrDash(row.videoCount, locale)}</td>
                    <td className="px-5 py-3 text-center tabular-nums">{numberOrDash(row.views, locale)}</td>
                    <td className="px-5 py-3 text-center tabular-nums">{percentOrDash(row.engagement, locale)}</td>
                    <td className="px-5 py-3 text-center">
                      <Badge variant="outline">{row.product.score?.growthVelocityScore ?? "—"}</Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}
