"use client";

/**
 * MetaMask + mavi shown the same way (logo, name, address, actions).
 */

import { injected } from "@wagmi/connectors/injected";
import Link from "next/link";
import { useEffect, useState, type ReactNode } from "react";
import {
  useAccount,
  useChainId,
  useConnect,
  useDisconnect,
  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, readVault, shortAddress } from "@/lib/mavi/storage";
import { establishPortalSession } from "@/lib/portal-session";
import { cn } from "@/lib/utils";

export function WalletsPanel({
  className,
  /** Also open portal session when MetaMask connects */
  asLogin = false,
  onConnected,
}: {
  className?: string;
  asLogin?: boolean;
  onConnected?: (address: string) => void;
}) {
  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 [maviAddr, setMaviAddr] = useState<string | null>(null);
  const [maviSaved, setMaviSaved] = useState(false);

  useEffect(() => {
    const vault = readVault();
    setMaviSaved(hasVault());
    setMaviAddr(vault?.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();
    }
  }

  const mmConnected = isConnected && Boolean(address);

  return (
    <div className={cn("space-y-3", className)}>
      {/* MetaMask — same card shape as mavi */}
      <WalletRow
        logo={<MetaMaskLogo size={22} />}
        name="MetaMask"
        status={mmConnected ? "connected" : "not connected"}
        address={mmConnected ? address! : null}
        detail={mmConnected ? `chain id ${chainId}` : "Browser extension"}
        actions={
          mmConnected ? (
            <>
              <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}
            </>
          ) : (
            <Button
              type="button"
              size="sm"
              disabled={isConnecting || isPending}
              onClick={handleConnect}
            >
              {isConnecting || isPending ? "Connecting…" : "Connect"}
            </Button>
          )
        }
      />

      {/* mavi — same card shape */}
      <WalletRow
        logo={<MaviWalletLogo size={22} />}
        name="mavi wallet"
        status={maviSaved ? "saved on this browser" : "not created"}
        address={maviSaved && maviAddr ? maviAddr : null}
        detail={
          maviSaved
            ? "24-word recovery · encrypted here"
            : "Create + back up 24 words"
        }
        actions={
          maviSaved ? (
            <Link
              href="/portal/mavi"
              className={cn(
                buttonVariants({ variant: "outline", size: "sm" }),
                "inline-flex items-center gap-2",
              )}
            >
              <MaviWalletLogo size={16} />
              mavi wallet
            </Link>
          ) : (
            <>
              <Link
                href="/portal/mavi/create"
                className={cn(
                  buttonVariants({ size: "sm" }),
                  "inline-flex items-center gap-2",
                )}
              >
                <MaviWalletLogo size={16} />
                mavi wallet
              </Link>
              <Link
                href="/portal/mavi/import"
                className={cn(buttonVariants({ variant: "ghost", size: "sm" }))}
              >
                Import
              </Link>
            </>
          )
        }
      />

      {error ? (
        <p className="text-sm text-pending" role="alert">
          {error.message}
        </p>
      ) : null}
    </div>
  );
}

function WalletRow({
  logo,
  name,
  status,
  address,
  detail,
  actions,
}: {
  logo: ReactNode;
  name: string;
  status: string;
  address: string | null;
  detail: string;
  actions: ReactNode;
}) {
  return (
    <div className="rounded-xl border border-border bg-muted/20 px-3 py-3">
      <div className="flex items-start gap-3">
        <div className="mt-0.5 shrink-0">{logo}</div>
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-center gap-2">
            <p className="text-sm font-medium text-foreground">{name}</p>
            <span className="rounded-full border border-border px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">
              {status}
            </span>
          </div>
          {address ? (
            <p className="mt-1 break-all font-mono text-xs text-foreground">
              {address}
            </p>
          ) : (
            <p className="mt-1 font-mono text-xs text-muted-foreground">
              No address yet
            </p>
          )}
          <p className="mt-0.5 text-[11px] text-muted-foreground">{detail}</p>
          {address ? (
            <p className="mt-0.5 text-[11px] text-muted-foreground">
              Short: {shortAddress(address)}
            </p>
          ) : null}
          <div className="mt-2 flex flex-wrap gap-2">{actions}</div>
        </div>
      </div>
    </div>
  );
}
