'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { Card } from '@/libs/frontend-ui-primitives'
import DisclosureSection from '@/components/common/DisclosureSection'
import CompactMetricBar from '@/components/common/CompactMetricBar'
import ListFilterBar from '@/components/common/ListFilterBar'
import PageIntro from '@/components/common/PageIntro'
import PaginationControls from '@/components/common/PaginationControls'
import SectionTabs, { TabPanel, type SectionTab } from '@/components/common/SectionTabs'
import { type TokenListResponse } from '@/services/api/config'
import { tokensApi } from '@/services/api/tokens'
import TokenListSurfaceNote from '@/components/common/TokenListSurfaceNote'
import OperationsSurfaceNav from './OperationsSurfaceNav'
import {
  aggregateLiquidityPools,
  getRouteBackedPoolAddresses,
  selectFeaturedLiquidityTokens,
} from '@/services/api/liquidity'
import { routesApi, type MissionControlLiquidityPool, type RouteMatrixResponse } from '@/services/api/routes'
import { formatCurrency, formatNumber, truncateMiddle } from './OperationsPageShell'

const POOLS_PAGE_SIZE = 6

type PoolsPageTab = 'overview' | 'pools' | 'tokens'

function matchesPoolQuery(pool: { address?: string | null; token0?: { symbol?: string | null }; token1?: { symbol?: string | null }; dex?: string | null; sourceSymbols?: string[] }, query: string) {
  const normalizedQuery = query.trim().toLowerCase()
  if (!normalizedQuery) return true
  const haystack = [
    pool.address,
    pool.token0?.symbol,
    pool.token1?.symbol,
    pool.dex,
    ...(pool.sourceSymbols || []),
  ]
    .filter(Boolean)
    .join(' ')
    .toLowerCase()
  return haystack.includes(normalizedQuery)
}

interface TokenPoolRecord {
  symbol: string
  pools: MissionControlLiquidityPool[]
}

