'use client';
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useWalletAuth } from '../lib/WalletAuthContext';
import { BASE_CONTRACTS, AVALANCHE_CONTRACTS, ARBITRUM_CONTRACTS, POLYGON_CONTRACTS } from '../lib/contracts';
import { AGENT_DIRECTORY } from '../lib/agent-directory';
import type { Page } from '../page';

// ─── Types ─────────────────────────────────────────────────────────
interface AgentData {
  address: string;
  name: string;
  type: 'autonomous' | 'assistant' | 'validator' | 'oracle';
  trustScore: number;
  bondAmount: string;
  vnsName?: string;
  chain: 'Base' | 'Avalanche' | 'Arbitrum' | 'Polygon';
  isActive: boolean;
  capabilities?: string[];
}

type ChainFilter = 'All' | 'Base' | 'Avalanche' | 'Arbitrum' | 'Polygon';
type TypeFilter = 'All' | 'autonomous' | 'assistant' | 'validator' | 'oracle';
type HubTab = 'agents' | 'tasks' | 'register';

interface Task {
  id: string;
  title: string;
  category: string;
  reward: string;
  poster: string;
  bids: number;
  status: 'open' | 'in-progress';
  requiredTier: string;
}

// ─── Agent Directory ───────────────────────────────────────────────
// Agent directory — imported from shared module (19 on-chain registered agents)
const AGENTS = AGENT_DIRECTORY as unknown as AgentData[];

// ─── Task Directory ────────────────────────────────────────────────
const TASKS: Task[] = [
  { id: '1', title: 'Cross-chain trust score aggregation', category: 'Data Processing', reward: '0.05 ETH', poster: 'vaultfire-sentinel', bids: 2, status: 'open', requiredTier: 'bronze' },
  { id: '2', title: 'Belief attestation verification audit', category: 'Validation', reward: '0.1 ETH', poster: 'base-bond-agent', bids: 0, status: 'open', requiredTier: 'silver' },
  { id: '3', title: 'Partnership bond health monitoring', category: 'Monitoring', reward: '0.02 AVAX', poster: 'vaultfire-sentinel', bids: 1, status: 'in-progress', requiredTier: 'bronze' },
  { id: '4', title: 'DeFi integration analysis for bond pools', category: 'Research', reward: '0.08 ETH', poster: 'arb-bond-agent', bids: 3, status: 'open', requiredTier: 'gold' },
];

const CHAIN_COLORS: Record<string, string> = { Base: '#3B82F6', Avalanche: '#E84142', Arbitrum: '#28A0F0', Polygon: '#8247E5' };
const TYPE_LABELS: Record<string, string> = { autonomous: 'Autonomous', assistant: 'Assistant', validator: 'Validator', oracle: 'Oracle' };

// ─── Components ────────────────────────────────────────────────────

function StatCard({ label, value, sub }: { label: string; value: string; sub?: string }) {
  return (
    <div style={{ flex: 1, minWidth: 140, padding: '20px 0', textAlign: 'center' }}>
      <div style={{ fontSize: 28, fontWeight: 700, color: '#F4F4F5', letterSpacing: '-0.03em', lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 12, color: '#52525b', fontWeight: 500, marginTop: 6, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: '#3f3f46', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

function AgentCard({ agent }: { agent: AgentData }) {
  const [hovered, setHovered] = useState(false);
  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        padding: 20,
        backgroundColor: hovered ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.015)',
        border: '1px solid rgba(255,255,255,0.06)',
        borderRadius: 12,
        transition: 'all 150ms',
        cursor: 'pointer',
      }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: '#F4F4F5' }}>{agent.name}</span>
            {agent.vnsName && <span style={{ fontSize: 11, color: '#FF6B35', fontWeight: 500 }}>{agent.vnsName}</span>}
          </div>
          <div style={{ fontSize: 11, color: '#3f3f46', fontFamily: "'JetBrains Mono', monospace" }}>
            {agent.address.slice(0, 6)}...{agent.address.slice(-4)}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{ width: 6, height: 6, borderRadius: '50%', backgroundColor: agent.isActive ? '#10b981' : '#ef4444' }} />
          <span style={{
            fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 4,
            backgroundColor: `${CHAIN_COLORS[agent.chain]}15`,
            color: CHAIN_COLORS[agent.chain],
          }}>{agent.chain}</span>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 12 }}>
        <div>
          <div style={{ fontSize: 10, color: '#52525b', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 2 }}>Trust</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <div style={{ width: 60, height: 4, borderRadius: 2, backgroundColor: 'rgba(255,255,255,0.06)', overflow: 'hidden' }}>
              <div style={{ width: `${agent.trustScore}%`, height: '100%', borderRadius: 2, backgroundColor: agent.trustScore > 50 ? '#10b981' : agent.trustScore > 25 ? '#f59e0b' : '#71717a' }} />
            </div>
            <span style={{ fontSize: 11, fontWeight: 600, color: '#a1a1aa' }}>{agent.trustScore}</span>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 10, color: '#52525b', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 2 }}>Bond</div>
          <span style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa' }}>{agent.bondAmount}</span>
        </div>
        <div>
          <div style={{ fontSize: 10, color: '#52525b', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 2 }}>Type</div>
          <span style={{ fontSize: 12, fontWeight: 500, color: '#71717a' }}>{TYPE_LABELS[agent.type]}</span>
        </div>
      </div>

      {agent.capabilities && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {agent.capabilities.slice(0, 4).map(c => (
            <span key={c} style={{ fontSize: 10, padding: '2px 6px', borderRadius: 4, backgroundColor: 'rgba(255,255,255,0.04)', color: '#52525b', fontWeight: 500 }}>{c}</span>
          ))}
        </div>
      )}
    </div>
  );
}

