'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { Card, Address } from '@/libs/frontend-ui-primitives'
import PageIntro from '@/components/common/PageIntro'
import SectionTabs, { TabPanel } from '@/components/common/SectionTabs'
import DisclosureSection from '@/components/common/DisclosureSection'
import EntityBadge from '@/components/common/EntityBadge'
import OperationsSurfaceNav from '@/components/explorer/OperationsSurfaceNav'
import LpPositionPanel from '@/components/wallet/LpPositionPanel'
import {
  fetchPoolRegistry,
  type CuratedPoolRegistryEntry,
} from '@/services/api/liquidityPositions'
import { formatBigIntWhole, formatTimestamp } from '@/utils/format'

function formatUsd(value: number | undefined): string {
  if (value == null || !Number.isFinite(value)) return 'Unavailable'
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: value >= 1000 ? 0 : 2,
  }).format(value)
}

function formatReserve(raw: string | undefined, symbol: string): string {
  if (!raw) return 'Unavailable'
  const decimals = symbol.toUpperCase().includes('BTC') ? 8 : 6
  try {
    const value = BigInt(raw)
    const scale = 10n ** BigInt(decimals)
    const whole = value / scale
    const fraction = value % scale
    const fractionText = fraction
      .toString()
      .padStart(decimals, '0')
      .slice(0, 4)
      .replace(/0+$/, '')
    return fractionText
      ? `${formatBigIntWhole(whole)}.${fractionText} ${symbol}`
      : `${formatBigIntWhole(whole)} ${symbol}`
  } catch {
    return 'Unavailable'
  }
}

function isStableLikeSymbol(symbol: string): boolean {
  const normalized = symbol.toUpperCase().replace(/^C/, '')
  return ['USDT', 'USDC', 'EURC', 'EURT', 'GBPC', 'DAI', 'BUSD', 'TUSD', 'FRAX'].includes(normalized)
}

function stableReserveAsymmetryNote(
  pool: CuratedPoolRegistryEntry,
): { severity: 'warning' | 'info'; message: string; deviationBps: number } | null {
  if (pool.reserve0Usd == null || pool.reserve1Usd == null) return null
  if (!isStableLikeSymbol(pool.baseSymbol) || !isStableLikeSymbol(pool.quoteSymbol)) return null
  const legs = [pool.reserve0Usd, pool.reserve1Usd].filter((v) => v > 0)
  if (legs.length < 2) return null
  const min = Math.min(...legs)
  const max = Math.max(...legs)
  const deviationBps = Math.round(((max - min) / max) * 10000)
  if (deviationBps < 150) return null
  return {
    severity: deviationBps >= 500 ? 'warning' : 'info',
    deviationBps,
    message: `Stable-pair reserves are asymmetric (${deviationBps} bps USD leg gap). PMM pools can hold unequal notionals while remaining tradable — do not assume 50/50 peg depth for trade sizing.`,
  }
}

interface PoolDetailPageProps {
  poolAddress: string
}