export default function PoolsOperationsPage() {
  const [tokenList, setTokenList] = useState<TokenListResponse | null>(null)
  const [routeMatrix, setRouteMatrix] = useState<RouteMatrixResponse | null>(null)
  const [tokenPoolRecords, setTokenPoolRecords] = useState<TokenPoolRecord[]>([])
  const [loadingError, setLoadingError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<PoolsPageTab>('pools')
  const [poolQuery, setPoolQuery] = useState('')
  const [poolPage, setPoolPage] = useState(1)
  const [tokenQuery, setTokenQuery] = useState('')

  useEffect(() => {
    let cancelled = false

    const load = async () => {
      const [tokenListResult, routeMatrixResult] = await Promise.allSettled([
        tokensApi.listForSurface('extended', 138).then(({ ok, data }) => ({ tokens: ok ? data : [] })),
        routesApi.getRouteMatrix(),
      ])

      if (cancelled) return

      if (tokenListResult.status === 'fulfilled') setTokenList(tokenListResult.value)
      if (routeMatrixResult.status === 'fulfilled') setRouteMatrix(routeMatrixResult.value)

      if (tokenListResult.status === 'fulfilled') {
        const featuredTokens = selectFeaturedLiquidityTokens(tokenListResult.value.tokens || [])
        const poolResults = await Promise.allSettled(
          featuredTokens.map(async (token) => ({
            symbol: token.symbol,
            pools: (await routesApi.getTokenPools(token.address)).pools || [],
          }))
        )

        if (!cancelled) {
          setTokenPoolRecords(
            poolResults
              .filter((result): result is PromiseFulfilledResult<TokenPoolRecord> => result.status === 'fulfilled')
              .map((result) => result.value)
          )
        }
      }

      if (tokenListResult.status === 'rejected' && routeMatrixResult.status === 'rejected') {
        setLoadingError('Live pool inventory is temporarily unavailable from the public explorer APIs.')
      }
    }

    load().catch((error) => {
      if (!cancelled) {
        setLoadingError(
          error instanceof Error ? error.message : 'Live pool inventory is temporarily unavailable from the public explorer APIs.'
        )
      }
    })

    return () => {
      cancelled = true
    }
  }, [])

  const featuredTokens = useMemo(
    () => selectFeaturedLiquidityTokens(tokenList?.tokens || []),
    [tokenList?.tokens]
  )
  const aggregatedPools = useMemo(
    () => aggregateLiquidityPools(tokenPoolRecords),
    [tokenPoolRecords]
  )
  const routeBackedPoolAddresses = useMemo(
    () => getRouteBackedPoolAddresses(routeMatrix),
    [routeMatrix]
  )

  const filteredPools = useMemo(
    () => aggregatedPools.filter((pool) => matchesPoolQuery(pool, poolQuery)),
    [aggregatedPools, poolQuery],
  )

  const poolPageCount = Math.max(1, Math.ceil(filteredPools.length / POOLS_PAGE_SIZE))

  const paginatedPools = useMemo(() => {
    const safePage = Math.min(Math.max(poolPage, 1), poolPageCount)
    const start = (safePage - 1) * POOLS_PAGE_SIZE
    return filteredPools.slice(start, start + POOLS_PAGE_SIZE)
  }, [filteredPools, poolPage, poolPageCount])

  const filteredFeaturedTokens = useMemo(() => {
    const normalizedQuery = tokenQuery.trim().toLowerCase()
    if (!normalizedQuery) return featuredTokens
    return featuredTokens.filter((token) => {
      const haystack = [token.symbol, token.name, token.address].filter(Boolean).join(' ').toLowerCase()
      return haystack.includes(normalizedQuery)
    })
  }, [featuredTokens, tokenQuery])

  useEffect(() => {
    setPoolPage(1)
  }, [poolQuery])

  useEffect(() => {
    if (poolPage > poolPageCount) {
      setPoolPage(poolPageCount)
    }
  }, [poolPage, poolPageCount])

  const poolTabs = useMemo<SectionTab<PoolsPageTab>[]>(
    () => [
      { id: 'overview', label: 'Overview' },
      { id: 'pools', label: 'Pool cards', count: aggregatedPools.length },
      { id: 'tokens', label: 'By token', count: featuredTokens.length },
    ],
    [aggregatedPools.length, featuredTokens.length],
  )

  return (
    <div className="container mx-auto px-4 py-4 sm:py-6">
      <PageIntro
        compact
        eyebrow="Live Pool Inventory"
        title="Pools"
        description="Live pool inventory from mission-control endpoints, cross-checked against the route matrix."
        actions={[
          { href: '/liquidity', label: 'Liquidity' },
          { href: '/routes', label: 'Routes' },
        ]}
      />
      <DisclosureSection title="Token list surface note" defaultOpen={false} alwaysCollapsible className="mb-3">
        <TokenListSurfaceNote className="text-sm text-gray-600 dark:text-gray-400" />
      </DisclosureSection>

      <OperationsSurfaceNav />

      {loadingError ? (
        <Card className="mb-6 border border-red-200 bg-red-50/70 dark:border-red-900/50 dark:bg-red-950/20">
          <p className="text-sm leading-6 text-red-900 dark:text-red-100">{loadingError}</p>
        </Card>
      ) : null}

      <CompactMetricBar
        metrics={[
          { label: 'Pools', value: formatNumber(aggregatedPools.length) },
          { label: 'Route-backed', value: formatNumber(routeBackedPoolAddresses.length) },
          { label: 'Featured', value: formatNumber(featuredTokens.length) },
          { label: 'With pools', value: formatNumber(tokenPoolRecords.filter((record) => record.pools.length > 0).length) },
        ]}
      />

      <SectionTabs
        tabs={poolTabs}
        activeTab={activeTab}
        onChange={setActiveTab}
        idPrefix="pools-page"
        ariaLabel="Pools sections"
        className="-mx-4 mb-4 px-4"
      />

      <TabPanel idPrefix="pools-page" tabId="overview" activeTab={activeTab}>
      <DisclosureSection title="Pool inventory details" defaultOpen={false} alwaysCollapsible className="mb-4">
      <div className="mb-4 grid gap-3 md:grid-cols-3">
        <Card className="border border-emerald-200 bg-emerald-50/70 dark:border-emerald-900/50 dark:bg-emerald-950/20">
          <div className="text-sm font-semibold uppercase tracking-wide text-emerald-800 dark:text-emerald-100">
            Unique pools
          </div>
          <div className="mt-2 text-3xl font-bold text-gray-900 dark:text-white">
            {formatNumber(aggregatedPools.length)}
          </div>
          <div className="mt-2 text-sm text-gray-700 dark:text-gray-300">
            Discovered across {formatNumber(featuredTokens.length)} featured Chain 138 tokens.
          </div>
        </Card>
        <Card className="border border-sky-200 bg-sky-50/70 dark:border-sky-900/50 dark:bg-sky-950/20">
          <div className="text-sm font-semibold uppercase tracking-wide text-sky-800 dark:text-sky-100">
            Route-backed pools
          </div>
          <div className="mt-2 text-3xl font-bold text-gray-900 dark:text-white">
            {formatNumber(routeBackedPoolAddresses.length)}
          </div>
          <div className="mt-2 text-sm text-gray-700 dark:text-gray-300">
            Unique pool addresses referenced by the live route matrix.
          </div>
        </Card>
        <Card>
          <div className="text-sm text-gray-500 dark:text-gray-400">Featured coverage</div>
          <div className="mt-2 text-3xl font-bold text-gray-900 dark:text-white">
            {formatNumber(tokenPoolRecords.filter((record) => record.pools.length > 0).length)}
          </div>
          <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">
            Featured tokens currently returning at least one live pool.
          </div>
        </Card>
      </div>
      </DisclosureSection>

      <Card title="Pool operation shortcuts" className="mb-4">
        <div className="space-y-4 text-sm leading-6 text-gray-600 dark:text-gray-400">
          <p>
            The broader liquidity page now shows live route, planner, and pool access together.
          </p>
          <p>
            The current route matrix publishes {formatNumber(routeMatrix?.counts?.liveSwapRoutes)} live
            swap routes and {formatNumber(routeMatrix?.counts?.liveBridgeRoutes)} bridge routes.
          </p>
          <div className="flex flex-wrap gap-3">
            <Link
              href="/liquidity"
              className="rounded-full bg-primary-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-primary-700"
            >
              Open liquidity access
            </Link>
            <Link
              href="/routes"
              className="rounded-full border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition hover:border-primary-400 hover:text-primary-700 dark:border-gray-600 dark:text-gray-300 dark:hover:text-primary-300"
            >
              Open routes page
            </Link>
            <Link
              href="/wallet"
              className="rounded-full border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 transition hover:border-primary-400 hover:text-primary-700 dark:border-gray-600 dark:text-gray-300 dark:hover:text-primary-300"
            >
              Open wallet tools
            </Link>
          </div>
        </div>
      </Card>
      </TabPanel>

      <TabPanel idPrefix="pools-page" tabId="pools" activeTab={activeTab}>
      <div className="mb-6">
        <Card title="Live Pool Cards">
          <ListFilterBar
            query={poolQuery}
            onQueryChange={setPoolQuery}
            placeholder="Filter pools by pair, DEX, address, or source token"
            resultCount={filteredPools.length}
            totalCount={aggregatedPools.length}
            className="mb-4"
          />
          <div className="grid gap-4 lg:grid-cols-3">
            {paginatedPools.map((pool) => (
              <Link
                key={pool.address}
                href={`/pools/${pool.address}`}
                className="rounded-2xl border border-gray-200 bg-gray-50 p-4 transition hover:border-primary-400 hover:bg-primary-50/40 dark:border-gray-700 dark:bg-gray-900/40 dark:hover:border-primary-700"
              >
                <div className="text-base font-semibold text-gray-900 dark:text-white">
                  {(pool.token0?.symbol || '?') + ' / ' + (pool.token1?.symbol || '?')}
                </div>
                <div className="mt-1 text-sm text-gray-600 dark:text-gray-400">
                  {pool.dex || 'Unknown DEX'} · TVL {formatCurrency(pool.tvl)}
                </div>
                <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  {truncateMiddle(pool.address, 10, 8)}
                </div>
                <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                  Seen from {pool.sourceSymbols.join(', ')}
                </div>
              </Link>
            ))}
            {paginatedPools.length === 0 ? (
              <p className="text-sm text-gray-600 dark:text-gray-400 lg:col-span-3">
                {aggregatedPools.length === 0 ? 'No live pools available right now.' : 'No pools match your filter.'}
              </p>
            ) : null}
          </div>
          <PaginationControls
            page={poolPage}
            pageCount={poolPageCount}
            onPageChange={setPoolPage}
            label="Pools"
            ariaLabel="Pool cards pagination"
          />
        </Card>
      </div>
      </TabPanel>

      <TabPanel idPrefix="pools-page" tabId="tokens" activeTab={activeTab}>
      <div>
        <Card title="Featured Token Pool Counts">
          <ListFilterBar
            query={tokenQuery}
            onQueryChange={setTokenQuery}
            placeholder="Filter featured tokens"
            resultCount={filteredFeaturedTokens.length}
            totalCount={featuredTokens.length}
            className="mb-4"
          />
          <div className="space-y-3">
            {filteredFeaturedTokens.length === 0 ? (
              <p className="text-sm text-gray-600 dark:text-gray-400">No featured tokens match your filter.</p>
            ) : (
              filteredFeaturedTokens.map((token) => {
              const record = tokenPoolRecords.find((entry) => entry.symbol === token.symbol)
              return (
                <DisclosureSection
                  key={token.address}
                  title={`${token.symbol} · ${formatNumber(record?.pools.length || 0)} pools`}
                  defaultOpen={token.symbol === 'cUSDT' || token.symbol === 'cUSDC'}
                  alwaysCollapsible
                  className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40"
                >
                  <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                    <div>
                      <div className="text-base font-semibold text-gray-900 dark:text-white">{token.symbol}</div>
                      <div className="mt-1 text-sm text-gray-600 dark:text-gray-400">{token.name || 'Unnamed token'}</div>
                    </div>
                    <Link
                      href={`/tokens/${token.address}`}
                      className="text-sm font-medium text-primary-600 hover:underline"
                    >
                      Open token →
                    </Link>
                  </div>
                  {record && record.pools.length > 0 ? (
                    <div className="mt-4 grid gap-3 md:grid-cols-2">
                      {record.pools.map((pool) => (
                        <Link
                          key={pool.address}
                          href={`/pools/${pool.address}`}
                          className="rounded-xl border border-gray-200 bg-white/80 p-3 transition hover:border-primary-400 dark:border-gray-700 dark:bg-black/10"
                        >
                          <div className="text-sm font-semibold text-gray-900 dark:text-white">
                            {(pool.token0?.symbol || '?') + ' / ' + (pool.token1?.symbol || '?')}
                          </div>
                          <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                            {pool.dex || 'Unknown DEX'} · TVL {formatCurrency(pool.tvl)}
                          </div>
                        </Link>
                      ))}
                    </div>
                  ) : (
                    <p className="mt-3 text-sm text-gray-600 dark:text-gray-400">No live pools returned for this token yet.</p>
                  )}
                </DisclosureSection>
              )
            })
            )}
          </div>
        </Card>
      </div>
      </TabPanel>
    </div>
  )
}
