"use client";

import { injected } from "@wagmi/connectors/injected";
import Link from "next/link";
import {
  useAccount,
  useConnect,
  useDisconnect,
  useChainId,
  useSwitchChain,
} from "wagmi";

import { usePortalAuth } from "@/components/auth/portal-auth-provider";
import { Button, buttonVariants } from "@/components/ui/button";
import {
  MetaMaskLogo,
  MaviWalletLogo,
} from "@/components/wallet/wallet-logos";
import { createDemoWalletSession } from "@/lib/demo-session";
import { hasVault, shortAddress, readVault } from "@/lib/mavi/storage";
import { establishPortalSession } from "@/lib/portal-session";
import { cn } from "@/lib/utils";
import { useEffect, useState } from "react";

export function ConnectWalletButton({
  className,
  onConnected,
  /** Compact layout for dashboard cards */
  compact = false,
  /** Show mavi wallet row under MetaMask */
  showMavi = true,
  /** Also mint portal session (same as sign-in) so dashboard stays open */
  asLogin = false,
}: {
  className?: string;
  onConnected?: (address: string) => void;
  compact?: boolean;
  showMavi?: boolean;
  asLogin?: boolean;
}) {
  const { address, isConnected, isConnecting } = useAccount();
  const { connect, error, isPending } = useConnect();
  const { disconnect } = useDisconnect();
  const chainId = useChainId();
  const { switchChain } = useSwitchChain();
  const { setDemoSession, clearDemo, demoSession } = usePortalAuth();
  const [maviVault, setMaviVault] = useState(false);
  const [maviAddr, setMaviAddr] = useState<string | null>(null);

  useEffect(() => {
    setMaviVault(hasVault());
    setMaviAddr(readVault()?.address ?? null);
  }, []);

  function handleConnect() {
    connect(
      { connector: injected() },
      {
        onSuccess: (data) => {
          const addr = data.accounts[0];
          if (addr) {
            setDemoSession(createDemoWalletSession(addr));
            if (asLogin) {
              void establishPortalSession({
                userId: `wallet_${addr.toLowerCase()}`,
                method: "wallet",
                walletAddress: addr,
              }).then(() => {
                window.dispatchEvent(new Event("krypco-auth-change"));
                onConnected?.(addr);
              });
            } else {
              onConnected?.(addr);
            }
          }
        },
      },
    );
  }

  function handleDisconnect() {
    disconnect();
    if (demoSession?.kind === "wallet") {
      clearDemo();
    }
  }

  if (isConnected && address) {
    return (
      <div className={className}>
        <div className="mb-2 flex items-center gap-2">
          <MetaMaskLogo size={compact ? 18 : 22} />
          <span className="text-xs font-medium text-muted-foreground">
            MetaMask
          </span>
        </div>
        <p
          className={
            compact
              ? "mb-2 font-mono text-xs text-foreground break-all"
              : "mb-2 font-mono text-xs text-muted-foreground break-all"
          }
        >
          {address}
        </p>
        <p className="mb-2 text-xs text-muted-foreground">
          chain id {chainId}
        </p>
        <div className="flex flex-wrap gap-2">
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={handleDisconnect}
          >
            Disconnect
          </Button>
          {chainId !== 31337 && switchChain ? (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => switchChain({ chainId: 31337 })}
            >
              Switch to local anvil
            </Button>
          ) : null}
        </div>
        {showMavi ? (
          <MaviLinkRow compact={compact} hasVault={maviVault} address={maviAddr} />
        ) : null}
      </div>
    );
  }

  return (
    <div className={className}>
      <div className="flex flex-col gap-2">
        <Button
          type="button"
          size={compact ? "sm" : "md"}
          className="inline-flex w-full items-center justify-center gap-2"
          disabled={isConnecting || isPending}
          onClick={handleConnect}
        >
          <MetaMaskLogo size={compact ? 18 : 20} />
          {isConnecting || isPending ? "Connecting…" : "Connect MetaMask"}
        </Button>

        {showMavi ? (
          <Link
            href={maviVault ? "/portal/mavi" : "/portal/mavi/create"}
            className={cn(
              buttonVariants({
                variant: "outline",
                size: compact ? "sm" : "md",
              }),
              "inline-flex w-full items-center justify-center gap-2",
            )}
          >
            <MaviWalletLogo size={compact ? 18 : 20} />
            mavi wallet
          </Link>
        ) : null}
      </div>

      {error ? (
        <p className="mt-2 text-sm text-pending" role="alert">
          {error.message}
        </p>
      ) : !compact ? (
        <p className="mt-2 text-xs text-muted-foreground leading-relaxed">
          <strong className="font-medium text-foreground">MetaMask</strong> is
          the browser extension.{" "}
          <strong className="font-medium text-foreground">mavi</strong> is
          krypco&apos;s wallet (create + backup on this site).
        </p>
      ) : (
        <p className="mt-2 text-xs text-muted-foreground">
          MetaMask extension or mavi on this site.
        </p>
      )}
    </div>
  );
}

function MaviLinkRow({
  compact,
  hasVault: vault,
  address,
}: {
  compact?: boolean;
  hasVault: boolean;
  address: string | null;
}) {
  return (
    <div
      className={
        compact
          ? "mt-3 flex items-center gap-2 rounded-lg border border-border/70 bg-muted/30 px-2.5 py-2"
          : "mt-4 flex items-center gap-3 rounded-lg border border-border/70 bg-muted/30 px-3 py-2.5"
      }
    >
      <MaviWalletLogo size={compact ? 18 : 22} />
      <div className="min-w-0 text-left">
        <p className="text-xs font-medium text-foreground">mavi wallet</p>
        <p className="text-[11px] text-muted-foreground leading-snug">
          {vault && address
            ? `Saved · ${shortAddress(address)}`
            : "Create + back up recovery phrase"}
        </p>
      </div>
      <Link
        href={vault ? "/portal/mavi" : "/portal/mavi/create"}
        className="ml-auto inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border px-2 py-0.5 text-[10px] font-medium tracking-wide text-muted-foreground hover:text-foreground"
      >
        <MaviWalletLogo size={12} />
        mavi wallet
      </Link>
    </div>
  );
}
