"use client";

import Link from "next/link";
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";

interface ConnectionRow {
  shopId: string;
  status: "CONNECTED" | "RECONNECT_REQUIRED" | "DISCONNECTED";
  scope: string | null;
  tokenExpiresAt: Date | null;
  refreshTokenExpiresAt: Date | null;
}

const COPY = {
  en: {
    title: "Integrations",
    description: "Manage TokNext data integrations with truthful connection state.",
    tiktok: "TikTok Shop",
    tiktokDescription: "Imports authorized shop products and product metric snapshots when credentials and permissions are available.",
    configured: "API configured",
    notConfigured: "API not configured",
    connected: "{count} authorized TikTok shops",
    healthy: "{count} healthy",
    reconnect: "{count} need reconnect",
    manage: "Manage TikTok account",
    connect: "Connect TikTok Shop",
    adminOnly: "Connection flow currently requires admin access on this server.",
  },
  es: {
    title: "Integraciones",
    description: "Administra integraciones de datos TokNext con estado real de conexión.",
    tiktok: "TikTok Shop",
    tiktokDescription: "Importa productos autorizados y snapshots de métricas cuando existen credenciales y permisos.",
    configured: "API configurada",
    notConfigured: "API no configurada",
    connected: "{count} tiendas TikTok autorizadas",
    healthy: "{count} saludables",
    reconnect: "{count} requieren reconexión",
    manage: "Administrar cuenta de TikTok",
    connect: "Conectar TikTok Shop",
    adminOnly: "El flujo de conexión requiere acceso admin en este servidor.",
  },
} as const;

export function IntegrationsPageContent({
  connections,
  configured,
  canConnect,
  loadError = false,
}: {
  connections: ConnectionRow[];
  configured: boolean;
  canConnect: boolean;
  loadError?: boolean;
}) {
  const { locale, t } = useLanguage();
  const copy = COPY[locale];
  const health = connections.map((connection) => mapTikTokConnectionHealth(connection));
  const healthyCount = health.filter((item) => item.healthy).length;
  const reconnectCount = health.filter((item) => item.reconnectRequired).length;

  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="flex items-center justify-between gap-3 border-b px-5 py-4">
          <p className="text-[15px] font-bold text-foreground">{copy.tiktok}</p>
          <Badge variant={configured ? "outline" : "destructive"}>{configured ? copy.configured : copy.notConfigured}</Badge>
        </div>
        {loadError ? (
          <div className="flex min-h-40 items-center justify-center px-5 text-center">
            <p className="text-sm text-muted-foreground">{t.errors.generic}</p>
          </div>
        ) : (
          <div className="flex flex-col gap-4 p-5">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <h2 className="m-0 text-lg font-semibold text-foreground">{copy.tiktok}</h2>
                <p className="mt-1 max-w-3xl text-sm text-muted-foreground">{copy.tiktokDescription}</p>
              </div>
              <div className="flex flex-wrap gap-2">
                <Button asChild variant="outline">
                  <Link href="/dashboard/tiktok-account">{copy.manage}</Link>
                </Button>
                {configured && canConnect ? (
                  <Button asChild>
                    <Link href="/api/auth/tiktok/connect">{copy.connect}</Link>
                  </Button>
                ) : null}
              </div>
            </div>
            <div className="grid gap-3 sm:grid-cols-3">
              <Metric label={copy.connected.replace("{count}", String(connections.length))} />
              <Metric label={copy.healthy.replace("{count}", String(healthyCount))} />
              <Metric label={copy.reconnect.replace("{count}", String(reconnectCount))} />
            </div>
            {!canConnect && configured ? <p className="m-0 text-sm text-muted-foreground">{copy.adminOnly}</p> : null}
          </div>
        )}
      </Card>
    </div>
  );
}

function Metric({ label }: { label: string }) {
  return (
    <div className="rounded-xl border border-border bg-secondary/20 p-4 text-sm font-semibold text-foreground">
      {label}
    </div>
  );
}