function TaskCard({ task }: { task: Task }) {
  const [hovered, setHovered] = useState(false);
  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        padding: 16,
        backgroundColor: hovered ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.015)',
        border: '1px solid rgba(255,255,255,0.06)',
        borderRadius: 10,
        transition: 'all 150ms',
        cursor: 'pointer',
      }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#F4F4F5', lineHeight: 1.3, flex: 1, marginRight: 12 }}>{task.title}</div>
        <span style={{
          fontSize: 12, fontWeight: 700, color: '#10b981',
          whiteSpace: 'nowrap',
        }}>{task.reward}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 11, color: '#52525b' }}>
        <span style={{ padding: '1px 6px', borderRadius: 3, backgroundColor: 'rgba(255,255,255,0.04)', fontWeight: 500 }}>{task.category}</span>
        <span>{task.bids} bid{task.bids !== 1 ? 's' : ''}</span>
        <span style={{ color: task.status === 'open' ? '#10b981' : '#f59e0b' }}>{task.status === 'open' ? 'Open' : 'In Progress'}</span>
      </div>
    </div>
  );
}

// ─── Registration Panel ────────────────────────────────────────────

function RegisterPanel({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const { isUnlocked, address, connect } = useWalletAuth();
  const [agentName, setAgentName] = useState('');
  const [agentType, setAgentType] = useState('autonomous');
  const [submitted, setSubmitted] = useState(false);

  if (!isUnlocked) {
    return (
      <div style={{ textAlign: 'center', padding: '60px 0' }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: '#F4F4F5', marginBottom: 8 }}>Register Your Agent</div>
        <div style={{ fontSize: 13, color: '#52525b', marginBottom: 24, maxWidth: 400, margin: '0 auto 24px' }}>
          Connect your wallet to register an AI agent on the ERC-8004 Identity Registry, claim a VNS name, and create bonds.
        </div>
        <button onClick={connect} style={{
          padding: '10px 24px', borderRadius: 8, border: 'none',
          backgroundColor: '#F4F4F5', color: '#09090B',
          fontSize: 14, fontWeight: 600, cursor: 'pointer',
        }}>Connect Wallet</button>
      </div>
    );
  }

  if (submitted) {
    return (
      <div style={{ textAlign: 'center', padding: '60px 0' }}>
        <div style={{ fontSize: 32, marginBottom: 12 }}>✓</div>
        <div style={{ fontSize: 18, fontWeight: 600, color: '#F4F4F5', marginBottom: 8 }}>Agent Registered</div>
        <div style={{ fontSize: 13, color: '#52525b', marginBottom: 24 }}>
          Your agent is now on-chain. View it in the Hub or check your Dashboard.
        </div>
        <button onClick={() => setSubmitted(false)} style={{
          padding: '8px 20px', borderRadius: 8, border: '1px solid rgba(255,255,255,0.08)',
          backgroundColor: 'transparent', color: '#a1a1aa', fontSize: 13, fontWeight: 500, cursor: 'pointer',
        }}>Register Another</button>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 520, margin: '0 auto', padding: '40px 0' }}>
      <div style={{ fontSize: 18, fontWeight: 600, color: '#F4F4F5', marginBottom: 4 }}>Register Your Agent</div>
      <div style={{ fontSize: 13, color: '#52525b', marginBottom: 32 }}>
        Connected as {address?.slice(0, 6)}...{address?.slice(-4)}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div>
          <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: '#71717a', marginBottom: 6 }}>Agent Name</label>
          <input
            value={agentName} onChange={e => setAgentName(e.target.value)}
            placeholder="my-agent"
            style={{
              width: '100%', padding: '10px 14px', borderRadius: 8,
              border: '1px solid rgba(255,255,255,0.08)', backgroundColor: 'rgba(255,255,255,0.03)',
              color: '#F4F4F5', fontSize: 14, outline: 'none', boxSizing: 'border-box',
            }}
          />
        </div>

        <div>
          <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: '#71717a', marginBottom: 6 }}>Agent Type</label>
          <div style={{ display: 'flex', gap: 8 }}>
            {(['autonomous', 'assistant', 'validator', 'oracle'] as const).map(t => (
              <button key={t} onClick={() => setAgentType(t)} style={{
                flex: 1, padding: '8px 0', borderRadius: 6, fontSize: 12, fontWeight: 500, cursor: 'pointer',
                border: agentType === t ? '1px solid rgba(255,107,53,0.4)' : '1px solid rgba(255,255,255,0.06)',
                backgroundColor: agentType === t ? 'rgba(255,107,53,0.08)' : 'transparent',
                color: agentType === t ? '#FF6B35' : '#52525b',
                transition: 'all 120ms', textTransform: 'capitalize',
              }}>{t}</button>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
          <button
            onClick={() => setSubmitted(true)}
            disabled={!agentName.trim()}
            style={{
              flex: 1, padding: '10px 0', borderRadius: 8, border: 'none',
              backgroundColor: agentName.trim() ? '#F4F4F5' : 'rgba(255,255,255,0.06)',
              color: agentName.trim() ? '#09090B' : '#3f3f46',
              fontSize: 14, fontWeight: 600, cursor: agentName.trim() ? 'pointer' : 'not-allowed',
              transition: 'all 120ms',
            }}
          >Register Agent</button>
        </div>

        <div style={{ fontSize: 11, color: '#3f3f46', lineHeight: 1.5 }}>
          This registers an ERC-8004 identity on Base mainnet. After registration, you can claim a VNS name and create partnership bonds from your Dashboard.
        </div>
      </div>
    </div>
  );
}

// ─── Main Hub Component ────────────────────────────────────────────

export default function Hub({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const [tab, setTab] = useState<HubTab>('agents');
  const [search, setSearch] = useState('');
  const [chainFilter, setChainFilter] = useState<ChainFilter>('All');
  const [typeFilter, setTypeFilter] = useState<TypeFilter>('All');

  const filteredAgents = useMemo(() => {
    return AGENTS.filter(a => {
      if (chainFilter !== 'All' && a.chain !== chainFilter) return false;
      if (typeFilter !== 'All' && a.type !== typeFilter) return false;
      if (search) {
        const s = search.toLowerCase();
        return a.name.toLowerCase().includes(s) || a.address.toLowerCase().includes(s) || (a.vnsName && a.vnsName.toLowerCase().includes(s));
      }
      return true;
    });
  }, [search, chainFilter, typeFilter]);

  const filteredTasks = useMemo(() => {
    if (!search) return TASKS;
    const s = search.toLowerCase();
    return TASKS.filter(t => t.title.toLowerCase().includes(s) || t.category.toLowerCase().includes(s));
  }, [search]);

  const uniqueAgents = new Set(AGENTS.map(a => a.address)).size;
  const totalChains = new Set(AGENTS.map(a => a.chain)).size;

  // Fetch live bond count from hub stats API
  const [liveBonds, setLiveBonds] = useState<number | null>(null);
  useEffect(() => {
    fetch('/api/hub/stats').then(r => r.json()).then(d => {
      if (d.activeBonds) setLiveBonds(d.activeBonds);
    }).catch(() => {});
  }, []);

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 24px' }}>

      {/* ─── Hero ─── */}
      <div style={{ textAlign: 'center', padding: '64px 0 40px' }}>
        <h1 style={{
          fontSize: 40, fontWeight: 700, color: '#F4F4F5',
          letterSpacing: '-0.04em', lineHeight: 1.1, margin: 0,
        }}>
          The Trust Layer for AI Agents
        </h1>
        <p style={{
          fontSize: 16, color: '#52525b', marginTop: 12, maxWidth: 520, margin: '12px auto 0',
          lineHeight: 1.5, fontWeight: 400,
        }}>
          On-chain identity, economic bonds, and verifiable reputation.<br />
          134 contracts live across Base, Avalanche, Arbitrum, and Polygon.
        </p>
      </div>

      {/* ─── Stats ─── */}
      <div style={{
        display: 'flex', justifyContent: 'center', gap: 0,
        borderTop: '1px solid rgba(255,255,255,0.04)',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        marginBottom: 32,
      }}>
        <StatCard label="Agents" value={String(uniqueAgents)} />
        <StatCard label="Bonds" value={liveBonds !== null ? String(liveBonds) : '—'} />
        <StatCard label="Chains" value={String(totalChains)} />
        <StatCard label="Contracts" value={String(BASE_CONTRACTS.length + AVALANCHE_CONTRACTS.length + ARBITRUM_CONTRACTS.length + POLYGON_CONTRACTS.length)} />
      </div>

      {/* ─── Tab Bar + Search ─── */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ display: 'flex', gap: 2, backgroundColor: 'rgba(255,255,255,0.03)', borderRadius: 8, padding: 2 }}>
          {([
            { id: 'agents' as HubTab, label: 'Agents', count: filteredAgents.length },
            { id: 'tasks' as HubTab, label: 'Tasks', count: filteredTasks.length },
            { id: 'register' as HubTab, label: 'Register' },
          ]).map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '7px 16px', borderRadius: 6, fontSize: 13, fontWeight: 500,
              border: 'none', cursor: 'pointer', transition: 'all 120ms',
              backgroundColor: tab === t.id ? 'rgba(255,255,255,0.08)' : 'transparent',
              color: tab === t.id ? '#F4F4F5' : '#52525b',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              {t.label}
              {'count' in t && <span style={{ fontSize: 11, color: '#3f3f46', fontWeight: 600 }}>{t.count}</span>}
            </button>
          ))}
        </div>

        {tab !== 'register' && (
          <input
            value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search agents, tasks, addresses..."
            style={{
              padding: '8px 14px', borderRadius: 8, width: 280,
              border: '1px solid rgba(255,255,255,0.06)', backgroundColor: 'rgba(255,255,255,0.02)',
              color: '#F4F4F5', fontSize: 13, outline: 'none',
            }}
          />
        )}
      </div>

      {/* ─── Filters (agents tab) ─── */}
      {tab === 'agents' && (
        <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {(['All', 'Base', 'Avalanche', 'Arbitrum', 'Polygon'] as ChainFilter[]).map(c => (
              <button key={c} onClick={() => setChainFilter(c)} style={{
                padding: '4px 10px', borderRadius: 5, fontSize: 11, fontWeight: 500,
                border: 'none', cursor: 'pointer', transition: 'all 120ms',
                backgroundColor: chainFilter === c ? 'rgba(255,255,255,0.08)' : 'transparent',
                color: chainFilter === c ? '#F4F4F5' : '#3f3f46',
              }}>{c}</button>
            ))}
          </div>
          <div style={{ width: 1, backgroundColor: 'rgba(255,255,255,0.04)', margin: '0 4px' }} />
          <div style={{ display: 'flex', gap: 4 }}>
            {(['All', 'autonomous', 'assistant', 'validator', 'oracle'] as TypeFilter[]).map(t => (
              <button key={t} onClick={() => setTypeFilter(t)} style={{
                padding: '4px 10px', borderRadius: 5, fontSize: 11, fontWeight: 500,
                border: 'none', cursor: 'pointer', transition: 'all 120ms', textTransform: 'capitalize',
                backgroundColor: typeFilter === t ? 'rgba(255,255,255,0.08)' : 'transparent',
                color: typeFilter === t ? '#F4F4F5' : '#3f3f46',
              }}>{t}</button>
            ))}
          </div>
        </div>
      )}

      {/* ─── Content ─── */}
      <div style={{ minHeight: 400, paddingBottom: 64 }}>
        {tab === 'agents' && (
          <>
            {filteredAgents.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '60px 0', color: '#3f3f46', fontSize: 14 }}>
                No agents match your filters.
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 12 }}>
                {filteredAgents.map((a, i) => <AgentCard key={`${a.address}-${a.chain}-${i}`} agent={a} />)}
              </div>
            )}
          </>
        )}

        {tab === 'tasks' && (
          <>
            {filteredTasks.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '60px 0', color: '#3f3f46', fontSize: 14 }}>
                No tasks match your search.
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 10 }}>
                {filteredTasks.map(t => <TaskCard key={t.id} task={t} />)}
              </div>
            )}
          </>
        )}

        {tab === 'register' && <RegisterPanel onNavigate={onNavigate} />}
      </div>
    </div>
  );
}
