"use client";

import Link from "next/link";
import { motion } from "motion/react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { mapTikTokConnectionHealth } from "@/lib/dashboard/connection-status";
import { useLanguage } from "@/lib/i18n/context";
import { STAGGER_CONTAINER, STAGGER_ITEM } from "@/components/dashboard/motion-variants";

interface ConnectionRow {
  id: string;
  shopId: string;
  shopName: string | null;
  sellerName: string | null;
  region: string | null;
  status: "CONNECTED" | "RECONNECT_REQUIRED" | "DISCONNECTED";
  scope: string | null;
  tokenExpiresAt: Date | null;
  refreshTokenExpiresAt: Date | null;
  lastRefreshAt: Date | null;
  connectedAt: Date;
  updatedAt: Date;
}

interface CreatorConnection {
  id: string;
  creatorName: string | null;
  region: string | null;
  status: "CONNECTED" | "RECONNECT_REQUIRED" | "DISCONNECTED";
  grantedScopes: string | null;
  userType: number;
  tokenExpiresAt: Date | null;
  updatedAt: Date;
}

const COPY = {
  en: {
    title: "My TikTok Account",
    description: "Manage your authorized TikTok creator, affiliate, or seller account. Tokens and shop ciphers are never displayed.",
    count: "{count} authorized shops",
    empty: "No authorized TikTok account connections are available yet.",
    connect: "Connect TikTok account",
    adminOnly: "TikTok authorization is currently enabled for admin users only on this server.",
    notConfigured: "TikTok Shop credentials are not configured on this server.",
    shop: "Authorized shop",
    status: "Status",
    token: "Token",
    scopes: "Scopes",
    updated: "Last updated",
    valid: "Valid",
    reconnect: "Reconnect required",
    missingScopes: "{count} missing",
    complete: "Complete",
    creatorTitle: "TikTok Creator / Affiliate account",
    creatorDescription: "Connect the account you use to promote products. This is separate from a seller shop connection.",
    creatorConnect: "Connect creator account",
    creatorConnected: "Creator account connected",
    creatorReconnect: "Reconnect creator account",
    discover: "Find affiliate products",
    creatorPermission: "Affiliate collaboration access",
    notConnected: "Not connected",
  },
  es: {
    title: "Mi cuenta de TikTok",
    description: "Administra tu cuenta autorizada de TikTok como creador, afiliado o vendedor. Nunca mostramos tokens ni shop ciphers.",
    count: "{count} tiendas autorizadas",
    empty: "Aún no hay conexiones autorizadas de tu cuenta de TikTok.",
    connect: "Conectar cuenta de TikTok",
    adminOnly: "La autorización de TikTok está habilitada solo para usuarios admin en este servidor.",
    notConfigured: "Las credenciales de TikTok Shop no están configuradas en este servidor.",
    shop: "Tienda autorizada",
    status: "Estado",
    token: "Token",
    scopes: "Permisos",
    updated: "Última actualización",
    valid: "Válido",
    reconnect: "Requiere reconexión",
    missingScopes: "{count} faltantes",
    complete: "Completo",
    creatorTitle: "Cuenta de creador / afiliado de TikTok",
    creatorDescription: "Conecta la cuenta con la que promocionas productos. Es independiente de una tienda vendedora.",
    creatorConnect: "Conectar cuenta de creador",
    creatorConnected: "Cuenta de creador conectada",
    creatorReconnect: "Reconectar cuenta de creador",
    discover: "Buscar productos de afiliado",
    creatorPermission: "Acceso a colaboraciones de afiliados",
    notConnected: "No conectada",
  },
} as const;

function formatDate(value: Date | null, locale: "en" | "es") {
  if (!value) return "—";
  return new Intl.DateTimeFormat(locale === "es" ? "es-US" : "en-US", { dateStyle: "medium" }).format(value);
}

