'use client'

import Link from 'next/link'
import { Lock } from 'lucide-react'
import { useEffect, useState } from 'react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { useApp } from '@/components/providers/AppProvider'
import { backend, yuan } from '@/lib/backend'
import { mapBackendTask } from '@/lib/backend'
import type { AgentProduct } from '@/types'

export default function AccountAgentsPage() {
  const { user, token } = useApp()
  const [agentProducts, setAgentProducts] = useState<AgentProduct[]>([])
  const [deliveryTasks, setDeliveryTasks] = useState<ReturnType<typeof mapBackendTask>[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  useEffect(() => {
    if (!token) return
    setLoading(true)
    void Promise.all([
      backend.agentCatalog(),
      backend.accountTasks(token),
    ])
      .then(([catalog, tasks]) => {
        setAgentProducts(catalog.items.map((item) => ({
        id: item.id,
        slug: item.slug,
        title: item.title,
        scenarioTags: item.scenarioTags,
        registeredAccess: item.registeredAccess,
        juniorAccess: item.juniorAccess,
        seniorAccess: item.seniorAccess,
        registeredPriceAmount: item.registeredPriceAmount,
        juniorPriceAmount: item.juniorPriceAmount,
        seniorPriceAmount: item.seniorPriceAmount,
        price: yuan(item.priceAmount),
        detailDescription: item.detailDescription,
        summary: item.summary,
        deliveryNote: item.deliveryNote,
        coverUrl: item.coverUrl,
        })))
        setDeliveryTasks(tasks.items.map(mapBackendTask).filter((task) => task.type === 'agent'))
        setError('')
      })
      .catch((err) => {
        setAgentProducts([])
        setDeliveryTasks([])
        setError(err instanceof Error ? err.message : '智能体记录加载失败')
      })
      .finally(() => setLoading(false))
  }, [token])
  if (!user) return <AccountAuthPrompt message="登录后可查看已购买智能体和部署交付进度。" />
  if (loading) return <div className="rounded-[4px] border border-line bg-white p-8 text-sm font-bold text-muted">正在加载智能体...</div>

  const agentTasks = deliveryTasks.filter((task) => task.type === 'agent')
  const agentTaskByProductId = new Map(agentTasks.map((task) => [task.productId || task.id.split('-agent-')[1], task]))
  const openedAgents = agentProducts.filter((product) => agentTaskByProductId.has(product.id))

  function renderAgentCards(products: { product: AgentProduct; locked: boolean }[]) {
    return (
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
        {products.map(({ product, locked }) => {
          const task = agentTaskByProductId.get(product.id)

          return (
            <Link
              key={product.id}
              href={!locked && task ? `/account/delivery/${task.id}` : `/agents/${product.slug}`}
              className={`block overflow-hidden rounded-[4px] border bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)] transition hover:border-brand/30 ${
                locked ? 'border-line opacity-75 hover:opacity-100' : 'border-line hover:bg-[#f8fbff]'
              }`}
            >
              <div
                className="relative aspect-[16/9] bg-bg bg-cover bg-center"
                style={{ backgroundImage: product.coverUrl ? `url(${product.coverUrl})` : undefined }}
              >
                {!product.coverUrl && <div className="grid h-full place-items-center px-3 text-center text-xs font-extrabold text-soft">暂无图片</div>}
                {locked && (
                  <div className="absolute inset-0 grid place-items-center bg-white/45 backdrop-blur-[1px]">
                    <Lock className="h-5 w-5 text-muted" />
                  </div>
                )}
              </div>
              <div className="p-3">
                <div className="min-h-10 text-sm font-extrabold leading-5 text-ink">{product.title}</div>
                <div className={`mt-2 text-xs font-bold ${locked ? 'text-muted' : 'text-brand'}`}>
                  {locked ? '未开通' : task?.status}
                </div>
              </div>
            </Link>
          )
        })}
      </div>
    )
  }

  return (
    <div className="space-y-8">
      <section>
        <div className="mb-3 text-sm font-extrabold text-muted">
          {openedAgents.length > 0 ? `我的智能体（${openedAgents.length}）` : '我的智能体'}
        </div>
        {error && <div className="mb-4 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
        {openedAgents.length > 0 ? (
          <>
            {renderAgentCards(openedAgents.map((product) => ({ product, locked: false })))}
            <Link href="/agents" className="mt-5 inline-flex h-10 items-center rounded-[4px] border border-line px-4 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">
              发现更多智能体
            </Link>
          </>
        ) : (
          <AccountEmptyState
            title="暂无智能体"
            description="开通智能体后，会在这里进入对应的产品详情和交付资料页面。"
            actionLabel="浏览智能体"
            actionHref="/agents"
          />
        )}
      </section>
    </div>
  )
}
