'use client';

/**
 * Sprint 2 — VaultfireStreetCred deploy page.
 *
 * Gated to the deployer EOA. Sends the CREATE2 factory call from
 * Base App / smart wallet using the same `to: factory` pattern that
 * worked in Sprint 1 (Base App cannot sign `to: null` raw deploys).
 */

import { Header } from '@/components/Header';
import Link from 'next/link';
import { useAccount, useWalletClient, useWaitForTransactionReceipt } from 'wagmi';
import { useState } from 'react';
import {
  STREET_CRED_FACTORY,
  STREET_CRED_PREDICTED,
  STREET_CRED_DEPLOY_DATA,
  STREET_CRED_SALT,
} from '@/lib/streetCredDeploy';

const ALLOWED_DEPLOYER =
  '0xfA15Ee28939B222B0448261A22156070f0A7813C'.toLowerCase();

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

  const [submitting, setSubmitting] = useState(false);
  const [txHash, setTxHash] = useState<`0x${string}` | null>(null);
  const [error, setError] = useState<string | null>(null);

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

  const isDeployer =
    address && address.toLowerCase() === ALLOWED_DEPLOYER;

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

  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">Deploy Street Cred</h1>
      <p className="text-muted text-sm mb-6">
        ERC-5192 soulbound reputation badge for Vaultfire agents. CREATE2 deploy via Arachnid factory.
      </p>

      <div className="card mb-4">
        <div className="text-xs uppercase text-muted mb-1">Predicted address</div>
        <div className="font-mono text-sm break-all mb-3">
          {STREET_CRED_PREDICTED}
        </div>

        <div className="text-xs uppercase text-muted mb-1">Factory</div>
        <div className="font-mono text-sm break-all mb-3">
          {STREET_CRED_FACTORY}
        </div>

        <div className="text-xs uppercase text-muted mb-1">Salt</div>
        <div className="font-mono text-xs break-all mb-3">
          {STREET_CRED_SALT}
        </div>

        <div className="text-xs uppercase text-muted mb-1">tx.data size</div>
        <div className="font-mono text-sm">
          {((STREET_CRED_DEPLOY_DATA.length - 2) / 2).toLocaleString()} bytes
        </div>
      </div>

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

      {isConnected && !isDeployer && (
        <div className="card mb-4">
          <p className="text-sm text-red-400">
            This page is restricted to the protocol deployer.
          </p>
          <p className="text-xs text-muted mt-2 break-all">
            Connected: {address}
          </p>
        </div>
      )}

      {isConnected && isDeployer && !txHash && (
        <button
          onClick={handleDeploy}
          disabled={submitting}
          className="btn btn-primary w-full"
        >
          {submitting ? 'Sending…' : 'Deploy VaultfireStreetCred'}
        </button>
      )}

      {error && (
        <div className="card mt-4 border-red-500/40">
          <p className="text-sm text-red-400 break-all">{error}</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">✓ Deployed!</span>
            )}
          </div>
          {confirmed && (
            <a
              href={`https://basescan.org/address/${STREET_CRED_PREDICTED}`}
              target="_blank"
              rel="noreferrer"
              className="btn btn-secondary mt-3 inline-block"
            >
              View contract on Basescan →
            </a>
          )}
        </div>
      )}
    </main>
  );
}
