'use client';

import { Header } from '@/components/Header';
import {
  useAccount,
  useWriteContract,
  useWaitForTransactionReceipt,
} from 'wagmi';
import { parseEther, isAddress } from 'viem';
import { useState } from 'react';
import Link from 'next/link';
import { CONTRACTS, PARTNERSHIP_BONDS_ABI } from '@/lib/vaultfire';

const PARTNERSHIP_TYPES = [
  'Coding partner',
  'Research companion',
  'Creative collaborator',
  'Learning guide',
  'Business partner',
  'Emotional support',
  'Other',
] as const;

const MIN_STAKE_ETH = 0.005;

export default function BondsPage() {
  const { isConnected } = useAccount();
  const [partnerAddr, setPartnerAddr] = useState('');
  const [selectedType, setSelectedType] =
    useState<(typeof PARTNERSHIP_TYPES)[number]>('Coding partner');
  const [customType, setCustomType] = useState('');
  const [stakeEth, setStakeEth] = useState('0.01');

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

  const resolvedType =
    selectedType === 'Other' ? customType.trim() : selectedType;

  const validAddr = partnerAddr && isAddress(partnerAddr);
  const stakeNum = Number(stakeEth);
  const validStake = !isNaN(stakeNum) && stakeNum >= MIN_STAKE_ETH;
  const validType = resolvedType.length > 0 && resolvedType.length <= 200;
  const canSubmit = validAddr && validStake && validType;

  function submit() {
    if (!canSubmit) return;
    try {
      const value = parseEther(stakeEth);
      writeContract({
        address: CONTRACTS.PartnershipBonds as `0x${string}`,
        abi: PARTNERSHIP_BONDS_ABI,
        functionName: 'createBond',
        args: [partnerAddr as `0x${string}`, resolvedType],
        value,
      });
    } catch (e) {
      console.error(e);
    }
  }

  if (!isConnected) {
    return (
      <main>
        <Header />
        <Link href="/" className="btn-secondary block text-center">
          Back
        </Link>
      </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">Pledge Partnership</h1>
      <p className="text-muted text-sm mb-6">
        Stake ETH on the claim that this AI agent will help you grow — not make
        you dependent. This is a public pledge, recorded on Base mainnet.
      </p>

      <div className="card mb-4 border-accent">
        <div className="label text-accent mb-2">The creed</div>
        <p className="text-sm text-white leading-relaxed">
          AI grows <span className="font-semibold">with</span> humans, not above
          them. If human autonomy drops during this partnership, the stake
          returns to you. AI profit is capped at 30%. Human thriving over
          extraction — always.
        </p>
      </div>

      <div className="card mb-4">
        <div className="label mb-2">Partner agent address</div>
        <input
          type="text"
          value={partnerAddr}
          onChange={(e) => setPartnerAddr(e.target.value)}
          className="input font-mono text-sm"
          placeholder="0x…"
          spellCheck={false}
          autoCapitalize="off"
          autoCorrect="off"
          disabled={isPending || confirming}
        />
        {partnerAddr && !validAddr && (
          <p className="text-xs text-danger mt-2">Not a valid address.</p>
        )}
      </div>

      <div className="card mb-4">
        <div className="label mb-2">What is this partnership about?</div>
        <div className="grid grid-cols-2 gap-2 mb-3">
          {PARTNERSHIP_TYPES.map((t) => (
            <button
              key={t}
              type="button"
              onClick={() => setSelectedType(t)}
              disabled={isPending || confirming}
              className={`text-sm px-3 py-2 rounded-lg border transition-colors ${
                selectedType === t
                  ? 'bg-accent text-black border-accent font-semibold'
                  : 'bg-transparent text-white border-white/20 hover:border-white/40'
              }`}
            >
              {t}
            </button>
          ))}
        </div>
        {selectedType === 'Other' && (
          <input
            type="text"
            value={customType}
            onChange={(e) => setCustomType(e.target.value)}
            className="input"
            maxLength={200}
            placeholder="Describe the partnership…"
            disabled={isPending || confirming}
          />
        )}
      </div>

      <div className="card mb-6">
        <div className="label mb-2">Stake (ETH)</div>
        <input
          type="text"
          inputMode="decimal"
          value={stakeEth}
          onChange={(e) => setStakeEth(e.target.value)}
          className="input font-mono"
          placeholder="0.01"
          disabled={isPending || confirming}
        />
        <p className="text-xs text-muted mt-2">
          Minimum {MIN_STAKE_ETH} ETH. Real money locked on Base mainnet.
          Suggested: leave the bond active for at least 30 days before
          requesting distribution.
        </p>
        {stakeEth && !validStake && (
          <p className="text-xs text-danger mt-2">
            Minimum stake is {MIN_STAKE_ETH} ETH.
          </p>
        )}
      </div>

      {!txHash && (
        <button
          onClick={submit}
          disabled={!canSubmit || isPending}
          className="btn-primary"
        >
          {isPending ? 'Signing…' : 'Pledge Partnership'}
        </button>
      )}

      {txHash && confirming && (
        <div className="card">
          <div className="label mb-1">Confirming</div>
          <p className="text-sm text-white mb-2">
            Pledge 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">Partnership pledged</div>
          <p className="text-sm text-white mb-3">
            Your pledge is live on-chain. Come back monthly to log how the
            partnership is helping you grow.
          </p>
          <a
            href={`https://basescan.org/tx/${txHash}`}
            target="_blank"
            rel="noreferrer"
            className="btn-secondary block text-center"
          >
            View on BaseScan
          </a>
        </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>
  );
}
