'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
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 { fetchOfficialProtocols, type OfficialProtocolRow, type ProtocolVerificationReport } from '@/services/api/officialProtocols'
import { formatTimestamp } from '@/utils/format'

export default function ProtocolDetailPage() {
  const router = useRouter()
  const protocolId = typeof router.query.id === 'string' ? router.query.id : ''
  const [protocol, setProtocol] = useState<OfficialProtocolRow | null>(null)
  const [forbidden, setForbidden] = useState<Array<{ id: string; description: string }>>([])
  const [verification, setVerification] = useState<ProtocolVerificationReport | null>(null)
  const [registryMeta, setRegistryMeta] = useState<{ schemaVersion?: string; updated?: string; generatedAt?: string }>({})
  const [loading, setLoading] = useState(true)
  const [protocolTab, setProtocolTab] = useState<'overview' | 'contracts'>('overview')

  useEffect(() => {
    if (!router.isReady || !protocolId) return
    let active = true
    void fetchOfficialProtocols(protocolId)
      .then((report) => {
        if (!active) return
        setProtocol(report?.protocol ?? report?.protocols?.[0] ?? null)
        setForbidden(report?.forbiddenProductionPatterns ?? [])
        setVerification(report?.verification ?? null)
        setRegistryMeta({
          schemaVersion: report?.schemaVersion,
          updated: report?.updated,
          generatedAt: report?.generatedAt,
        })
      })
      .finally(() => {
        if (active) setLoading(false)
      })
    return () => {
      active = false
    }
  }, [protocolId, router.isReady])

  return (
    <div className="container mx-auto px-4 py-4 sm:py-6">
      <OperationsSurfaceNav />
      <PageIntro
        compact
        eyebrow="Official protocol"
        title={protocol?.id ?? (protocolId || 'Protocol')}
        description={
          protocol?.upstreamRepo
            ? `Official upstream · ${protocol.contracts.length} Chain 138 contracts.`
            : 'Chain 138 official protocol catalog.'
        }
        actions={[
          { href: '/protocols', label: 'All protocols' },
          { href: '/liquidity', label: 'Liquidity' },
        ]}
      />

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

      {!loading && !protocol ? (
        <Card title="Not found">
          <Link href="/protocols" className="text-primary-600 hover:underline">
            Back to protocols →
          </Link>
        </Card>
      ) : null}

      {protocol ? (
        <>
          <SectionTabs
            idPrefix="protocol-detail"
            ariaLabel="Protocol detail sections"
            tabs={[
              { id: 'overview', label: 'Overview' },
              { id: 'contracts', label: 'Contracts', count: protocol.contracts.length },
            ]}
            activeTab={protocolTab}
            onChange={setProtocolTab}
            className="mb-4"
          />

          <TabPanel idPrefix="protocol-detail" tabId="overview" activeTab={protocolTab}>
          {verification ? (
            <Card title="On-chain verification" className="mb-4">
              <div className="flex flex-wrap gap-2">
                <EntityBadge
                  label={verification.allVerified ? 'all contracts deployed' : 'review required'}
                  tone={verification.allVerified ? 'success' : 'warning'}
                />
                <EntityBadge label={`chain ${verification.chainId}`} tone="neutral" />
                {registryMeta.schemaVersion ? (
                  <EntityBadge label={`registry ${registryMeta.schemaVersion}`} tone="info" className="normal-case tracking-normal" />
                ) : null}
              </div>
              <p className="mt-3 text-sm text-gray-600 dark:text-gray-400">
                Live bytecode probe via Chain 138 RPC at {formatTimestamp(verification.verifiedAt)}.
                {registryMeta.updated ? ` Registry updated ${registryMeta.updated}.` : ''}
              </p>
              <div className="mt-4 space-y-2">
                {verification.contracts.map((row) => (
                  <div key={row.address} className="flex flex-wrap items-center gap-2 text-sm">
                    <EntityBadge
                      label={row.status.replace('_', ' ')}
                      tone={row.status === 'verified' ? 'success' : 'warning'}
                      className="normal-case tracking-normal"
                    />
                    <span className="font-medium text-gray-900 dark:text-white">{row.name}</span>
                    <span className="text-gray-500 dark:text-gray-400">
                      code {row.codeSize} bytes
                      {row.minCodeSize ? ` (min ${row.minCodeSize})` : ''}
                    </span>
                  </div>
                ))}
              </div>
            </Card>
          ) : null}

          <Card title="Deployment metadata">
            <div className="flex flex-wrap gap-2">
              {protocol.requiredForProduction ? <EntityBadge label="required for production" tone="success" /> : null}
              {protocol.classification ? (
                <EntityBadge label={protocol.classification} tone="info" className="normal-case tracking-normal" />
              ) : null}
            </div>
            {protocol.upstreamRepo ? (
              <p className="mt-3 text-sm">
                Upstream:{' '}
                <a href={protocol.upstreamRepo} target="_blank" rel="noopener noreferrer" className="text-primary-600 hover:underline">
                  {protocol.upstreamRepo}
                </a>
              </p>
            ) : null}
            {protocol.deployScripts?.length ? (
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                Deploy: {protocol.deployScripts.join(', ')}
              </p>
            ) : null}
            {protocol.integrationNotes ? (
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">{protocol.integrationNotes}</p>
            ) : null}
          </Card>

          {forbidden.length > 0 ? (
            <DisclosureSection title="Forbidden in production" defaultOpen={false} alwaysCollapsible className="mt-4">
              <Card>
                <ul className="list-disc space-y-2 pl-5 text-sm text-gray-700 dark:text-gray-300">
                  {forbidden.slice(0, 5).map((row) => (
                    <li key={row.id}>
                      <span className="font-medium">{row.id}</span> — {row.description}
                    </li>
                  ))}
                </ul>
              </Card>
            </DisclosureSection>
          ) : null}
          </TabPanel>

          <TabPanel idPrefix="protocol-detail" tabId="contracts" activeTab={protocolTab}>
          <Card title="Contracts">
            <div className="space-y-3">
              {protocol.contracts.map((contract) => (
                <div key={contract.name} className="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-gray-700">
                  <div className="font-semibold text-gray-900 dark:text-white">{contract.name}</div>
                  <div className="mt-1">
                    <Address address={contract.address} truncate showCopy />
                  </div>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {contract.inventoryKey ? (
                      <EntityBadge label={contract.inventoryKey} tone="neutral" className="normal-case tracking-normal" />
                    ) : null}
                    <Link href={`/addresses/${contract.address}`} className="text-xs text-primary-600 hover:underline">
                      Explorer address →
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          </Card>
          </TabPanel>
        </>
      ) : null}
    </div>
  )
}
