'use client';

/**
 * Bond Insurance Pool — public contribute page + live ERC-4626 vault stats.
 *
 * Underlying: VaultfireBondInsurancePool (write target)
 * Adapter:    VaultfireBIPVault (read-only ERC-4626 view layer)
 *
 * Users call pool.contribute() {value} directly. The vault adapter exists
 * so wallets/indexers can read pool exposure as a standard ERC-4626 vault.
 */

import { Header } from '@/components/Header';
import Link from 'next/link';
import {
  useAccount,
  useReadContract,
  useWriteContract,
  useWaitForTransactionReceipt,
} from 'wagmi';
import { formatEther, parseEther } from 'viem';
import { useState } from 'react';
import {
  BIP_POOL_ADDRESS,
  BIP_POOL_ABI,
  BIP_VAULT_ADDRESS,
  BIP_VAULT_ABI,
} from '@/lib/vaultfire';

const MIN_ETH = 0.001;

export default function InsurancePage() {
  const { address, isConnected } = useAccount();
  const [amountEth, setAmountEth] = useState('0.001');

  // Live reads from the vault adapter (proves end-to-end ERC-4626 surface)
  const { data: totalAssets, refetch: refetchTotal } = useReadContract({
    address: BIP_VAULT_ADDRESS,
    abi: BIP_VAULT_ABI,
    functionName: 'totalAssets',
  });
  const { data: totalSupply } = useReadContract({
    address: BIP_VAULT_ADDRESS,
    abi: BIP_VAULT_ABI,
    functionName: 'totalSupply',
  });
  const { data: myShares, refetch: refetchMine } = useReadContract({
    address: BIP_VAULT_ADDRESS,
    abi: BIP_VAULT_ABI,
    functionName: 'balanceOf',
    args: address ? [address] : undefined,
    query: { enabled: !!address },
  });
  const { data: vaultName } = useReadContract({
    address: BIP_VAULT_ADDRESS,
    abi: BIP_VAULT_ABI,
    functionName: 'name',
  });
  const { data: vaultSymbol } = useReadContract({
    address: BIP_VAULT_ADDRESS,
    abi: BIP_VAULT_ABI,
    functionName: 'symbol',
  });

  const { data: txHash, writeContract, isPending, error } = useWriteContract();
  const { isLoading: confirming, isSuccess: confirmed } =
    useWaitForTransactionReceipt({
      hash: txHash,
      query: {
        // Refresh on-chain reads after confirmation
        select: (r) => {
          refetchTotal();
          refetchMine();
          return r;
        },
      },
    });

  const amountNum = Number(amountEth);
  const validAmount = !Number.isNaN(amountNum) && amountNum >= MIN_ETH;

  function submit() {
    if (!validAmount) return;
    try {
      writeContract({
        address: BIP_POOL_ADDRESS,
        abi: BIP_POOL_ABI,
        functionName: 'contribute',
        value: parseEther(amountEth),
      });
    } catch (e) {
      console.error(e);
    }
  }

  return (
    <main>
      <Header />

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

      <h1 className="text-2xl font-bold mb-2">Bond Insurance Pool</h1>
      <p className="text-muted text-sm mb-6">
        Shared insurance pool for accountability bonds. Contributions are
        non-redeemable — they back the protocol and earn reputation. Exposed
        as a soulbound ERC-4626 vault ({vaultSymbol ?? 'vBIP'}) so wallets and
        indexers can read positions natively.
      </p>

      <div className="card mb-4">
        <div className="text-xs uppercase text-muted mb-1">Vault</div>
        <div className="font-mono text-xs break-all mb-3">
          {vaultName ?? '…'} ({vaultSymbol ?? '…'})
        </div>

        <div className="text-xs uppercase text-muted mb-1">Total pool assets</div>
        <div className="font-mono text-sm mb-3">
          {totalAssets != null ? `${formatEther(totalAssets as bigint)} ETH` : '…'}
        </div>

        <div className="text-xs uppercase text-muted mb-1">Total shares (vBIP)</div>
        <div className="font-mono text-sm mb-3">
          {totalSupply != null ? `${formatEther(totalSupply as bigint)} vBIP` : '…'}
        </div>

        {isConnected && (
          <>
            <div className="text-xs uppercase text-muted mb-1">Your contribution</div>
            <div className="font-mono text-sm">
              {myShares != null
                ? `${formatEther(myShares as bigint)} vBIP`
                : '…'}
            </div>
          </>
        )}
      </div>

      {!isConnected && (
        <div className="card mb-4">
          <p className="text-sm text-muted">
            Connect your wallet to contribute. Use the Connect button above.
          </p>
        </div>
      )}

      {isConnected && (
        <div className="card mb-4">
          <label className="block text-xs uppercase text-muted mb-2">
            Contribute (ETH, min 0.001)
          </label>
          <input
            type="text"
            inputMode="decimal"
            value={amountEth}
            onChange={(e) => setAmountEth(e.target.value)}
            className="w-full bg-transparent border border-white/10 rounded px-3 py-2 font-mono text-sm mb-3"
            placeholder="0.001"
          />
          <button
            onClick={submit}
            disabled={!validAmount || isPending || confirming}
            className="btn btn-primary w-full"
          >
            {isPending
              ? 'Sending…'
              : confirming
                ? 'Confirming…'
                : 'Contribute'}
          </button>
        </div>
      )}

      {error && (
        <div className="card mt-4 border-red-500/40">
          <p className="text-sm text-red-400 break-all">{error.message}</p>
        </div>
      )}

      {txHash && (
        <div className="card mt-4">
          <div className="text-xs uppercase text-muted mb-1">Tx hash</div>
          <a
            href={`https://basescan.org/tx/${txHash}`}
            target="_blank"
            rel="noreferrer"
            className="font-mono text-xs break-all underline"
          >
            {txHash}
          </a>
          <div className="mt-3 text-sm">
            {confirming && '⏳ Confirming…'}
            {confirmed && (
              <span className="text-green-400">✓ Contributed!</span>
            )}
          </div>
          {confirmed && (
            <a
              href={`https://basescan.org/address/${BIP_VAULT_ADDRESS}`}
              target="_blank"
              rel="noreferrer"
              className="btn btn-secondary mt-3 inline-block"
            >
              View vault on Basescan →
            </a>
          )}
        </div>
      )}

      <div className="card mt-4">
        <div className="text-xs uppercase text-muted mb-1">Pool contract</div>
        <a
          href={`https://basescan.org/address/${BIP_POOL_ADDRESS}`}
          target="_blank"
          rel="noreferrer"
          className="font-mono text-xs break-all underline"
        >
          {BIP_POOL_ADDRESS}
        </a>

        <div className="text-xs uppercase text-muted mt-3 mb-1">
          ERC-4626 adapter
        </div>
        <a
          href={`https://basescan.org/address/${BIP_VAULT_ADDRESS}`}
          target="_blank"
          rel="noreferrer"
          className="font-mono text-xs break-all underline"
        >
          {BIP_VAULT_ADDRESS}
        </a>
      </div>
    </main>
  );
}
