'use client'

import Link from 'next/link'
import Image from 'next/image'
import { useMemo, useState } from 'react'
import { ScrollReveal } from '@/components/shared/ScrollReveal'
import { useApp } from '@/components/providers/AppProvider'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import type { BackendSiteHomeAsset } from '@/lib/backend'
import type { AgentCatalogCategory, AgentProduct, AgentWorkflow, CourseAccessState } from '@/types'

function matchesCategory(product: AgentProduct, category: string) {
  if (category === '全部') return true
  return product.scenarioTags.includes(category)
}

function normalizeAccessState(value: unknown): CourseAccessState {
  if (value === 'closed' || value === 'free' || value === 'paid') return value
  return 'paid'
}

function accessForLevel(product: AgentProduct, level: 0 | 1 | 2) {
  if (level === 2) return normalizeAccessState(product.seniorAccess)
  if (level === 1) return normalizeAccessState(product.juniorAccess)
  return normalizeAccessState(product.registeredAccess)
}

function priceForLevel(product: AgentProduct, level: 0 | 1 | 2) {
  const base = Math.max(0, Math.round((product.price || 0) * 100))
  const raw = level === 2 ? product.seniorPriceAmount : level === 1 ? product.juniorPriceAmount : product.registeredPriceAmount
  return Math.max(0, Math.round((raw != null ? raw : base) / 100))
}

function guestPriceLabel(product: AgentProduct) {
  const access = accessForLevel(product, 0)
  if (access === 'closed') return '会员专享'
  if (access === 'free') return '免费'
  return `¥${priceForLevel(product, 0)}`
}

function userPriceLabel(product: AgentProduct, level: 0 | 1 | 2) {
  const access = accessForLevel(product, level)
  if (access === 'closed') return '会员专享'
  if (access === 'free') return '免费'
  return `¥${priceForLevel(product, level)}`
}

function categoryCount(products: AgentProduct[], category: string) {
  return products.filter((product) => matchesCategory(product, category)).length
}

