"use client";

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

import { Badge } from "@/components/ui/badge";
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 {
  clearActivityForWallet,
  formatActivityTime,
  readActivityForWallet,
  shortHash,
  type MaviActivityItem,
} from "@/lib/mavi/activity";
import { shortAddress } from "@/lib/mavi/storage";
import { cn } from "@/lib/utils";

// Re-export for callers that imported from this module earlier
export { notifyActivityChanged } from "@/lib/mavi/activity";

export function ActivityList({
  walletAddress,
  /** Compact strip on home (fewer rows) */
  compact = false,
  className,
}: {
  walletAddress: string;
  compact?: boolean;
  className?: string;
}) {
  const [items, setItems] = useState<MaviActivityItem[]>([]);
  const [mounted, setMounted] = useState(false);

  const refresh = useCallback(() => {
    setItems(readActivityForWallet(walletAddress, compact ? 5 : 30));
  }, [compact, walletAddress]);

  useEffect(() => {
    setMounted(true);
    refresh();
    const onStorage = (e: StorageEvent) => {
      if (e.key === "mavi_activity_v1" || e.key === null) refresh();
    };
    window.addEventListener("storage", onStorage);
    window.addEventListener("mavi-activity", refresh);
    return () => {
      window.removeEventListener("storage", onStorage);
      window.removeEventListener("mavi-activity", refresh);
    };
  }, [refresh]);

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

  return (
    <Card className={className}>
      <CardHeader className="flex flex-row flex-wrap items-start justify-between gap-2">
        <div>
          <CardTitle className="text-base">Activity</CardTitle>
          <CardDescription>
            Recent mavi actions in this browser (not a full chain explorer).
          </CardDescription>
        </div>
        {items.length > 0 && !compact ? (
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => {
              if (
                window.confirm(
                  "Clear activity history for this wallet on this browser?",
                )
              ) {
                clearActivityForWallet(walletAddress);
                refresh();
              }
            }}
          >
            Clear
          </Button>
        ) : null}
      </CardHeader>
      <CardContent className="space-y-3">
        {items.length === 0 ? (
          <EmptyState
            className="border-0 bg-transparent py-6"
            title="No activity yet"
            description="When you send or get test ETH, it shows up here."
            action={
              <Link
                href="/portal/mavi/send"
                className={cn(buttonVariants({ size: "sm" }))}
              >
                Send
              </Link>
            }
          />
        ) : (
          <ul className="space-y-2">
            {items.map((item) => (
              <li
                key={item.id}
                className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border/70 bg-muted/20 px-3 py-2.5"
              >
                <div className="min-w-0">
                  <div className="flex flex-wrap items-center gap-2">
                    <Badge variant="outline">{kindLabel(item.kind)}</Badge>
                    {item.amountEth ? (
                      <span className="text-sm font-medium tabular-nums">
                        {item.kind === "send" ? "−" : "+"}
                        {trimEth(item.amountEth)} ETH
                      </span>
                    ) : null}
                  </div>
                  <p className="mt-1 text-xs text-muted-foreground">
                    {item.kind === "send" && item.to
                      ? `To ${shortAddress(item.to)}`
                      : item.kind === "fund"
                        ? "From local test bank"
                        : item.note ?? ""}
                    {item.hash ? (
                      <>
                        {" · "}
                        <span className="font-mono">{shortHash(item.hash)}</span>
                      </>
                    ) : null}
                  </p>
                </div>
                <time
                  className="shrink-0 text-[11px] text-muted-foreground"
                  dateTime={item.at}
                >
                  {formatActivityTime(item.at)}
                </time>
              </li>
            ))}
          </ul>
        )}
        {compact && items.length > 0 ? (
          <Link
            href="/portal/mavi/activity"
            className={cn(
              buttonVariants({ variant: "ghost", size: "sm" }),
              "px-0",
            )}
          >
            Full activity →
          </Link>
        ) : null}
      </CardContent>
    </Card>
  );
}

function kindLabel(kind: MaviActivityItem["kind"]): string {
  switch (kind) {
    case "send":
      return "Sent";
    case "fund":
      return "Test ETH";
    case "receive_note":
      return "Received";
    default:
      return kind;
  }
}

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+$/, "");
}


