"use client";

import { AlertTriangle, CheckCircle2, XCircle } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { DashboardLayout } from "@/components/layout/dashboard-layout";
import { OnboardingFooter } from "@/components/layout/onboarding-footer";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { selectActiveProject } from "@/hooks/use-projects-hydrated";
import { flushProjectsSync } from "@/lib/client/projects-sync";
import {
  formatLastSynced,
  getAccountHealth,
} from "@/lib/social/token-validation";
import { getPlatformConfig } from "@/lib/social/platforms";
import { MetaSetupBanner, type MetaDiagnostics } from "@/components/social/meta-setup-banner";
import { cn } from "@/lib/utils";
import { useAccountsStore } from "@/store/accounts-store";
import { useProjectsStore } from "@/store/projects-store";
import type { ConnectedAccount } from "@/types/workflow";

export default function ConnectedAccountsPage() {
  const activeProject = useProjectsStore(selectActiveProject);
  const hydrateActiveAccounts = useProjectsStore((s) => s.hydrateActiveAccounts);
  const { accounts } = useAccountsStore();
  const [connecting, setConnecting] = useState<string | null>(null);
  const [linkedInDiag, setLinkedInDiag] = useState<string | null>(null);
  const [metaDiag, setMetaDiag] = useState<MetaDiagnostics | null>(null);

  const loadServerAccounts = useCallback(async () => {
    if (!activeProject?.id) return;
    try {
      const res = await fetch(`/api/projects/${encodeURIComponent(activeProject.id)}/social-accounts`);
      if (!res.ok) return;
      const data = (await res.json()) as { accounts?: ConnectedAccount[] };
      if (data.accounts?.length) {
        hydrateActiveAccounts(data.accounts);
      }

      const diagRes = await fetch(
        `/api/social/linkedin/diagnostics?projectId=${encodeURIComponent(activeProject.id)}`,
      );
      if (diagRes.ok) {
        const diag = (await diagRes.json()) as {
          connected?: boolean;
          readyToPublish?: boolean;
          recommendation?: string;
          probe?: { recommendation?: string };
          scopeMode?: string;
          scopesConfigured?: { envExample?: string; valid?: boolean };
        };
        // Only show red banner when LinkedIn is connected but not publish-ready.
        if (diag.connected === false) {
          setLinkedInDiag(null);
        } else if (diag.readyToPublish === false) {
          if (diag.scopesConfigured?.valid === false) {
            setLinkedInDiag(
              `Server LINKEDIN_SCOPES is invalid. Use: ${diag.scopesConfigured?.envExample ?? "r_liteprofile r_emailaddress w_member_social"}`,
            );
          } else {
            setLinkedInDiag(
              diag.probe?.recommendation ??
                diag.recommendation ??
                "Disconnect and reconnect LinkedIn to refresh publish permissions.",
            );
          }
        } else {
          setLinkedInDiag(null);
        }
      }

      const metaRes = await fetch("/api/social/meta/diagnostics");
      if (metaRes.ok) {
        const meta = (await metaRes.json()) as {
          appId?: string | null;
          redirectUri?: string;
          facebook?: { scopes?: string[] };
          instagram?: { scopes?: string[] };
          portalChecklist?: string[];
          portalLinks?: MetaDiagnostics["portalLinks"];
        };
        setMetaDiag({
          appId: meta.appId ?? null,
          redirectUri: meta.redirectUri ?? "",
          facebookScopes: meta.facebook?.scopes ?? [],
          instagramScopes: meta.instagram?.scopes ?? [],
          steps: meta.portalChecklist ?? [],
          portalLinks: meta.portalLinks,
        });
      }
    } catch {
      // ignore — local state still usable
    }
  }, [activeProject?.id, hydrateActiveAccounts]);

  useEffect(() => {
    void loadServerAccounts();
  }, [loadServerAccounts]);

  const handleConnect = async (platform: string) => {
    if (!activeProject?.id) return;
    const config = getPlatformConfig(platform);
    if (!config?.supportsOAuth) return;

    setConnecting(platform);
    try {
      // Persist the project to MariaDB before OAuth so connected_accounts FK succeeds.
      await flushProjectsSync();
    } catch (err) {
      console.error("Project sync before OAuth failed:", err);
      // Server will still auto-create a stub project if needed.
    }

    const projectId = encodeURIComponent(activeProject.id);

    if (platform === "linkedin") {
      window.location.href = `/api/social/linkedin/connect?projectId=${projectId}`;
      return;
    }
    if (platform === "facebook" || platform === "instagram") {
      window.location.href = `/api/social/meta/connect?projectId=${projectId}&platform=${platform}`;
      return;
    }
    if (platform === "youtube") {
      window.location.href = `/api/social/youtube/connect?projectId=${projectId}`;
    }
  };

  const handleDisconnect = async (platform: string) => {
    if (!activeProject?.id) return;
    useProjectsStore.getState().disconnectActiveAccount(platform);
    try {
      await fetch(
        `/api/projects/${encodeURIComponent(activeProject.id)}/social-accounts/disconnect?platform=${encodeURIComponent(platform)}`,
        { method: "DELETE" },
      );
    } catch {
      // local state already cleared
    }
  };

  const handleFixLinkedIn = async () => {
    if (!activeProject?.id) return;
    setConnecting("linkedin");
    try {
      await flushProjectsSync();
    } catch {
      // stub create on connect still works
    }
    await handleDisconnect("linkedin");
    window.location.href = `/api/social/linkedin/connect?projectId=${encodeURIComponent(activeProject.id)}&reconnect=1`;
  };

  const expiredCount = accounts.filter(
    (a) => a.connected && getAccountHealth(a) === "expired",
  ).length;

  const facebookAccount = accounts.find((a) => a.platform === "facebook");
  const instagramAccount = accounts.find((a) => a.platform === "instagram");
  const facebookConnected = Boolean(facebookAccount?.connected);
  const instagramConnected = Boolean(instagramAccount?.connected);
  const metaBannerVariant =
    !facebookConnected && !instagramConnected
      ? "setup-all"
      : !facebookConnected
        ? "setup-facebook"
        : !instagramConnected
          ? "setup-instagram"
          : null;

  return (
    <DashboardLayout>
      <PageHeader
        title="Connected Accounts"
        subtitle={
          activeProject
            ? `Social accounts for ${activeProject.name} — connect LinkedIn, Facebook, Instagram, and YouTube via OAuth`
            : "Link social media platforms for publishing"
        }
      />
      <div className="flex-1 px-4 pb-32 pt-2 sm:px-6 lg:px-8">
        {linkedInDiag && (
          <div className="mx-auto mb-4 max-w-2xl rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">
            <div className="flex items-start gap-3">
              <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
              <div className="min-w-0 flex-1">
                <p className="font-semibold">LinkedIn publish not ready</p>
                <p className="mt-1">{linkedInDiag}</p>
                <p className="mt-2 text-xs text-red-700">
                  Clear the old token and reconnect so LinkedIn issues a fresh access token with
                  profile + <code className="text-xs">w_member_social</code> publish permission.
                </p>
              </div>
            </div>
            <div className="mt-3 flex justify-end">
              <Button
                type="button"
                size="sm"
                disabled={connecting === "linkedin"}
                onClick={() => void handleFixLinkedIn()}
              >
                Fix LinkedIn Connection
              </Button>
            </div>
          </div>
        )}

        {metaBannerVariant && metaDiag && (
          <MetaSetupBanner
            diagnostics={metaDiag}
            variant={metaBannerVariant}
            facebookPageName={facebookAccount?.profileName}
          />
        )}

        {expiredCount > 0 && (
          <div className="mx-auto mb-4 flex max-w-2xl items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
            <div>
              <p className="font-semibold">Token expired — publishing disabled</p>
              <p className="mt-1">
                {expiredCount} account{expiredCount === 1 ? "" : "s"} need reconnecting before
                you can publish.
              </p>
            </div>
          </div>
        )}

        <div className="mx-auto max-w-2xl space-y-3">
          {(Array.isArray(accounts) ? accounts : []).map((account) => {
            const config = getPlatformConfig(account.platform);
            const health = getAccountHealth(account);
            const isConnected = health === "connected";
            const isExpired = health === "expired";
            const isError = account.connectionStatus === "error";
            const isComingSoon = config?.availability === "coming_soon";
            const oauthLive = Boolean(config?.supportsOAuth);

            return (
              <div
                key={account.platform}
                className={cn(
                  "rounded-[var(--radius-card)] border bg-white p-4 shadow-[var(--shadow-card)]",
                  isExpired || isError ? "border-amber-300 bg-amber-50/30" : "border-gray-100",
                )}
              >
                <div className="flex items-start justify-between gap-4">
                  <div className="flex min-w-0 gap-4">
                    <div
                      className={cn(
                        "flex h-11 w-11 shrink-0 items-center justify-center rounded-lg text-sm font-bold text-white",
                        config?.iconClass ?? "bg-gray-500",
                      )}
                    >
                      {config?.icon ?? "?"}
                    </div>
                    <div className="min-w-0">
                      <div className="flex flex-wrap items-center gap-2">
                        <p className="text-sm font-semibold text-gray-900">{account.label}</p>
                        {isConnected && (
                          <span className="inline-flex items-center gap-1 rounded-full bg-green-50 px-2 py-0.5 text-xs font-medium text-green-700">
                            <CheckCircle2 className="h-3 w-3" />
                            Connected
                          </span>
                        )}
                        {isComingSoon && (
                          <span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600">
                            Coming soon
                          </span>
                        )}
                        {config?.note && !isConnected && !isComingSoon && (
                          <span className="rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">
                            {config.note}
                          </span>
                        )}
                        {isError && (
                          <span className="inline-flex items-center gap-1 rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-800">
                            <AlertTriangle className="h-3 w-3" />
                            Needs reconnect
                          </span>
                        )}
                        {isExpired && (
                          <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800">
                            <AlertTriangle className="h-3 w-3" />
                            Token expired
                          </span>
                        )}
                        {!account.connected && !isComingSoon && (
                          <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600">
                            <XCircle className="h-3 w-3" />
                            Not connected
                          </span>
                        )}
                      </div>
                      {account.connected && (
                        <>
                          <p className="mt-1 text-sm text-gray-700">{account.profileName}</p>
                          <p className="text-xs text-gray-400">
                            Last synced: {formatLastSynced(account.lastSyncedAt)}
                          </p>
                        </>
                      )}
                      {!account.connected && config?.note && (
                        <p className="mt-1 text-xs text-gray-500">{config.note}</p>
                      )}
                    </div>
                  </div>

                  <div className="shrink-0">
                    {!account.connected && oauthLive && (
                      <Button
                        type="button"
                        size="sm"
                        disabled={connecting === account.platform}
                        onClick={() => void handleConnect(account.platform)}
                      >
                        Connect
                      </Button>
                    )}
                    {!account.connected && !oauthLive && !isComingSoon && (
                      <Button type="button" size="sm" variant="secondary" disabled>
                        Soon
                      </Button>
                    )}
                    {(isConnected || isExpired || isError) && oauthLive && account.platform === "linkedin" && isError && (
                      <Button
                        type="button"
                        size="sm"
                        variant="primary"
                        disabled={connecting === account.platform}
                        onClick={() => void handleFixLinkedIn()}
                      >
                        Fix Connection
                      </Button>
                    )}
                    {(isConnected || isExpired) && oauthLive && !(account.platform === "linkedin" && isError) && (
                      <Button
                        type="button"
                        size="sm"
                        variant={isExpired ? "primary" : "secondary"}
                        disabled={connecting === account.platform}
                        onClick={() => void handleConnect(account.platform)}
                      >
                        Reconnect
                      </Button>
                    )}
                    {account.connected && !isExpired && oauthLive && (
                      <button
                        type="button"
                        className="mt-2 block w-full text-xs text-gray-400 hover:text-red-600"
                        onClick={() => void handleDisconnect(account.platform)}
                      >
                        Disconnect
                      </button>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <p className="mx-auto mt-6 max-w-2xl text-sm text-gray-500">
          OAuth tokens are stored securely on the server per user and project. LinkedIn, Facebook,
          and Instagram publishing use the real APIs. YouTube channel connection is live; text-only
          YouTube uploads MP4 when VIDEO_PROVIDER=ffmpeg and a video is generated. X (Twitter) is excluded (paid API).
          Publish logs: <code className="text-xs">logs/publish-YYYY-MM-DD.log</code>
        </p>
      </div>
      <OnboardingFooter currentStep={6} />
    </DashboardLayout>
  );
}
