"use client";

/**
 * Receive — show address + QR so others can send to this mavi wallet.
 * Address is public metadata (no unlock required).
 */

import Link from "next/link";
import QRCode from "qrcode";
import { useEffect, useState } from "react";

import { MaviWalletLogo } from "@/components/wallet/wallet-logos";
import { Button, buttonVariants } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { ErrorBanner } from "@/components/ui/error-banner";
import { hasVault, readVault, shortAddress } from "@/lib/mavi/storage";
import { cn } from "@/lib/utils";

export function ReceivePanel() {
  const [mounted, setMounted] = useState(false);
  const [address, setAddress] = useState<string | null>(null);
  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [shareOk, setShareOk] = useState(false);

  useEffect(() => {
    setMounted(true);
    setShareOk(typeof navigator !== "undefined" && Boolean(navigator.share));
    if (!hasVault()) {
      setAddress(null);
      return;
    }
    const vault = readVault();
    setAddress(vault?.address ?? null);
  }, []);

  useEffect(() => {
    if (!address) {
      setQrDataUrl(null);
      return;
    }
    let cancelled = false;
    void QRCode.toDataURL(address, {
      width: 240,
      margin: 2,
      color: {
        dark: "#0a0a0a",
        light: "#ffffff",
      },
      errorCorrectionLevel: "M",
    })
      .then((url) => {
        if (!cancelled) setQrDataUrl(url);
      })
      .catch(() => {
        if (!cancelled) {
          setError("Could not draw the QR code. You can still copy the address.");
        }
      });
    return () => {
      cancelled = true;
    };
  }, [address]);

  function onCopy() {
    if (!address) return;
    void navigator.clipboard.writeText(address).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    });
  }

  async function onShare() {
    if (!address || !navigator.share) return;
    try {
      await navigator.share({
        title: "mavi wallet address",
        text: address,
      });
    } catch {
      /* user cancelled */
    }
  }

  if (!mounted) {
    return (
      <Card>
        <CardContent className="py-10 text-center text-sm text-muted-foreground">
          Loading…
        </CardContent>
      </Card>
    );
  }

  if (!address) {
    return (
      <EmptyState
        title="No mavi wallet yet"
        description="Create or import a wallet first. Then this page shows your address and a QR code so others can send to you."
        action={
          <div className="flex w-full max-w-sm flex-col gap-2">
            <Link
              href="/portal/mavi/create"
              className={cn(
                buttonVariants({ variant: "primary" }),
                "inline-flex items-center justify-center gap-2",
              )}
            >
              <MaviWalletLogo size={18} />
              Create mavi wallet
            </Link>
            <Link
              href="/portal/mavi/import"
              className={cn(buttonVariants({ variant: "outline" }), "w-full")}
            >
              Import recovery phrase
            </Link>
          </div>
        }
      />
    );
  }

  return (
    <Card>
      <CardHeader>
        <div className="mb-2 flex items-center gap-2">
          <MaviWalletLogo size={28} />
          <CardTitle>Receive</CardTitle>
        </div>
        <CardDescription>
          Share this address so someone can send to your mavi wallet. Anyone
          with the address can send; only you control spending with your
          password and recovery phrase.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-5">
        {error ? <ErrorBanner title="QR note">{error}</ErrorBanner> : null}

        <div className="flex flex-col items-center gap-3">
          <div className="rounded-2xl border border-border bg-white p-4 shadow-sm">
            {qrDataUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={qrDataUrl}
                alt={`QR code for ${shortAddress(address)}`}
                width={240}
                height={240}
                className="h-60 w-60"
              />
            ) : (
              <div
                className="flex h-60 w-60 items-center justify-center text-sm text-muted-foreground"
                aria-busy="true"
              >
                Drawing QR…
              </div>
            )}
          </div>
          <p className="text-center text-xs text-muted-foreground">
            Scan with a wallet camera · short form{" "}
            <span className="font-mono text-foreground">
              {shortAddress(address)}
            </span>
          </p>
        </div>

        <div className="rounded-xl border border-border bg-muted/30 px-4 py-3">
          <p className="text-xs uppercase tracking-wide text-muted-foreground">
            Your address
          </p>
          <p className="mt-1 break-all font-mono text-sm text-foreground">
            {address}
          </p>
        </div>

        <div className="flex flex-col gap-2 sm:flex-row">
          <Button type="button" className="sm:flex-1" onClick={onCopy}>
            {copied ? "Copied" : "Copy address"}
          </Button>
          {shareOk ? (
            <Button
              type="button"
              variant="outline"
              className="sm:flex-1"
              onClick={() => void onShare()}
            >
              Share
            </Button>
          ) : null}
          <Link
            href="/portal/mavi"
            className={cn(
              buttonVariants({ variant: "ghost" }),
              "sm:flex-1 text-center",
            )}
          >
            Back to mavi
          </Link>
        </div>
      </CardContent>
    </Card>
  );
}