export function ConnectedStoresPageContent({
  connections,
  canConnect,
  creatorConnection,
  configured,
  loadError = false,
}: {
  connections: ConnectionRow[];
  canConnect: boolean;
  creatorConnection: CreatorConnection | null;
  configured: boolean;
  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="flex flex-row flex-wrap items-center justify-between gap-3 rounded-2xl p-4">
        <p className="m-0 text-sm text-muted-foreground">
          {!configured ? copy.notConfigured : canConnect ? copy.description : copy.adminOnly}
        </p>
        {configured && canConnect ? (
          <Button asChild>
            <Link href="/api/auth/tiktok/connect">{copy.connect}</Link>
          </Button>
        ) : null}
      </Card>

      <Card className="rounded-2xl border-primary/15 bg-gradient-to-br from-primary/[0.04] via-background to-violet-500/[0.05] p-5">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="m-0 text-xs font-semibold uppercase tracking-[0.16em] text-primary">TokNext Affiliate</p>
            <h2 className="mt-2 text-lg font-semibold text-foreground">{copy.creatorTitle}</h2>
            <p className="mt-1 max-w-2xl text-sm text-muted-foreground">{copy.creatorDescription}</p>
          </div>
          <Badge variant={creatorConnection?.status === "CONNECTED" ? "outline" : "secondary"}>
            {creatorConnection?.status === "CONNECTED" ? copy.creatorConnected : creatorConnection?.status === "RECONNECT_REQUIRED" ? copy.creatorReconnect : copy.notConnected}
          </Badge>
        </div>
        <div className="mt-5 flex flex-wrap items-center gap-3">
          {configured && creatorConnection?.status !== "CONNECTED" ? (
            <Button asChild>
              <Link href="/api/auth/tiktok/creator/connect">{copy.creatorConnect}</Link>
            </Button>
          ) : null}
          {creatorConnection?.status === "CONNECTED" ? (
            <Button asChild variant="outline">
              <Link href="/dashboard/affiliate-products">{copy.discover}</Link>
            </Button>
          ) : null}
          <span className="text-xs text-muted-foreground">
            {creatorConnection?.grantedScopes?.includes("creator.affiliate_collaboration.read") ? copy.creatorPermission : copy.notConnected}
          </span>
        </div>
      </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(connections.length))}</p>
        </div>
        {loadError || connections.length === 0 ? (
          <div className="flex min-h-40 items-center justify-center px-5 text-center">
            <p className="text-sm text-muted-foreground">{loadError ? t.errors.generic : copy.empty}</p>
          </div>
        ) : (
          <motion.div initial="hidden" whileInView="visible" viewport={{ once: true, amount: 0.1 }} variants={STAGGER_CONTAINER}>
            {connections.map((connection) => {
              const health = mapTikTokConnectionHealth(connection);
              return (
                <motion.article key={connection.id} variants={STAGGER_ITEM} className="flex flex-col gap-4 border-b px-5 py-5 last:border-b-0">
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div>
                      <h2 className="m-0 text-base font-semibold text-foreground">{connection.shopName ?? copy.shop}</h2>
                      <p className="mt-1 text-sm text-muted-foreground">
                        {health.maskedShopId} · {connection.region ?? "—"} · {connection.sellerName ?? "—"}
                      </p>
                    </div>
                    <Badge variant={health.reconnectRequired ? "destructive" : "outline"}>
                      {health.reconnectRequired ? copy.reconnect : connection.status}
                    </Badge>
                  </div>
                  <div className="grid gap-3 text-sm sm:grid-cols-3">
                    <Metric label={copy.token} value={health.tokenStatus === "valid" ? copy.valid : health.tokenStatus} />
                    <Metric
                      label={copy.scopes}
                      value={health.missingScopes.length === 0 ? copy.complete : copy.missingScopes.replace("{count}", String(health.missingScopes.length))}
                    />
                    <Metric label={copy.updated} value={formatDate(connection.updatedAt, locale)} />
                  </div>
                </motion.article>
              );
            })}
          </motion.div>
        )}
      </Card>
    </div>
  );
}

function Metric({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <p className="m-0 text-xs text-muted-foreground">{label}</p>
      <p className="mt-1 font-semibold text-foreground">{value}</p>
    </div>
  );
}
