"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { SOCIAL_PLATFORM_LIST, type SocialPlatformId } from "@/lib/social/platforms";

interface ConnectionsPayload {
  social: Record<SocialPlatformId, boolean>;
}

interface SafeSocialAccount {
  id: string;
  platform: SocialPlatformId;
  handle: string;
  displayName?: string;
}

const METRICS = [
  { key: "followers", label: "Followers", icon: "👥" },
  { key: "reach", label: "Reach (28d)", icon: "📣" },
  { key: "engagement", label: "Engagement rate", icon: "💬", suffix: "%" },
  { key: "posts", label: "Posts (28d)", icon: "📅" },
];

export function SocialPerformance() {
  const [connections, setConnections] = useState<ConnectionsPayload | null>(null);
  const [accounts, setAccounts] = useState<SafeSocialAccount[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const t = setTimeout(async () => {
      try {
        const [c, a] = await Promise.all([
          fetch("/api/system/connections").then((r) => r.json()),
          fetch("/api/social/accounts").then((r) => r.json()),
        ]);
        setConnections(c);
        setAccounts(a.accounts ?? []);
      } finally {
        setLoading(false);
      }
    }, 0);
    return () => clearTimeout(t);
  }, []);

  return (
    <div className="space-y-6">
      <Card>
        <CardContent className="p-6">
          <h2 className="text-base font-semibold">Performance dashboard</h2>
          <p className="mt-2 text-sm text-muted-foreground max-w-3xl">
            One row per platform. Cards stay as <code className="text-xs">—</code> until that
            platform’s API is connected and the first sync runs. Posting tooling on the composer
            side ships independently of analytics — both light up once each platform clears app
            review.
          </p>
          <div className="mt-3">
            <Button asChild variant="brand" size="sm">
              <Link href="/app/social/accounts">Connect accounts →</Link>
            </Button>
          </div>
        </CardContent>
      </Card>

      {loading ? (
        <Card>
          <CardContent className="p-6 space-y-3">
            <Skeleton className="h-5 w-40" />
            <Skeleton className="h-4 w-64" />
            <div className="grid gap-3 grid-cols-2 md:grid-cols-4 mt-3">
              <Skeleton className="h-20" />
              <Skeleton className="h-20" />
              <Skeleton className="h-20" />
              <Skeleton className="h-20" />
            </div>
          </CardContent>
        </Card>
      ) : (
        SOCIAL_PLATFORM_LIST.map((plat) => {
          const configured = connections?.social[plat.id] ?? false;
          const platAccounts = accounts.filter((a) => a.platform === plat.id);
          const isConnected = configured && platAccounts.length > 0;
          return (
            <Card key={plat.id}>
              <CardContent className="p-6">
                <div className="flex items-center justify-between flex-wrap gap-3 mb-3">
                  <div className="flex items-center gap-3">
                    <div
                      className="w-10 h-10 rounded-xl flex items-center justify-center text-xl"
                      style={{ backgroundColor: `${plat.color}25` }}
                    >
                      {plat.icon}
                    </div>
                    <div>
                      <h3 className="text-sm font-semibold flex items-center gap-2 flex-wrap">
                        {plat.label}
                        {isConnected ? (
                          <Badge variant="success" className="text-[10px]">
                            {platAccounts.length} account
                            {platAccounts.length === 1 ? "" : "s"}
                          </Badge>
                        ) : (
                          <Badge variant="outline" className="text-[10px]">
                            Not connected
                          </Badge>
                        )}
                      </h3>
                      <p className="text-[11px] text-muted-foreground">
                        {platAccounts.length === 0
                          ? "No accounts yet."
                          : platAccounts.map((a) => a.handle).join(" · ")}
                      </p>
                    </div>
                  </div>
                  {!isConnected && (
                    <Button asChild variant="outline" size="sm">
                      <Link href="/app/social/accounts">Connect {plat.label}</Link>
                    </Button>
                  )}
                </div>
                <div className="grid gap-3 grid-cols-2 md:grid-cols-4">
                  {METRICS.map((m) => (
                    <Card key={m.key} className="bg-muted/30">
                      <CardContent className="p-4">
                        <div className="section-label flex items-center gap-1">
                          <span>{m.icon}</span> {m.label}
                        </div>
                        <div className="mt-1 text-2xl font-semibold tabular-nums text-muted-foreground/60">
                          —{m.suffix ?? ""}
                        </div>
                        <div className="mt-1 text-[10px] text-muted-foreground">
                          {isConnected ? "Sync pending API approval" : "Connect to populate"}
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>
          );
        })
      )}
    </div>
  );
}
