"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

import { UnlockPanel } from "@/components/mavi/unlock-panel";
import { MaviWalletLogo } from "@/components/wallet/wallet-logos";
import { Badge } from "@/components/ui/badge";
import { Button, buttonVariants } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { ErrorBanner } from "@/components/ui/error-banner";
import { Input } from "@/components/ui/input";
import {
  addActivity,
  notifyActivityChanged,
} from "@/lib/mavi/activity";
import {
  fetchEthBalance,
  isValidEthAddress,
  sendEth,
} from "@/lib/mavi/chain";
import { getActiveNetwork } from "@/lib/mavi/network";
import {
  hasVault,
  readUnlockedSession,
  type UnlockedMavi,
} from "@/lib/mavi/storage";
import { cn } from "@/lib/utils";

export function SendForm() {
  const router = useRouter();
  const [mounted, setMounted] = useState(false);
  const [exists, setExists] = useState(false);
  const [unlocked, setUnlocked] = useState<UnlockedMavi | null>(null);
  const [to, setTo] = useState("");
  const [amount, setAmount] = useState("0.01");
  const [balance, setBalance] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [txHash, setTxHash] = useState<string | null>(null);
  const [netLabel, setNetLabel] = useState("");

  useEffect(() => {
    setMounted(true);
    setExists(hasVault());
    setUnlocked(readUnlockedSession());
    setNetLabel(getActiveNetwork().shortLabel);
    const sync = () => {
      setUnlocked(readUnlockedSession());
      setNetLabel(getActiveNetwork().shortLabel);
    };
    window.addEventListener("mavi-unlock", sync);
    window.addEventListener("mavi-network", sync);
    return () => {
      window.removeEventListener("mavi-unlock", sync);
      window.removeEventListener("mavi-network", sync);
    };
  }, []);

  useEffect(() => {
    if (!unlocked) return;
    let cancelled = false;
    void fetchEthBalance(unlocked.address).then((b) => {
      if (!cancelled && b.ok) setBalance(b.eth);
    });
    return () => {
      cancelled = true;
    };
  }, [unlocked, netLabel]);

  async function onSend() {
    if (!unlocked) return;
    setError(null);
    setTxHash(null);
    const dest = to.trim() as `0x${string}`;
    if (!isValidEthAddress(dest)) {
      setError("Enter a valid address starting with 0x (40 hex characters).");
      return;
    }
    const amt = amount.trim();
    if (!amt || Number.isNaN(Number(amt)) || Number(amt) <= 0) {
      setError("Enter an amount greater than 0.");
      return;
    }
    setBusy(true);
    try {
      const { hash } = await sendEth({
        privateKey: unlocked.privateKey,
        to: dest,
        amountEth: amt,
      });
      setTxHash(hash);
      addActivity({
        kind: "send",
        wallet: unlocked.address,
        hash,
        to: dest,
        from: unlocked.address,
        amountEth: amt,
        note: getActiveNetwork().shortLabel,
      });
      notifyActivityChanged();
      const b = await fetchEthBalance(unlocked.address);
      if (b.ok) setBalance(b.eth);
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Send failed";
      setError(
        /connect|fetch|network|ECONNREFUSED/i.test(msg)
          ? "Local chain is not running. Start it with: bun run chains:up"
          : msg,
      );
    } finally {
      setBusy(false);
    }
  }

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

  if (!exists) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>No mavi wallet</CardTitle>
          <CardDescription>
            Create or import a wallet before sending.
          </CardDescription>
        </CardHeader>
        <CardContent className="flex 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>
        </CardContent>
      </Card>
    );
  }

  if (!unlocked) {
    return (
      <Card>
        <CardHeader>
          <div className="mb-2 flex flex-wrap items-center gap-2">
            <MaviWalletLogo size={28} />
            <CardTitle>Unlock to send</CardTitle>
            <Badge variant="pending">Locked</Badge>
          </div>
          <CardDescription>
            Unlock once for this tab — then send without re-entering the
            password until you lock.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <UnlockPanel
            onUnlocked={(u) => {
              setUnlocked(u);
              setError(null);
            }}
            title="Password"
            description="Same unlock as mavi home. Stays open in this tab."
            submitLabel="Unlock and continue"
          />
          <p className="mt-4 text-center text-xs text-muted-foreground">
            Or unlock on{" "}
            <Link
              href="/portal/mavi?next=/portal/mavi/send"
              className="text-accent-hover underline-offset-2 hover:underline"
            >
              mavi home
            </Link>{" "}
            first.
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <div className="mb-2 flex flex-wrap items-center gap-2">
          <MaviWalletLogo size={28} />
          <CardTitle>Send</CardTitle>
          <Badge variant="anchored">Unlocked</Badge>
        </div>
        <CardDescription>
          Network: <strong className="text-foreground">{netLabel}</strong>
          {" · "}
          from{" "}
          <span className="font-mono text-foreground">
            {unlocked.address.slice(0, 8)}…
          </span>
          {balance != null ? ` · balance ${trimEth(balance)} ETH` : null}
          . Change network on mavi home.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {error ? <ErrorBanner title="Send failed">{error}</ErrorBanner> : null}
        {txHash ? (
          <div className="rounded-xl border border-proof/30 bg-proof/5 px-4 py-3 text-sm">
            <p className="font-medium text-proof">Sent</p>
            <p className="mt-1 break-all font-mono text-xs text-muted-foreground">
              {txHash}
            </p>
          </div>
        ) : null}

        <div className="space-y-2">
          <label htmlFor="mavi-to" className="text-sm font-medium">
            To address
          </label>
          <Input
            id="mavi-to"
            value={to}
            onChange={(e) => setTo(e.target.value)}
            placeholder="0x…"
            spellCheck={false}
            autoCapitalize="none"
            className="font-mono"
          />
        </div>
        <div className="space-y-2">
          <label htmlFor="mavi-amount" className="text-sm font-medium">
            Amount (ETH)
          </label>
          <Input
            id="mavi-amount"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            inputMode="decimal"
            placeholder="0.01"
          />
        </div>
        <div className="flex flex-col gap-2 sm:flex-row">
          <Button
            type="button"
            variant="outline"
            className="sm:flex-1"
            onClick={() => router.push("/portal/mavi")}
          >
            Back
          </Button>
          <Button
            type="button"
            className="sm:flex-1"
            disabled={busy}
            onClick={() => void onSend()}
          >
            {busy ? "Sending…" : "Send"}
          </Button>
        </div>
        <p className="text-xs text-muted-foreground leading-relaxed">
          If the chain is down, run{" "}
          <code className="text-foreground">bun run chains:up</code>. New
          wallets need test ETH — use Get test ETH on mavi home.
        </p>
      </CardContent>
    </Card>
  );
}

function trimEth(eth: string): string {
  const n = Number(eth);
  if (!Number.isFinite(n)) return eth;
  if (n === 0) return "0";
  if (n >= 1) return n.toFixed(4).replace(/\.?0+$/, "");
  return n.toFixed(6).replace(/\.?0+$/, "");
}
