'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import {
  fetchLpPositions,
  fetchPoolRegistry,
  type LpPositionRow,
  type PoolRegistryResponse,
} from '@/services/api/liquidityPositions'
import { chainLabel } from '@/utils/walletChainCatalog'

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

function formatShare(value: number): string {
  if (!Number.isFinite(value) || value <= 0) return '0%'
  return `${(value * 100).toFixed(value < 0.01 ? 4 : 2)}%`
}

interface LpPositionPanelProps {
  chainId?: number
  address?: string | null
  hintAddresses?: string[]
  title?: string
  compact?: boolean
}

export default function LpPositionPanel({
  chainId = 138,
  address,
  hintAddresses = [],
  title = 'LP positions',
  compact = false,
}: LpPositionPanelProps) {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [positions, setPositions] = useState<LpPositionRow[]>([])
  const [totalUsd, setTotalUsd] = useState<number | null>(null)
  const [registry, setRegistry] = useState<PoolRegistryResponse | null>(null)
  const [notes, setNotes] = useState<string[]>([])

  useEffect(() => {
    void fetchPoolRegistry(chainId).then(setRegistry).catch(() => setRegistry(null))
  }, [chainId])

  useEffect(() => {
    if (!address) {
      setPositions([])
      setTotalUsd(null)
      setNotes([])
      return
    }

    let active = true
    setLoading(true)
    setError(null)

    void fetchLpPositions({ chainId, address, hintAddresses })
      .then((report) => {
        if (!active) return
        if (!report) {
          setError('LP position scan is unavailable right now.')
          setPositions([])
          setTotalUsd(null)
          return
        }
        setPositions(report.positions)
        setTotalUsd(report.totalEstimatedUsd)
        setNotes(report.notes)
      })
      .catch(() => {
        if (!active) return
        setError('LP position scan failed.')
        setPositions([])
        setTotalUsd(null)
      })
      .finally(() => {
        if (active) setLoading(false)
      })

    return () => {
      active = false
    }
  }, [address, chainId, hintAddresses.join(',')])

  return (
    <div className="rounded-2xl border border-gray-200 bg-gray-50/70 p-4 dark:border-gray-800 dark:bg-gray-900/40">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">{title}</div>
          <div className="mt-1 text-sm text-gray-600 dark:text-gray-400">
            Curated DODO PMM + UniV2 pools on {chainLabel(chainId)}
            {registry ? ` · ${registry.count} pools in registry` : ''}
            {address ? '' : ' · connect a wallet to scan LP shares'}
          </div>
        </div>
        {totalUsd != null ? (
          <div className="text-right">
            <div className="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Estimated LP NAV</div>
            <div className="text-lg font-semibold text-gray-900 dark:text-white">{formatUsd(totalUsd)}</div>
          </div>
        ) : null}
      </div>

      {loading ? (
        <div className="mt-4 text-sm text-gray-600 dark:text-gray-400">Scanning on-chain LP balances…</div>
      ) : null}
      {error ? <div className="mt-4 text-sm text-red-600 dark:text-red-400">{error}</div> : null}

      {!loading && !error && address && positions.length === 0 ? (
        <div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
          No active LP shares detected in the curated pool registry for this address.
        </div>
      ) : null}

      {positions.length > 0 ? (
        <div className={`mt-4 space-y-3 ${compact ? '' : ''}`}>
          {positions.map((position) => (
            <div
              key={position.poolAddress}
              className="rounded-xl border border-gray-200 bg-white/80 px-4 py-3 dark:border-gray-700 dark:bg-black/10"
            >
              <div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
                <div>
                  <div className="font-semibold text-gray-900 dark:text-white">
                    {position.pairLabel}{' '}
                    <span className="text-xs font-normal text-gray-500 dark:text-gray-400">
                      ({position.venue.replace('_', ' ')})
                    </span>
                  </div>
                  <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    Pool {position.poolAddress.slice(0, 10)}…{position.poolAddress.slice(-8)} · share{' '}
                    {formatShare(position.shareOfPool)} · balance {position.shareBalanceUnits}
                  </div>
                </div>
                  <div className="mt-2 flex flex-col items-end gap-1">
                    <div className="text-sm font-semibold text-gray-900 dark:text-white">
                      {formatUsd(position.estimatedUsd)}
                    </div>
                    <Link href={`/pools/${position.poolAddress}`} className="text-xs text-primary-600 hover:underline">
                      Pool detail →
                    </Link>
                    <Link href={`/liquidity`} className="text-xs text-primary-600 hover:underline">
                      Liquidity tools →
                    </Link>
                  </div>
              </div>
            </div>
          ))}
        </div>
      ) : null}

      {notes.length > 0 ? (
        <div className="mt-4 space-y-1 text-xs text-gray-500 dark:text-gray-400">
          {notes.map((note) => (
            <p key={note}>{note}</p>
          ))}
        </div>
      ) : null}
    </div>
  )
}
