"use client";

import { AlertCircle, CheckCircle2, Loader2 } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { useProjectsStore } from "@/store/projects-store";

interface SocialOAuthCallbackProps {
  platformLabel: string;
  callbackPath: string;
}

function SocialOAuthCallbackContent({ platformLabel, callbackPath }: SocialOAuthCallbackProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const switchProject = useProjectsStore((s) => s.switchProject);
  const connectActiveAccount = useProjectsStore((s) => s.connectActiveAccount);

  const [status, setStatus] = useState<"processing" | "success" | "error">("processing");
  const [errorMessage, setErrorMessage] = useState("");

  const code = searchParams.get("code");
  const state = searchParams.get("state");
  const error = searchParams.get("error");
  const errorDescription = searchParams.get("error_description");

  useEffect(() => {
    if (error) {
      setStatus("error");
      const raw = errorDescription ?? error;
      if (/instagram business/i.test(raw) || /linked to your facebook page/i.test(raw)) {
        setErrorMessage(
          raw +
            " Instagram uses Meta login (Facebook screen) — that is normal. " +
            "You need an Instagram Business or Creator account linked to your Facebook Page in Meta Business Suite before Connect will succeed.",
        );
      } else if (/invalid scopes/i.test(raw)) {
        setErrorMessage(
          "Meta Invalid Scopes: your Facebook app does not have Page publishing permissions enabled. " +
            "In Meta Developer Portal, add the use case \"Manage everything on your Page\", enable " +
            "Facebook Login for Business, whitelist the redirect URI, then try Connect again. " +
            "PostSync Pro OAuth URL is already correct.",
        );
      } else {
        setErrorMessage(raw);
      }
      return;
    }

    if (!code || !state) {
      setStatus("error");
      setErrorMessage("Missing authorization code or state.");
      return;
    }

    let cancelled = false;

    (async () => {
      try {
        const res = await fetch(callbackPath, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ code, state }),
        });

        const data = (await res.json()) as {
          success?: boolean;
          projectId?: string;
          returnTo?: string;
          platform?: string;
          profileName?: string;
          externalId?: string;
          expiresAt?: string | null;
          error?: string;
        };

        if (!res.ok || !data.success || !data.projectId || !data.platform) {
          throw new Error(data.error ?? `${platformLabel} connection failed`);
        }

        if (data.projectId !== useProjectsStore.getState().activeProjectId) {
          switchProject(data.projectId);
        }

        connectActiveAccount(data.platform, data.profileName ?? platformLabel, {
          externalId: data.externalId,
          expiresAt: data.expiresAt ?? undefined,
        });

        if (!cancelled) {
          setStatus("success");
          setTimeout(() => {
            router.replace(data.returnTo ?? "/connected-accounts");
          }, 800);
        }
      } catch (err) {
        if (!cancelled) {
          setStatus("error");
          setErrorMessage(err instanceof Error ? err.message : `${platformLabel} connection failed`);
        }
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [code, state, error, errorDescription, connectActiveAccount, router, switchProject, callbackPath, platformLabel]);

  return (
    <Card className="w-full max-w-md p-8">
      <div className="space-y-4 text-center">
        {status === "processing" && (
          <>
            <Loader2 className="mx-auto h-8 w-8 animate-spin text-brand-600" />
            <p className="font-medium text-gray-900">Connecting {platformLabel} to your project…</p>
          </>
        )}
        {status === "success" && (
          <>
            <CheckCircle2 className="mx-auto h-8 w-8 text-green-600" />
            <p className="font-medium text-gray-900">{platformLabel} connected</p>
          </>
        )}
        {status === "error" && (
          <>
            <AlertCircle className="mx-auto h-8 w-8 text-red-500" />
            <p className="font-medium text-gray-900">Connection failed</p>
            <p className="text-sm text-gray-500">{errorMessage}</p>
            <Link
              href="/connected-accounts"
              className="inline-flex items-center justify-center rounded-[var(--radius-button)] border border-gray-200 bg-white px-5 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50"
            >
              Back to Connected Accounts
            </Link>
          </>
        )}
      </div>
    </Card>
  );
}

export function SocialOAuthCallbackPage(props: SocialOAuthCallbackProps) {
  return (
    <div className="flex min-h-screen items-center justify-center bg-surface p-4">
      <Suspense fallback={<Loader2 className="h-8 w-8 animate-spin text-brand-600" />}>
        <SocialOAuthCallbackContent {...props} />
      </Suspense>
    </div>
  );
}
