'use client';

import { Header } from '@/components/Header';
import { useAccount, useWriteContract, useWaitForTransactionReceipt } from 'wagmi';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  CONTRACTS,
  IDENTITY_REGISTRY_ABI,
  nameForAddress,
  buildAgentURI,
  computeCapabilitiesHash,
} from '@/lib/vaultfire';

const DEFAULT_CAPABILITIES = [
  'trust',
  'verification',
  'identity',
];

export default function RegisterPage() {
  const { address, isConnected } = useAccount();
  const [agentType, setAgentType] = useState('human-operated');
  const [description, setDescription] = useState('');
  const [preparing, setPreparing] = useState(false);
  const [prepared, setPrepared] = useState<{
    agentURI: string;
    agentType: string;
    capsHash: `0x${string}`;
  } | null>(null);

  const { data: txHash, writeContract, isPending, error } = useWriteContract();
  const { isLoading: confirming, isSuccess: confirmed } =
    useWaitForTransactionReceipt({ hash: txHash });

  const previewName = address ? nameForAddress(address) : 'agent-xxxx.vns';

  async function prepare() {
    if (!address) return;
    setPreparing(true);
    const capsHash = await computeCapabilitiesHash(DEFAULT_CAPABILITIES);
    const agentURI = buildAgentURI({
      address,
      description: description.trim() || undefined,
      capabilities: DEFAULT_CAPABILITIES,
    });
    setPrepared({ agentURI, agentType, capsHash });
    setPreparing(false);
  }

  function submit() {
    if (!prepared) return;
    writeContract({
      address: CONTRACTS.IdentityRegistry as `0x${string}`,
      abi: IDENTITY_REGISTRY_ABI,
      functionName: 'registerAgent',
      args: [prepared.agentURI, prepared.agentType, prepared.capsHash],
    });
  }

  useEffect(() => {
    if (confirmed) {
      const t = setTimeout(() => {
        window.location.href = '/status';
      }, 1500);
      return () => clearTimeout(t);
    }
  }, [confirmed]);

  if (!isConnected) {
    return (
      <main>
        <Header />
        <div className="card">
          <p className="text-sm text-muted mb-4">
            Connect your wallet first.
          </p>
          <Link href="/" className="btn-secondary block text-center">
            Back
          </Link>
        </div>
      </main>
    );
  }

  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">Register your agent</h1>
      <p className="text-muted text-sm mb-6">
        This creates a real on-chain identity for your wallet in the Vaultfire
        registry on Base.
      </p>

      <div className="card mb-4">
        <div className="label mb-2">Your agent name</div>
        <div className="text-lg font-semibold text-white font-mono">
          {previewName}
        </div>
        <p className="text-xs text-muted mt-2">
          Auto-generated from your wallet. You can set a custom name in a
          future update.
        </p>
      </div>

      <div className="card mb-4">
        <div className="label mb-2">Agent type</div>
        <select
          value={agentType}
          onChange={(e) => setAgentType(e.target.value)}
          className="input"
          disabled={!!prepared || isPending || confirming}
        >
          <option value="human-operated">human-operated</option>
          <option value="autonomous">autonomous</option>
          <option value="hybrid">hybrid</option>
        </select>
      </div>

      <div className="card mb-4">
        <div className="label mb-2">Description (optional)</div>
        <input
          type="text"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          className="input"
          placeholder="What does this agent do?"
          maxLength={200}
          disabled={!!prepared || isPending || confirming}
        />
      </div>

      <div className="card mb-4">
        <div className="label mb-2">Default capabilities</div>
        <div className="flex flex-wrap gap-2">
          {DEFAULT_CAPABILITIES.map((c) => (
            <span
              key={c}
              className="text-xs bg-bg border border-border rounded-lg px-3 py-1 text-white"
            >
              {c}
            </span>
          ))}
        </div>
      </div>

      {!prepared && (
        <button
          onClick={prepare}
          disabled={preparing}
          className="btn-primary"
        >
          {preparing ? 'Preparing…' : 'Continue'}
        </button>
      )}

      {prepared && !txHash && !isPending && (
        <>
          <div className="card mb-4 border-accent">
            <div className="label mb-2">Ready to sign</div>
            <p className="text-sm text-white mb-1">
              You'll sign 1 transaction on Base. Gas only — no USDC required.
            </p>
          </div>
          <button onClick={submit} className="btn-primary">
            Register on-chain
          </button>
        </>
      )}

      {isPending && !txHash && (
        <div className="card">
          <p className="text-sm text-white">Waiting for wallet signature…</p>
        </div>
      )}

      {txHash && confirming && (
        <div className="card">
          <div className="label mb-1">Confirming</div>
          <p className="text-sm text-white mb-2">
            Transaction submitted. Waiting for Base confirmation…
          </p>
          <a
            href={`https://basescan.org/tx/${txHash}`}
            target="_blank"
            rel="noreferrer"
            className="text-xs font-mono text-accent hover:underline break-all"
          >
            {txHash}
          </a>
        </div>
      )}

      {confirmed && (
        <div className="card border-success">
          <div className="label text-success mb-1">Confirmed</div>
          <p className="text-sm text-white">
            Your agent is registered. Redirecting…
          </p>
        </div>
      )}

      {error && (
        <div className="card border-danger">
          <div className="label text-danger mb-1">Error</div>
          <p className="text-sm text-white break-words">{error.message}</p>
        </div>
      )}
    </main>
  );
}
