"use client";

import { useEffect, useTransition } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { useLanguage } from "@/lib/i18n/context";

export interface TikTokConnectionInfo {
  id: string;
  status: "CONNECTED" | "RECONNECT_REQUIRED" | "DISCONNECTED";
  shopName: string | null;
  sellerName: string | null;
  region: string | null;
  updatedAt: Date;
}

interface Props {
  connections: TikTokConnectionInfo[];
  configured: boolean;
}

/** Step 1 "multiple connected stores per user" — renders one card per
 * connected TikTok Shop store (a TikTokConnection is a shared, site-wide
 * data source, not scoped to the viewing admin — see the architectural note
 * in PROJECT_STATE.md), plus a persistent "connect another store" action. */
export function TikTokConnectionsSection({ connections, configured }: Props) {
  const { t } = useLanguage();
  const tk = t.admin.tiktok;
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    const connected = searchParams.get("connected");
    const errorParam = searchParams.get("tiktokError");
    if (connected === "tiktok") {
      toast.success(tk.connected);
      router.replace("/admin/data-sources");
    } else if (errorParam) {
      const errors = tk.errors as unknown as Record<string, string>;
      toast.error(errors[errorParam] ?? tk.errors.token_exchange_failed);
      router.replace("/admin/data-sources");
    }
    // Only meant to run once on mount to consume the redirect query params.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="flex flex-col gap-4">
      <Card>
        <CardHeader>
          <CardTitle>{tk.title}</CardTitle>
          <CardDescription>{tk.description}</CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          {connections.length === 0 && <p className="text-sm text-muted-foreground">{tk.noConnections}</p>}

          {connections.map((connection) => (
            <ConnectionRow key={connection.id} connection={connection} />
          ))}

          <div>
            {configured ? (
              <Button asChild size="sm">
                <Link href="/api/auth/tiktok/connect">{connections.length === 0 ? tk.connect : tk.addAnother}</Link>
              </Button>
            ) : (
              <Button size="sm" disabled>
                {tk.connect}
              </Button>
            )}
          </div>
          {!configured && <p className="text-xs text-muted-foreground">{tk.notConfigured}</p>}
        </CardContent>
      </Card>
    </div>
  );
}

function ConnectionRow({ connection }: { connection: TikTokConnectionInfo }) {
  const { t, locale } = useLanguage();
  const tk = t.admin.tiktok;
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  function handleDisconnect() {
    startTransition(async () => {
      const res = await fetch("/api/auth/tiktok/disconnect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ connectionId: connection.id }),
      });
      if (res.ok) {
        toast.success(tk.disconnectSuccess);
        router.refresh();
      } else {
        toast.error(tk.disconnectError);
      }
    });
  }

  const statusBadge =
    connection.status === "CONNECTED" ? (
      <Badge>{tk.connected}</Badge>
    ) : connection.status === "RECONNECT_REQUIRED" ? (
      <Badge variant="destructive">{tk.reconnectRequired}</Badge>
    ) : (
      <Badge variant="outline">{tk.notConnected}</Badge>
    );

  return (
    <div className="flex flex-col gap-3 rounded-lg border border-border p-4">
      <div className="flex items-center justify-between gap-2">
        <p className="font-medium text-foreground">{connection.shopName ?? tk.store}</p>
        {statusBadge}
      </div>

      <div className="grid grid-cols-2 gap-3 text-sm sm:grid-cols-3">
        <div>
          <p className="text-xs text-muted-foreground">{tk.seller}</p>
          <p className="text-foreground">{connection.sellerName ?? "—"}</p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">{tk.region}</p>
          <p className="text-foreground">{connection.region ?? "—"}</p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">{tk.lastSync}</p>
          <p className="text-foreground">
            {new Intl.DateTimeFormat(locale === "es" ? "es-US" : "en-US", {
              dateStyle: "medium",
              timeStyle: "short",
            }).format(connection.updatedAt)}
          </p>
        </div>
      </div>

      <div className="flex gap-2">
        {connection.status === "CONNECTED" ? (
          <Button variant="outline" size="sm" onClick={handleDisconnect} disabled={isPending}>
            {isPending ? tk.disconnecting : tk.disconnect}
          </Button>
        ) : (
          <Button asChild size="sm">
            <Link href="/api/auth/tiktok/connect">{tk.reconnect}</Link>
          </Button>
        )}
      </div>
    </div>
  );
}