export default function PoolDetailPage({ poolAddress }: PoolDetailPageProps) {
  const [pools, setPools] = useState<CuratedPoolRegistryEntry[]>([])
  const [loading, setLoading] = useState(true)
  const [poolTab, setPoolTab] = useState<'summary' | 'lp'>('summary')

  useEffect(() => {
    let active = true
    void fetchPoolRegistry()
      .then((report) => {
        if (!active) return
        setPools(report?.pools ?? [])
      })
      .finally(() => {
        if (active) setLoading(false)
      })
    return () => {
      active = false
    }
  }, [])

  const pool = useMemo(() => {
    const lower = poolAddress.toLowerCase()
    return pools.find(
      (row) => row.poolAddress.toLowerCase() === lower || row.lpTokenAddress.toLowerCase() === lower,
    )
  }, [poolAddress, pools])

  const pairLabel = pool ? `${pool.baseSymbol} / ${pool.quoteSymbol}` : poolAddress
  const asymmetryNote = pool ? stableReserveAsymmetryNote(pool) : null

  return (
    <div className="container mx-auto px-4 py-4 sm:py-6">
      <OperationsSurfaceNav />
      <PageIntro
        compact
        eyebrow="Curated pool registry"
        title={loading ? 'Loading pool…' : pool ? pairLabel : 'Pool not in registry'}
        description="DODO PMM + UniV2 registry · LP receipts are chain-local only."
        actions={[
          { href: '/liquidity', label: 'Liquidity' },
          { href: '/pools', label: 'All pools' },
        ]}
      />

      {loading ? (
        <Card>
          <p className="text-sm text-gray-600 dark:text-gray-400">Loading pool registry…</p>
        </Card>
      ) : null}

      {!loading && !pool ? (
        <Card title="Not in curated registry">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            This address is not listed in the curated pool registry. It may still be a valid contract on Chain 138 or
            another network — open the address page for generic explorer data.
          </p>
          <div className="mt-4 flex flex-wrap gap-3">
            <Link href={`/addresses/${poolAddress}`} className="text-primary-600 hover:underline">
              Open address page →
            </Link>
            <Link href="/search" className="text-primary-600 hover:underline">
              Back to search →
            </Link>
          </div>
        </Card>
      ) : null}

      {pool ? (
        <>
          {asymmetryNote ? (
            <DisclosureSection title="Reserve asymmetry notice" defaultOpen={false} alwaysCollapsible className="mb-4">
              <Card>
                <p
                  className={
                    asymmetryNote.severity === 'warning'
                      ? 'text-sm text-amber-800 dark:text-amber-200'
                      : 'text-sm text-gray-700 dark:text-gray-300'
                  }
                >
                  {asymmetryNote.message}
                </p>
              </Card>
            </DisclosureSection>
          ) : null}

          <SectionTabs
            idPrefix="pool-detail"
            ariaLabel="Pool detail sections"
            tabs={[
              { id: 'summary', label: 'Summary' },
              { id: 'lp', label: 'Your LP' },
            ]}
            activeTab={poolTab}
            onChange={setPoolTab}
            className="mb-4"
          />

          <TabPanel idPrefix="pool-detail" tabId="summary" activeTab={poolTab}>
          <Card title="Pool summary">
            <div className="flex flex-wrap gap-2">
              <EntityBadge label={pool.venue.replace('_', ' ')} tone="info" />
              <EntityBadge label={pool.lpTokenType.replace('_', ' ')} tone="neutral" />
              <EntityBadge label={`chain ${pool.chainId}`} tone="warning" />
              {pool.integrationStack ? (
                <EntityBadge label={pool.integrationStack} tone="success" className="normal-case tracking-normal" />
              ) : null}
            </div>
            <dl className="mt-4 grid gap-3 text-sm sm:grid-cols-2">
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Pool address</dt>
                <dd className="mt-1">
                  <Address address={pool.poolAddress} truncate showCopy />
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">LP token</dt>
                <dd className="mt-1">
                  <Address address={pool.lpTokenAddress} truncate showCopy />
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Base</dt>
                <dd className="mt-1">
                  <Link href={`/tokens/${pool.baseAddress}`} className="text-primary-600 hover:underline">
                    {pool.baseSymbol}
                  </Link>
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Quote</dt>
                <dd className="mt-1">
                  <Link href={`/tokens/${pool.quoteAddress}`} className="text-primary-600 hover:underline">
                    {pool.quoteSymbol}
                  </Link>
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Est. liquidity (USD)</dt>
                <dd className="mt-1 font-semibold text-gray-900 dark:text-white">
                  {formatUsd(pool.totalLiquidityUsd)}
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Base reserve</dt>
                <dd className="mt-1 text-gray-700 dark:text-gray-300">
                  {formatReserve(pool.reserve0, pool.baseSymbol)}
                  {pool.reserve0Usd != null && pool.reserve0Usd > 0 ? (
                    <span className="ml-2 text-xs text-gray-500 dark:text-gray-400">
                      ({formatUsd(pool.reserve0Usd)})
                    </span>
                  ) : null}
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Quote reserve</dt>
                <dd className="mt-1 text-gray-700 dark:text-gray-300">
                  {formatReserve(pool.reserve1, pool.quoteSymbol)}
                  {pool.reserve1Usd != null && pool.reserve1Usd > 0 ? (
                    <span className="ml-2 text-xs text-gray-500 dark:text-gray-400">
                      ({formatUsd(pool.reserve1Usd)})
                    </span>
                  ) : null}
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Liquidity source</dt>
                <dd className="mt-1 text-gray-700 dark:text-gray-300">
                  {pool.liquiditySource ?? 'curated registry'}
                  {pool.liquidityAsOf ? (
                    <span className="block text-xs text-gray-500 dark:text-gray-400">
                      As of {formatTimestamp(pool.liquidityAsOf)}
                    </span>
                  ) : null}
                </dd>
              </div>
              <div>
                <dt className="text-gray-500 dark:text-gray-400">Policy</dt>
                <dd className="mt-1 text-gray-700 dark:text-gray-300">
                  LP shares are chain-local receipts — not cross-chain mesh tokens.
                </dd>
              </div>
            </dl>
          </Card>
          </TabPanel>

          <TabPanel idPrefix="pool-detail" tabId="lp" activeTab={poolTab}>
          <LpPositionPanel
            chainId={pool.chainId}
            title="Your LP in this pool"
            compact
            hintAddresses={[pool.poolAddress, pool.lpTokenAddress]}
          />
          </TabPanel>
        </>
      ) : null}
    </div>
  )
}
