'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import { Card, Address } from '@/libs/frontend-ui-primitives'
import Link from 'next/link'
import { getExplorerApiBase } from '@/services/api/blockscout'

interface SearchResult {
  type: string
  chain_id?: number
  data: {
    hash?: string
    address?: string
    number?: number
    block_number?: number
  }
  score?: number
}

export default function SearchPage() {
  const router = useRouter()
  const initialQuery = typeof router.query.q === 'string' ? router.query.q : ''
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<SearchResult[]>([])
  const [loading, setLoading] = useState(false)

  const runSearch = async (rawQuery: string) => {
    if (!rawQuery.trim()) return
    setLoading(true)
    try {
      const response = await fetch(
        `${getExplorerApiBase()}/api/v2/search?q=${encodeURIComponent(rawQuery)}`
      )
      const data = await response.json()
      if (!response.ok) {
        setResults([])
        return
      }
      const normalizedResults = Array.isArray(data?.items)
        ? data.items.map((item: {
            type?: string
            address?: string
            transaction_hash?: string
            block_number?: number
            priority?: number
          }) => ({
            type: item.type || 'unknown',
            chain_id: 138,
            data: {
              hash: item.transaction_hash,
              address: item.address,
              number: item.block_number,
            },
            score: item.priority ?? 0,
          }))
        : []
      setResults(normalizedResults)
    } catch (error) {
      console.error('Search failed:', error)
      setResults([])
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (!router.isReady) return
    if (!initialQuery.trim()) return
    setQuery(initialQuery)
    runSearch(initialQuery)
  }, [initialQuery, router.isReady])

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault()
    await runSearch(query)
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">Search</h1>

      <Card className="mb-6">
        <form onSubmit={handleSearch} className="flex gap-4">
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search by address, transaction hash, block number..."
            className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
          />
          <button
            type="submit"
            disabled={loading}
            className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50"
          >
            {loading ? 'Searching...' : 'Search'}
          </button>
        </form>
      </Card>

      {results.length > 0 && (
        <Card title="Search Results">
          <div className="space-y-4">
            {results.map((result, index) => (
              <div key={result.data?.hash ?? result.data?.address ?? result.data?.number ?? index} className="border-b border-gray-200 dark:border-gray-700 pb-4 last:border-0">
                {result.type === 'block' && result.data.number && (
                  <Link href={`/blocks/${result.data.number}`} className="text-primary-600 hover:underline">
                    Block #{result.data.number}
                  </Link>
                )}
                {result.type === 'transaction' && result.data.hash && (
                  <Link href={`/transactions/${result.data.hash}`} className="text-primary-600 hover:underline">
                    Transaction <Address address={result.data.hash} truncate />
                  </Link>
                )}
                {result.type === 'address' && result.data.address && (
                  <Link href={`/addresses/${result.data.address}`} className="text-primary-600 hover:underline">
                    Address <Address address={result.data.address} truncate />
                  </Link>
                )}
                <div className="text-sm text-gray-500 mt-1">
                  Type: {result.type} | Chain: {result.chain_id ?? 138} | Score: {(result.score ?? 0).toFixed(2)}
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  )
}
