"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Wallet, ArrowUpRight, ArrowDownLeft, ExternalLink } from "lucide-react";
import { useCurrency } from "@/lib/currency";
import { timeAgo } from "@/lib/utils";
import clsx from "clsx";

type Tx = { id: string; kind: string; amount: number; note?: string; createdAt: string };

/** A compact wallet summary, so sellers don't leave their storefront. */
export function WalletPanel() {
  const [balance, setBalance] = useState<number | null>(null);
  const [txs, setTxs] = useState<Tx[]>([]);
  const { format: money } = useCurrency();

  useEffect(() => {
    fetch("/api/wallet")
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (!d) return;
        setBalance(d.balance ?? 0);
        setTxs(Array.isArray(d.transactions) ? d.transactions.slice(0, 8) : []);
      })
      .catch(() => {});
  }, []);

  return (
    <div>
      <div className="wp-balance">
        <span className="wp-icon">
          <Wallet size={20} />
        </span>
        <span>
          <em>Available balance</em>
          <b>{balance === null ? "—" : money(balance)}</b>
        </span>
        <Link href="/wallet" className="wp-full">
          Full wallet <ExternalLink size={12} />
        </Link>
      </div>

      <div className="flex flex-col gap-1.5 mt-3">
        {txs.map((t) => {
          const incoming = t.amount > 0;
          return (
            <div key={t.id} className="wp-row">
              <span className={clsx("wp-dir", incoming ? "in" : "out")}>
                {incoming ? <ArrowDownLeft size={14} /> : <ArrowUpRight size={14} />}
              </span>
              <span className="min-w-0 flex-1">
                <b>{t.note || t.kind}</b>
                <em>{timeAgo(t.createdAt)}</em>
              </span>
              <span className={clsx("wp-amt", incoming ? "in" : "out")}>
                {incoming ? "+" : ""}
                {money(Math.abs(t.amount))}
              </span>
            </div>
          );
        })}
        {txs.length === 0 && (
          <p className="text-[12.5px] text-neutral-400 text-center py-8">
            No transactions yet.
          </p>
        )}
      </div>
    </div>
  );
}
