import type { GetStaticProps } from 'next'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react'
import { Card } from '@/libs/frontend-ui-primitives'
import PageIntro from '@/components/common/PageIntro'
import EntityBadge from '@/components/common/EntityBadge'
import { tokensApi } from '@/services/api/tokens'
import type { TokenListToken } from '@/services/api/config'
import { fetchPublicJson } from '@/utils/publicExplorer'

const quickSearches = [
  { label: 'cUSDT', description: 'Canonical bridged USDT liquidity and address results.' },
  { label: 'cUSDC', description: 'Canonical bridged USDC routes and address coverage.' },
  { label: 'cXAUC', description: 'Gold-backed cXAUC pools and token references.' },
  { label: 'cXAUT', description: 'Gold-backed cXAUT references and search coverage.' },
  { label: 'cEURT', description: 'EUR liquidity and cXAUC-connected route coverage.' },
  { label: 'USDT', description: 'Native-side USDT routes and address discovery.' },
]

function normalizeAddress(value: string) {
  const trimmed = value.trim()
  return /^0x[a-fA-F0-9]{40}$/.test(trimmed) ? trimmed : ''
}

interface TokensPageProps {
  initialCuratedTokens: TokenListToken[]
}

export default function TokensPage({ initialCuratedTokens }: TokensPageProps) {
  const router = useRouter()
  const [query, setQuery] = useState('')
  const [curatedTokens, setCuratedTokens] = useState<TokenListToken[]>(initialCuratedTokens)

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault()
    const normalized = normalizeAddress(query)
    router.push(normalized ? `/tokens/${normalized}` : `/search?q=${encodeURIComponent(query.trim())}`)
  }

  useEffect(() => {
    if (initialCuratedTokens.length > 0) {
      setCuratedTokens(initialCuratedTokens)
      return
    }

    let active = true
    tokensApi.listCuratedSafe(138).then(({ ok, data }) => {
      if (active) {
        setCuratedTokens(ok ? data : [])
      }
    }).catch(() => {
      if (active) {
        setCuratedTokens([])
      }
    })
    return () => {
      active = false
    }
  }, [initialCuratedTokens])

  const featuredCuratedTokens = useMemo(() => {
    const preferred = ['cUSDT', 'cUSDC', 'cXAUC', 'cXAUT', 'cEURT', 'USDT']
    const selected = preferred
      .map((symbol) => curatedTokens.find((token) => token.symbol === symbol))
      .filter((token): token is TokenListToken => Boolean(token?.address))

    return selected.length > 0 ? selected : curatedTokens.slice(0, 6)
  }, [curatedTokens])

  return (
    <div className="container mx-auto px-4 py-8">
      <PageIntro
        eyebrow="Token Discovery"
        title="Tokens"
        description="Browse curated Chain 138 assets, open token contracts directly, and move into holders, transfers, liquidity, and provenance without pretending a search box is a complete token strategy."
        actions={[
          { href: '/wallet', label: 'Wallet tools' },
          { href: '/liquidity', label: 'Liquidity access' },
          { href: '/search', label: 'Explorer search' },
        ]}
      />

      <Card className="mb-6" title="Find A Token">
        <form onSubmit={handleSubmit} className="flex flex-col gap-3 md:flex-row">
          <input
            type="text"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder="Token symbol, name, or contract address"
            className="flex-1 rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500"
          />
          <button
            type="submit"
            disabled={!query.trim()}
            className="rounded-lg bg-primary-600 px-6 py-2 text-white hover:bg-primary-700 disabled:cursor-not-allowed disabled:opacity-50"
          >
            Search
          </button>
        </form>
        <p className="mt-3 text-sm text-gray-600 dark:text-gray-400">
          Contract addresses open dedicated token detail pages with holders, transfers, provenance, and liquidity context.
        </p>
      </Card>

      <div className="grid gap-6 lg:grid-cols-3">
        <Card title="Curated Registry">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            Review listed Chain 138 assets with provenance tags such as compliant, wrapped, and bridge-aware before acting on a symbol match.
          </p>
          <div className="mt-4">
            <Link href="/tokens" className="text-primary-600 hover:underline">
              Browse curated tokens →
            </Link>
          </div>
        </Card>
        <Card title="Wallet Discovery">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            Add Chain 138 and supported token metadata to MetaMask directly from the explorer wallet tools.
          </p>
          <div className="mt-4">
            <Link href="/wallet" className="text-primary-600 hover:underline">
              Open wallet tools →
            </Link>
          </div>
        </Card>
        <Card title="Liquidity Routes">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            Review canonical PMM routes, partner payload templates, and token-routing examples for supported pools.
          </p>
          <div className="mt-4">
            <Link href="/liquidity" className="text-primary-600 hover:underline">
              Open liquidity access →
            </Link>
          </div>
        </Card>
      </div>

      <div className="mt-8">
        <Card title="Curated Chain 138 tokens">
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {featuredCuratedTokens.map((token) => (
              <Link
                key={token.address}
                href={`/tokens/${token.address}`}
                className="rounded-lg border border-gray-200 p-4 transition hover:border-primary-400 hover:shadow-sm dark:border-gray-700"
              >
                <div className="text-sm font-semibold text-gray-900 dark:text-white">{token.symbol || token.name || 'Token'}</div>
                <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                  {token.name || 'Listed in the Chain 138 token registry.'}
                </p>
                {token.tags && token.tags.length > 0 && (
                  <div className="mt-3 flex flex-wrap gap-2">
                    {token.tags.slice(0, 3).map((tag) => (
                      <EntityBadge key={`${token.address}-${tag}`} label={tag} className="px-2 py-1 text-[11px]" />
                    ))}
                  </div>
                )}
              </Link>
            ))}
          </div>
        </Card>
      </div>

      <div className="mt-8">
        <Card title="Common token searches">
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {quickSearches.map((token) => (
              <Link
                key={token.label}
                href={`/search?q=${encodeURIComponent(token.label)}`}
                className="rounded-lg border border-gray-200 p-4 transition hover:border-primary-400 hover:shadow-sm dark:border-gray-700"
              >
                <div className="text-sm font-semibold text-gray-900 dark:text-white">{token.label}</div>
                <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">{token.description}</p>
              </Link>
            ))}
          </div>
        </Card>
      </div>
    </div>
  )
}

export const getStaticProps: GetStaticProps<TokensPageProps> = async () => {
  const tokenListResult = await fetchPublicJson<{ tokens?: TokenListToken[] }>('/api/config/token-list').catch(() => null)

  return {
    props: {
      initialCuratedTokens: Array.isArray(tokenListResult?.tokens)
        ? tokenListResult.tokens
            .filter((token) => token.chainId === 138 && typeof token.address === 'string' && token.address.trim().length > 0)
            .sort((left, right) => (left.symbol || left.name || '').localeCompare(right.symbol || right.name || ''))
        : [],
    },
    revalidate: 300,
  }
}
