"use client";

import { AlertTriangle, Check, Copy, ExternalLink, Info } from "lucide-react";
import { useCallback, useState } from "react";
import { Button } from "@/components/ui/button";

export type MetaSetupBannerVariant = "setup-all" | "setup-facebook" | "setup-instagram";

export interface MetaDiagnostics {
  appId: string | null;
  redirectUri: string;
  facebookScopes: string[];
  instagramScopes: string[];
  steps: string[];
  portalLinks?: {
    appDashboard?: string;
    useCases?: string;
    fbLoginSettings?: string;
    appReview?: string;
  };
}

interface MetaSetupBannerProps {
  diagnostics: MetaDiagnostics;
  variant: MetaSetupBannerVariant;
  facebookPageName?: string;
}

export function MetaSetupBanner({ diagnostics, variant, facebookPageName }: MetaSetupBannerProps) {
  const [copied, setCopied] = useState(false);
  const isInstagramOnly = variant === "setup-instagram";
  const links = diagnostics.portalLinks ?? {};

  const copyRedirectUri = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(diagnostics.redirectUri);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // ignore
    }
  }, [diagnostics.redirectUri]);

  const scopes = (isInstagramOnly ? diagnostics.instagramScopes : diagnostics.facebookScopes) ?? [];

  return (
    <div
      className={
        isInstagramOnly
          ? "mx-auto mb-4 max-w-2xl rounded-lg border border-blue-200 bg-blue-50 px-4 py-4 text-sm text-blue-950"
          : "mx-auto mb-4 max-w-2xl rounded-lg border border-red-200 bg-red-50 px-4 py-4 text-sm text-red-900"
      }
    >
      <div className="flex items-start gap-3">
        {isInstagramOnly ? (
          <Info className="mt-0.5 h-5 w-5 shrink-0 text-blue-600" />
        ) : (
          <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-red-600" />
        )}
        <div className="min-w-0 flex-1 space-y-3">
          <div>
            <p className={`font-semibold ${isInstagramOnly ? "text-blue-950" : "text-red-950"}`}>
              {isInstagramOnly
                ? "Facebook connected — set up Instagram publishing"
                : "Fix Facebook / Instagram — Meta Developer Portal (one-time)"}
            </p>
            <p className={`mt-1 ${isInstagramOnly ? "text-blue-900" : "text-red-800"}`}>
              {isInstagramOnly ? (
                <>
                  Your Facebook Page is connected. This banner is <strong>not</strong> a Facebook
                  error. Connect Instagram below — if Meta shows <strong>Invalid Scopes</strong>, your
                  app is missing Instagram permissions (see steps).
                </>
              ) : (
                <>
                  <strong>Invalid Scopes</strong> appears when Meta rejects Page permissions during
                  OAuth. Complete the steps below in the Meta Developer Portal, then click{" "}
                  <strong>Connect</strong> on Facebook.
                </>
              )}
            </p>
          </div>

          {diagnostics.appId && (
            <p className={`text-xs ${isInstagramOnly ? "text-blue-800" : "text-red-800"}`}>
              Meta App ID: <code className="rounded bg-white/70 px-1">{diagnostics.appId}</code>
            </p>
          )}

          <div
            className={`rounded-md border p-3 ${
              isInstagramOnly ? "border-blue-200 bg-white/60" : "border-red-200 bg-white/60"
            }`}
          >
            <p className={`text-xs font-semibold ${isInstagramOnly ? "text-blue-950" : "text-red-950"}`}>
              {isInstagramOnly ? "Instagram setup" : "Facebook Page setup (about 10 minutes)"}
            </p>
            <ol
              className={`mt-2 list-decimal space-y-2 pl-4 text-xs ${
                isInstagramOnly ? "text-blue-900" : "text-red-900"
              }`}
            >
              {isInstagramOnly ? (
                <>
                  <li>
                    In Meta Business Suite, link your <strong>Instagram Business</strong> account to
                    the Facebook Page{" "}
                    <strong>{facebookPageName ?? "connected above"}</strong> (Settings → Linked
                    accounts).
                  </li>
                  <li>
                    Open{" "}
                    {links.useCases ? (
                      <a href={links.useCases} target="_blank" rel="noreferrer" className="font-medium underline">
                        Meta → Use cases
                      </a>
                    ) : (
                      "Meta Developer Portal → Use cases"
                    )}
                    . Ensure <strong>Manage everything on your Page</strong> is added. Also add{" "}
                    <strong>Instagram</strong> / content publishing use case if offered.
                  </li>
                  <li>
                    Under App Review → Permissions, confirm{" "}
                    <code className="text-[11px]">instagram_basic</code> and{" "}
                    <code className="text-[11px]">instagram_content_publish</code> are available
                    (Development mode: app role users only).
                  </li>
                  <li>
                    Whitelist redirect URI under Facebook Login → Settings:{" "}
                    <code className="break-all text-[11px]">{diagnostics.redirectUri}</code>
                  </li>
                  <li>
                    Return here → click <strong>Connect</strong> on Instagram (uses the same Meta
                    app as Facebook).
                  </li>
                </>
              ) : (
                <>
                  <li>
                    Open{" "}
                    {links.useCases ? (
                      <a href={links.useCases} target="_blank" rel="noreferrer" className="font-medium underline">
                        Meta → Use cases
                      </a>
                    ) : (
                      "Meta Developer Portal → your app → Use cases"
                    )}
                    . Click <strong>Add use cases</strong> → select{" "}
                    <strong>Manage everything on your Page</strong> → Save.
                  </li>
                  <li>
                    Open{" "}
                    {links.fbLoginSettings ? (
                      <a
                        href={links.fbLoginSettings}
                        target="_blank"
                        rel="noreferrer"
                        className="font-medium underline"
                      >
                        Facebook Login → Settings
                      </a>
                    ) : (
                      "Facebook Login for Business → Settings"
                    )}
                    . Turn on <strong>Client OAuth Login</strong> and <strong>Web OAuth Login</strong>.
                  </li>
                  <li>
                    Under <strong>Valid OAuth Redirect URIs</strong>, paste exactly (no trailing slash):
                    <div className="mt-1 flex flex-wrap items-center gap-2">
                      <code className="break-all rounded bg-red-50 px-2 py-1 text-[11px]">
                        {diagnostics.redirectUri}
                      </code>
                      <Button type="button" size="sm" variant="secondary" onClick={() => void copyRedirectUri()}>
                        {copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
                        {copied ? "Copied" : "Copy URI"}
                      </Button>
                    </div>
                  </li>
                  <li>
                    <strong>App roles</strong> → add the Facebook account you log in with as{" "}
                    <strong>Administrator</strong> or <strong>Developer</strong>.
                  </li>
                  <li>
                    Wait 2–5 minutes. Graph API Explorer should list{" "}
                    <code className="text-[11px]">pages_show_list</code> and{" "}
                    <code className="text-[11px]">pages_manage_posts</code>.
                  </li>
                  <li>
                    Return here → click <strong>Connect</strong> on Facebook.
                  </li>
                </>
              )}
            </ol>
          </div>

          <p className={`text-xs ${isInstagramOnly ? "text-blue-800" : "text-red-800"}`}>
            Scopes PostSync requests for {isInstagramOnly ? "Instagram" : "Facebook"}:{" "}
            <code className="text-[11px]">{scopes.join(", ")}</code>
          </p>

          <div className="flex flex-wrap gap-2">
            {links.appDashboard && (
              <a
                href={links.appDashboard}
                target="_blank"
                rel="noreferrer"
                className={`inline-flex items-center gap-1 rounded-md border bg-white px-3 py-1.5 text-xs font-medium hover:bg-white/80 ${
                  isInstagramOnly ? "border-blue-300 text-blue-900" : "border-red-300 text-red-900"
                }`}
              >
                Open Meta App Dashboard
                <ExternalLink className="h-3 w-3" />
              </a>
            )}
            <a
              href={
                isInstagramOnly
                  ? "https://developers.facebook.com/docs/instagram-api/getting-started"
                  : "https://developers.facebook.com/docs/pages-api/create-an-app/"
              }
              target="_blank"
              rel="noreferrer"
              className={`inline-flex items-center gap-1 rounded-md border bg-white px-3 py-1.5 text-xs font-medium hover:bg-white/80 ${
                isInstagramOnly ? "border-blue-300 text-blue-900" : "border-red-300 text-red-900"
              }`}
            >
              Official setup guide
              <ExternalLink className="h-3 w-3" />
            </a>
          </div>

          {!isInstagramOnly && (
            <p className="text-xs text-red-700">
              If your app was created as consumer Facebook Login only, create a{" "}
              <strong>Business app</strong> with the Page use case, then update{" "}
              <code className="text-[11px]">FACEBOOK_CLIENT_ID</code> and{" "}
              <code className="text-[11px]">FACEBOOK_CLIENT_SECRET</code> on the server.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
