'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { Card } from '@/libs/frontend-ui-primitives'
import PageIntro from '@/components/common/PageIntro'
import DisclosureSection from '@/components/common/DisclosureSection'
import EntityBadge from '@/components/common/EntityBadge'
import OperationsSurfaceNav from '@/components/explorer/OperationsSurfaceNav'
import { fetchOfficialProtocols, type OfficialProtocolsResponse } from '@/services/api/officialProtocols'

export default function ProtocolsIndexPage() {
  const [report, setReport] = useState<OfficialProtocolsResponse | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let active = true
    void fetchOfficialProtocols()
      .then((data) => {
        if (active) setReport(data)
      })
      .finally(() => {
        if (active) setLoading(false)
      })
    return () => {
      active = false
    }
  }, [])

  return (
    <div className="container mx-auto px-4 py-4 sm:py-6">
      <OperationsSurfaceNav />
      <PageIntro
        compact
        eyebrow="Chain 138 infrastructure"
        title="Official protocol contracts"
        description="Production DODO, UniV2/V3, CCIP, Multicall3, and integration contracts from official upstream sources."
        actions={[
          { href: '/liquidity', label: 'Liquidity' },
          { href: '/token-aggregation/api/v1/report/official-protocols', label: 'JSON API' },
        ]}
      />

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

      {!loading && !report ? (
        <Card title="Registry unavailable">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            The official protocol registry API is temporarily unavailable.
          </p>
        </Card>
      ) : null}

      {report ? (
        <div className="space-y-4">
          <DisclosureSection title="Production guardrails" defaultOpen={false} alwaysCollapsible>
            <ul className="list-disc space-y-2 pl-5 text-sm text-gray-700 dark:text-gray-300">
              {report.guardrails.slice(0, 4).map((line) => (
                <li key={line}>{line}</li>
              ))}
            </ul>
          </DisclosureSection>

          <Card title={`Protocols (${report.count})`}>
            <div className="grid gap-3 sm:grid-cols-2">
              {report.protocols.map((protocol) => (
                <Link
                  key={protocol.id}
                  href={`/protocols/${protocol.id}`}
                  className="block rounded-2xl border border-gray-200 px-4 py-4 hover:border-primary-300 dark:border-gray-700"
                >
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="font-semibold text-gray-900 dark:text-white">{protocol.id}</span>
                    {protocol.requiredForProduction ? (
                      <EntityBadge label="production" tone="success" />
                    ) : null}
                    {protocol.classification ? (
                      <EntityBadge label={protocol.classification} tone="neutral" className="normal-case tracking-normal" />
                    ) : null}
                  </div>
                  <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                    {protocol.contracts.length} contract{protocol.contracts.length === 1 ? '' : 's'}
                    {protocol.upstreamRepo ? ' · official upstream' : ''}
                  </p>
                </Link>
              ))}
            </div>
          </Card>
        </div>
      ) : null}
    </div>
  )
}
