"use client";

import Link from "next/link";
import { motion } from "motion/react";
import { ArrowUpRight, Bookmark, Check, Database, Download, FileSpreadsheet, History, Package, Store, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { useLanguage } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
import { STAGGER_CONTAINER, STAGGER_ITEM } from "@/components/dashboard/motion-variants";

interface Counts {
  products: number;
  savedProducts: number;
  stores: number;
  creators: number;
  connections: number;
}

const COPY = {
  en: {
    title: "Reports",
    description: "Generate exports from real TokNext records. Unsupported formats are clearly marked unavailable.",
    overview: "Workspace data",
    availableCount: "1 format available",
    available: "Available exports",
    history: "Report history",
    noHistory: "Report history storage is not implemented yet, so generated CSV files download immediately and are not saved.",
    historyStatus: "Coming soon",
    included: "Included in this export",
    secure: "Generated from your workspace data",
    stats: ["Products", "Saved", "Stores", "Creators"],
    products: "Product opportunity CSV",
    productsDesc: "Up to 500 active products with category, store, price, opportunity, growth, risk, source and last seen date.",
    csv: "CSV",
    pdfUnavailable: "PDF unavailable",
    download: "Download CSV",
    counts: "{products} products · {saved} saved · {stores} stores · {creators} creators · {connections} TikTok accounts",
  },
  es: {
    title: "Reportes",
    description: "Genera exportaciones desde registros reales de TokNext. Los formatos no soportados se marcan como no disponibles.",
    overview: "Datos del espacio de trabajo",
    availableCount: "1 formato disponible",
    available: "Exportaciones disponibles",
    history: "Historial de reportes",
    noHistory: "El almacenamiento del historial aún no está implementado; los CSV se descargan directamente y no se guardan.",
    historyStatus: "Próximamente",
    included: "Incluye esta exportación",
    secure: "Generado con los datos de tu espacio de trabajo",
    stats: ["Productos", "Guardados", "Tiendas", "Creadores"],
    products: "CSV de oportunidades de producto",
    productsDesc: "Hasta 500 productos activos con categoría, tienda, precio, oportunidad, crecimiento, riesgo, fuente y última fecha vista.",
    csv: "CSV",
    pdfUnavailable: "PDF no disponible",
    download: "Descargar CSV",
    counts: "{products} productos · {saved} guardados · {stores} tiendas · {creators} creadores · {connections} cuentas de TikTok",
  },
} as const;

const STAT_TONE_CLASSES: Record<string, string> = {
  cyan: "bg-cyan-500/10 text-cyan-600 dark:text-cyan-400",
  purple: "bg-violet-500/10 text-violet-600 dark:text-violet-400",
  blue: "bg-blue-500/10 text-blue-600 dark:text-blue-400",
  pink: "bg-pink-500/10 text-pink-600 dark:text-pink-400",
};

export function ReportsPageContent({ counts, loadError = false }: { counts: Counts; loadError?: boolean }) {
  const { locale, t } = useLanguage();
  const copy = COPY[locale];
  const formatter = new Intl.NumberFormat(locale);
  const statItems = [
    { label: copy.stats[0], value: counts.products, tone: "cyan", icon: Package, href: "/dashboard/products" },
    { label: copy.stats[1], value: counts.savedProducts, tone: "purple", icon: Bookmark, href: "/dashboard/saved" },
    { label: copy.stats[2], value: counts.stores, tone: "blue", icon: Store, href: "/dashboard/stores" },
    { label: copy.stats[3], value: counts.creators, tone: "pink", icon: Users, href: "/dashboard/creators" },
  ];
  const includedFields = locale === "es"
    ? ["Categoría", "Tienda", "Precio", "Opportunity Score", "Crecimiento", "Riesgo"]
    : ["Category", "Store", "Price", "Opportunity Score", "Growth", "Risk"];

  return (
    <div className="flex w-full max-w-[1500px] flex-col gap-4 pb-8">
      <div className="flex flex-wrap items-start justify-between gap-4 pt-0.5">
        <div>
          <span className="mb-2 inline-flex items-center gap-1.5 text-[10px] font-extrabold tracking-[0.14em] text-primary uppercase">
            <Database className="size-3.5" aria-hidden="true" /> {copy.overview}
          </span>
          <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>
        <Badge variant="outline" className="gap-1.5 self-start rounded-full border-success/30 bg-success/10 px-3 py-1.5 text-xs font-semibold text-success">
          <span className="size-1.5 rounded-full bg-success" />
          {copy.availableCount}
        </Badge>
      </div>

      <motion.div
        className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4"
        initial="hidden"
        whileInView="visible"
        viewport={{ once: true, amount: 0.2 }}
        variants={STAGGER_CONTAINER}
      >
        {statItems.map((item) => (
          <motion.div key={item.label} variants={STAGGER_ITEM} whileHover={{ y: -2 }}>
            <Link href={item.href} className="flex items-center gap-3 rounded-2xl border bg-card px-4 py-4 shadow-xs transition-shadow hover:shadow-md">
              <span className={cn("flex size-9 shrink-0 items-center justify-center rounded-full", STAT_TONE_CLASSES[item.tone])}>
                <item.icon className="size-4" aria-hidden="true" />
              </span>
              <span className="flex min-w-0 flex-1 flex-col gap-0.5">
                <span className="text-xs text-muted-foreground">{item.label}</span>
                <strong className="text-xl font-bold text-foreground tabular-nums">{formatter.format(item.value)}</strong>
              </span>
              <ArrowUpRight className="size-3.5 shrink-0 text-muted-foreground/70" aria-hidden="true" />
            </Link>
          </motion.div>
        ))}
      </motion.div>

      <Card className="gap-0 overflow-hidden rounded-2xl py-0">
        <div className="flex items-center gap-3 border-b px-5 py-4">
          <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-cyan-500/10 text-cyan-600 dark:text-cyan-400">
            <FileSpreadsheet className="size-4" aria-hidden="true" />
          </span>
          <div>
            <p className="text-[15px] font-bold text-foreground">{copy.available}</p>
            <span className="text-[11px] text-muted-foreground">{copy.availableCount}</span>
          </div>
        </div>

        {loadError ? (
          <div className="flex min-h-40 items-center justify-center px-5 text-sm text-muted-foreground">{t.errors.generic}</div>
        ) : (
          <div className="flex flex-col gap-4 p-5">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
              <div className="flex min-w-0 items-start gap-3">
                <span className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-muted text-muted-foreground">
                  <FileSpreadsheet className="size-5" aria-hidden="true" />
                </span>
                <div className="min-w-0">
                  <div className="flex flex-wrap items-center gap-2">
                    <h2 className="text-[15px] font-bold text-foreground">{copy.products}</h2>
                    <Badge className="gap-1 bg-success/10 text-success">
                      <Check className="size-3" aria-hidden="true" />
                      {copy.csv}
                    </Badge>
                  </div>
                  <p className="mt-1 text-sm text-muted-foreground">{copy.productsDesc}</p>
                  <p className="mt-2 text-xs text-muted-foreground">
                    {copy.counts
                      .replace("{products}", formatter.format(counts.products))
                      .replace("{saved}", formatter.format(counts.savedProducts))
                      .replace("{stores}", formatter.format(counts.stores))
                      .replace("{creators}", formatter.format(counts.creators))
                      .replace("{connections}", formatter.format(counts.connections))}
                  </p>
                </div>
              </div>

              <div className="flex shrink-0 flex-col items-start gap-2 sm:items-end">
                <div className="flex items-center gap-2">
                  <Badge variant="secondary">{copy.pdfUnavailable}</Badge>
                  <Button asChild>
                    <Link href="/api/dashboard/reports/products.csv">
                      <Download className="size-4" />
                      {copy.download}
                      <ArrowUpRight className="size-4" aria-hidden="true" />
                    </Link>
                  </Button>
                </div>
                <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
                  <Database className="size-3.5" aria-hidden="true" />
                  <span>{copy.secure}</span>
                </div>
              </div>
            </div>

            <div className="flex flex-col gap-2 border-t pt-4">
              <span className="text-[10px] font-bold tracking-wide text-muted-foreground uppercase">{copy.included}</span>
              <div className="flex flex-wrap gap-2">
                {includedFields.map((field) => (
                  <Badge key={field} variant="outline" className="gap-1 font-normal text-muted-foreground">
                    <Check className="size-3 text-success" aria-hidden="true" />
                    {field}
                  </Badge>
                ))}
              </div>
            </div>
          </div>
        )}
      </Card>

      <Card className="gap-0 overflow-hidden rounded-2xl py-0">
        <div className="flex items-center justify-between gap-4 border-b px-5 py-4">
          <div className="flex items-center gap-3">
            <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-violet-500/10 text-violet-600 dark:text-violet-400">
              <History className="size-4" aria-hidden="true" />
            </span>
            <div>
              <p className="text-[15px] font-bold text-foreground">{copy.history}</p>
              <span className="text-[11px] text-muted-foreground">{copy.historyStatus}</span>
            </div>
          </div>
          <Badge variant="outline">{copy.historyStatus}</Badge>
        </div>
        <div className="flex flex-col items-center justify-center gap-2 px-6 py-14 text-center">
          <span className="flex size-11 items-center justify-center rounded-full bg-muted text-muted-foreground">
            <History className="size-5" aria-hidden="true" />
          </span>
          <p className="max-w-md text-sm font-semibold text-foreground">{copy.noHistory}</p>
          <span className="text-xs text-muted-foreground">{copy.secure}</span>
        </div>
      </Card>
    </div>
  );
}