export function AgentsPageClient({ products, heroAsset, categories, workflow }: { products: AgentProduct[]; heroAsset?: BackendSiteHomeAsset | null; categories: AgentCatalogCategory[]; workflow: AgentWorkflow | null }) {
  const dynamicCategories = useMemo(() => {
    const configured = categories.map((category) => category.name).filter(Boolean)
    const fromProducts = Array.from(new Set(products.flatMap((product) => product.scenarioTags || []))).filter(Boolean)
    return ['全部', ...(configured.length ? configured : fromProducts)]
  }, [categories, products])
  const [activeCategory, setActiveCategory] = useState('全部')
  const [heroImageFailed, setHeroImageFailed] = useState(false)
  const { user } = useApp()
  const filteredProducts = useMemo(
    () => products.filter((product) => matchesCategory(product, activeCategory)),
    [activeCategory, products],
  )

  return (
    <>
      <ScrollReveal />
      <section className="bg-white py-14">
        <div className="mx-auto grid max-w-[1280px] gap-12 px-6 lg:grid-cols-[0.88fr_1.12fr] lg:items-center">
          <div data-reveal="left">
            <h1 className="text-[38px] font-extrabold leading-tight text-ink md:text-[56px]">智能体产品</h1>
            <p className="mt-6 max-w-[680px] text-base leading-8 text-text-body">
              把政策研究、数据治理、产业服务和项目交付经验封装成可购买的业务智能体。用户按场景选择产品，下单后由团队完成配置、复核与交付，进度和结果沉淀在个人中心。
            </p>
            <p className="mt-4 max-w-[680px] text-sm leading-7 text-muted">
              它不是一次性的聊天问答，而是面向真实业务流程的产品：能复用、能协作、能追踪，也能根据机构场景继续扩展。
            </p>
          </div>

          <div data-reveal="right" className="relative">
            <div className="overflow-hidden rounded-[8px] border border-line bg-bg shadow-[0_20px_54px_rgba(15,23,42,0.08)]">
              {heroAsset?.imageUrl && !heroImageFailed ? (
                <Image
                  src={heroAsset.imageUrl}
                  alt={heroAsset.label || heroAsset.title || '智能体产品主视觉'}
                  width={960}
                  height={540}
                  unoptimized
                  onError={() => setHeroImageFailed(true)}
                  className="h-[360px] w-full object-cover"
                />
              ) : (
                <ImagePlaceholder label="智能体产品主视觉：多智能体协作、业务流程自动化与交付看板场景" className="h-[360px] w-full rounded-none" />
              )}
              <div className="border-t border-line bg-white px-6 py-5">
                <div className="text-lg font-extrabold leading-snug text-ink">{heroAsset?.title || '多智能体协作交付工作台'}</div>
                <div className="mt-2 text-sm font-bold leading-7 text-muted">
                  {heroAsset?.description || '把政策研究、数据治理、客户画像、内容生成和交付跟进串成可复用的业务流程。'}
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="bg-[#f7f9fc] py-12">
        <div className="mx-auto max-w-[1280px] px-6">
          <div data-reveal="fade" className="mb-8">
            <h2 className="text-3xl font-extrabold text-ink">{workflow?.title || '智能体工作流案例'}</h2>
          </div>

          <div data-reveal="lift" className="border-y border-line py-10">
            {!workflow?.nodes?.length ? (
              <div className="border border-dashed border-line bg-white px-5 py-8 text-sm font-bold text-muted">后台暂未配置智能体工作流节点</div>
            ) : (
            <div className="relative overflow-x-auto overflow-y-visible pb-3">
              <div className="relative h-[650px] min-w-[2300px]">
                <svg
                  className="pointer-events-none absolute inset-0 h-full w-full"
                  viewBox="0 0 2300 650"
                  fill="none"
                  aria-hidden="true"
                >
                  <path
                    d="M285 305 C330 180 365 145 430 140 C532 133 565 321 670 330 C772 339 805 145 910 140 C1012 135 1045 321 1150 330 C1252 339 1285 145 1390 140 C1492 135 1525 321 1630 330 C1732 339 1765 145 1870 140 C2010 132 2065 205 2015 305"
                    stroke="#cbd5e1"
                    strokeWidth="2"
                  />
                  <path
                    d="M285 305 C500 520 850 540 1150 500 C1450 460 1720 540 2015 305"
                    stroke="#e2e8f0"
                    strokeWidth="1.5"
                    strokeDasharray="6 8"
                  />
                </svg>

                {workflow.nodes.map((node) => {
                  const isEdge = node.id === 'problem' || node.id === 'result'
                  const isWide = node.size === 'wide'

                  return (
                    <div
                      key={node.id}
                      className={`absolute z-10 -translate-x-1/2 -translate-y-1/2 rounded-[10px] border border-line bg-white/95 p-4 text-left shadow-[0_16px_36px_rgba(15,23,42,0.08)] ${isEdge ? 'bg-[#fbfcfe]' : ''}`}
                      style={{ left: node.x, top: node.y }}
                    >
                      <span className="block text-[11px] font-extrabold text-soft">{node.label}</span>
                      <span className={`mt-1 block font-extrabold leading-6 text-ink ${isWide ? 'text-lg' : 'text-sm'}`}>
                        {node.title}
                      </span>
                      <span
                        className={`mt-2 block text-xs leading-6 text-muted ${
                          isWide ? 'w-[250px]' : 'w-[184px]'
                        }`}
                      >
                        {node.detail}
                      </span>
                    </div>
                  )
                })}
              </div>
            </div>
            )}
          </div>
        </div>
      </section>

      <section className="bg-[#f7f9fc] py-12">
        <div className="mx-auto max-w-[1280px] px-6">
          <div data-reveal="fade" className="mb-8">
            <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
              <h1 className="text-2xl font-extrabold text-ink">智能体列表</h1>
            </div>
            <div className="flex flex-wrap gap-2">
              {dynamicCategories.map((category) => {
                const isActive = activeCategory === category

                return (
                  <button
                    key={category}
                    type="button"
                    onClick={() => setActiveCategory(category)}
                    className={`inline-flex h-9 items-center gap-2 rounded-full px-4 text-sm font-extrabold transition-colors ${
                      isActive
                        ? 'bg-brand text-white shadow-[0_10px_24px_rgba(10,58,120,0.16)]'
                        : 'bg-[#f4f7fb] text-text-body hover:bg-brand-light hover:text-brand'
                    }`}
                  >
                    <span>{category}</span>
                    <span className={isActive ? 'text-white/70' : 'text-soft'}>{categoryCount(products, category)}</span>
                  </button>
                )
              })}
            </div>
          </div>

          <div data-reveal-group className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
            {filteredProducts.map((product) => {
              const priceText = user ? userPriceLabel(product, user.membershipLevel) : guestPriceLabel(product)
              const detail = product.detailDescription || product.deliveryNote || '购买后进入交付流程'

              return (
                <Link
                  key={product.id}
                  href={`/agents/${product.slug}`}
                  data-reveal="lift"
                  className="group block overflow-hidden rounded-[4px] border border-line bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)] transition hover:border-brand/30 hover:bg-[#f8fbff]"
                >
                  {product.coverUrl ? (
                    <div
                      className="relative aspect-[16/9] bg-cover bg-center"
                      style={{ backgroundImage: `url(${product.coverUrl})` }}
                    />
                  ) : (
                    <ImagePlaceholder label={`暂无智能体封面：${product.title}`} className="aspect-[16/9] w-full border-0 border-b border-dashed border-[#9db6d3]" />
                  )}
                  <div className="p-3">
                    <div className="min-h-10 text-sm font-extrabold leading-5 text-ink transition-colors group-hover:text-brand">
                      {product.title}
                    </div>
                    <div className="mt-2 text-xs font-bold text-brand">
                      {priceText}
                    </div>
                    <div className="mt-2 line-clamp-2 text-xs text-muted">
                      {detail}
                    </div>
                  </div>
                </Link>
              )
            })}
          </div>
        </div>
      </section>
    </>
  )
}
