'use client';

import { Header } from '@/components/Header';
import Link from 'next/link';
import { useEffect, useState, useMemo } from 'react';
import { useAccount, useWalletClient, useWaitForTransactionReceipt } from 'wagmi';
import {
  readStreetCred,
  readTokenURI,
  encodeMintFor,
  tokenIdOf,
  tierColor,
  STREET_CRED_ADDRESS,
  type StreetCredState,
} from '@/lib/streetCred';
import { formatEther, type Address } from 'viem';

export default function StreetCredPage() {
  const { address, isConnected } = useAccount();
  const { data: walletClient } = useWalletClient();

  const [state, setState] = useState<StreetCredState | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [txHash, setTxHash] = useState<`0x${string}` | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [imgUrl, setImgUrl] = useState<string | null>(null);

  const { isLoading: confirming, isSuccess: confirmed } =
    useWaitForTransactionReceipt({ hash: txHash ?? undefined });

  // Read live Street Cred state
  async function refresh(addr: Address) {
    setLoading(true);
    setError(null);
    try {
      const s = await readStreetCred(addr);
      setState(s);
      if (s.hasBadge) {
        const uri = await readTokenURI(tokenIdOf(addr));
        // tokenURI is data:application/json;base64,<...>
        try {
          const json = JSON.parse(atob(uri.split(',')[1] ?? ''));
          setImgUrl(json.image ?? null);
        } catch { /* ignore parse errors */ }
      } else {
        setImgUrl(null);
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Read failed');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    if (address) refresh(address);
  }, [address]);

  // After confirmation, refresh state
  useEffect(() => {
    if (confirmed && address) refresh(address);
  }, [confirmed, address]);

  async function handleMint() {
    if (!walletClient || !address) return;
    setSubmitting(true);
    setError(null);
    try {
      const hash = await walletClient.sendTransaction({
        to: STREET_CRED_ADDRESS,
        data: encodeMintFor(address as Address),
        value: 0n,
      });
      setTxHash(hash);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Mint failed');
    } finally {
      setSubmitting(false);
    }
  }

  const eligible = useMemo(() => state ? state.tier > 0 : false, [state]);

  return (
    <main>
      <Header />

      <div className="mb-6">
        <Link href="/" className="text-sm text-muted hover:text-white transition-colors">
          ← Back
        </Link>
      </div>

      <h1 className="text-2xl font-bold mb-2">Street Cred</h1>
      <p className="text-muted text-sm mb-6">
        Soulbound (ERC-5192) reputation badge. Tier is computed live on-chain
        from your registered identity and bonds.
      </p>

      {!isConnected && (
        <div className="card">
          <p className="text-sm text-muted">
            Connect your wallet to view or mint your badge.
          </p>
        </div>
      )}

      {isConnected && loading && (
        <div className="card">
          <p className="text-sm text-muted">Reading on-chain score…</p>
        </div>
      )}

      {isConnected && state && (
        <>
          {/* Score card */}
          <div className="card mb-4">
            <div className="flex items-center gap-4">
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center font-mono font-bold text-bg"
                style={{ backgroundColor: tierColor(state.tier) }}
              >
                {state.tierName === 'None' ? '–' : state.tierName[0]}
              </div>
              <div>
                <div className="label mb-1">Tier</div>
                <div className="text-xl font-semibold text-white">
                  {state.tierName}
                </div>
                <div className="text-xs text-muted mt-1">
                  Score {state.score} / 95
                </div>
              </div>
            </div>
          </div>

          {/* Breakdown */}
          <div className="card mb-4">
            <div className="label mb-3">Score breakdown</div>
            <Row k="Identity registered" v={state.registered ? '+30' : '0'} />
            <Row k="Has bond"            v={state.hasBond ? '+25' : '0'} />
            <Row k="Bond active"         v={state.bondActive ? '+15' : '0'} />
            <Row k="Bond stake"          v={state.stakeWei > 0n ? `${formatEther(state.stakeWei)} ETH` : '0'} />
            <Row k="Bond count"          v={state.bondCount > 1 ? `${state.bondCount} (+5)` : `${state.bondCount}`} />
          </div>

          {/* Badge preview / mint */}
          {state.hasBadge && imgUrl && (
            <div className="card mb-4">
              <div className="label mb-3">Your badge</div>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={imgUrl}
                alt="Vaultfire Street Cred badge"
                className="w-full max-w-xs mx-auto rounded-lg border border-border"
              />
              <p className="text-xs text-muted text-center mt-3">
                Soulbound. Non-transferable. Tier auto-updates.
              </p>
            </div>
          )}

          {!state.hasBadge && !txHash && (
            <button
              onClick={handleMint}
              disabled={!eligible || submitting}
              className="btn-primary w-full block text-center"
            >
              {submitting
                ? 'Sending…'
                : eligible
                  ? `Mint ${state.tierName} badge`
                  : 'Register first to qualify'}
            </button>
          )}

          {!eligible && !state.hasBadge && (
            <Link href="/onboard" className="btn-secondary w-full block text-center mt-3">
              Onboard now →
            </Link>
          )}

          {txHash && (
            <div className="card mt-4">
              <div className="label mb-1">Tx</div>
              <a
                href={`https://basescan.org/tx/${txHash}`}
                target="_blank"
                rel="noreferrer"
                className="text-xs font-mono break-all underline text-white"
              >
                {txHash}
              </a>
              <div className="mt-2 text-sm">
                {confirming && '⏳ Confirming…'}
                {confirmed && <span className="text-success">✓ Minted</span>}
              </div>
            </div>
          )}

          {error && (
            <div className="card mt-4 border-danger">
              <p className="text-sm text-danger break-all">{error}</p>
            </div>
          )}

          {/* Contract info */}
          <div className="text-center mt-6">
            <a
              href={`https://basescan.org/address/${STREET_CRED_ADDRESS}`}
              target="_blank"
              rel="noreferrer"
              className="text-xs text-muted underline"
            >
              Contract on Basescan →
            </a>
          </div>
        </>
      )}
    </main>
  );
}

function Row({ k, v }: { k: string; v: string }) {
  return (
    <div className="flex items-center justify-between py-2 border-b border-border last:border-0">
      <span className="text-sm text-muted">{k}</span>
      <span className="text-sm font-mono text-white">{v}</span>
    </div>
  );
}
