'use client'

import Link from 'next/link'
import { ArrowRight, ChevronLeft, ChevronRight, PanelLeftClose, PanelLeftOpen, Search } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import { ScrollReveal } from '@/components/shared/ScrollReveal'
import { useApp } from '@/components/providers/AppProvider'
import { backend, mapBackendExpert, type BackendExpertDirection } from '@/lib/backend'
import type { Expert } from '@/types'

const flow = ['选择专家', '填写问题', '选择时段', '提交预约', '专家确认']
const fallbackHeroSlides = [
  {
    imageUrl: '',
    label: '专家访谈、线上咨询与产业智库服务场景',
  },
  {
    imageUrl: '',
    label: '专家评审会、规划研讨与方案论证现场',
  },
  {
    imageUrl: '',
    label: '政企项目交流、产业资源对接与专题咨询',
  },
]

function availabilityText(expert: Expert) {
  if (expert.acceptingOrders === false || expert.availabilityStatus === 'unavailable') return '无法预约'
  if (expert.availabilityStatus === 'this-week') return '本周可约'
  return '下周可约'
}

function normalizeGroupName(value: string) {
  if (value === 'AI 与智能化') return 'AI 与技术'
  return value
}

function expertInGroup(expert: Expert, groupName: string, directions: BackendExpertDirection[]) {
  if (groupName === '全部') return true
  const names = new Set(directions.filter((item) => normalizeGroupName(item.groupName) === groupName).map((item) => item.name))
  return (expert.directions?.length ? expert.directions : expert.specialties).some((item) => names.has(item))
}

function ExpertPhoto({ expert, className }: { expert: Expert; className: string }) {
  if (expert.photoUrl) {
    return <img src={expert.photoUrl} alt={`${expert.name}专家照片`} className={`${className} object-cover`} />
  }
  return <ImagePlaceholder label={`${expert.name}专家照片`} className={className} />
}

interface ExpertHeroSlide {
  imageUrl: string
  label: string
}

export function ExpertsPageClient({ initialExperts, heroSlides = [] }: { initialExperts: Expert[]; heroSlides?: ExpertHeroSlide[] }) {
  const { user } = useApp()
  const [experts, setExperts] = useState<Expert[]>(initialExperts)
  const [directions, setDirections] = useState<BackendExpertDirection[]>([])
  const [activeGroup, setActiveGroup] = useState('全部')
  const [filtersOpen, setFiltersOpen] = useState(true)
  const [activeHero, setActiveHero] = useState(0)
  const [search, setSearch] = useState('')
  const [availableOnly, setAvailableOnly] = useState(false)
  const [loading, setLoading] = useState(false)

  const groups = useMemo(() => {
    const unique = Array.from(new Set(directions.map((item) => normalizeGroupName(item.groupName))))
    return ['全部', ...unique]
  }, [directions])

  const filteredExperts = useMemo(() => {
    return experts.filter((expert) => expertInGroup(expert, activeGroup, directions))
  }, [activeGroup, directions, experts])

  const groupCounts = useMemo(() => {
    return groups.reduce<Record<string, number>>((result, group) => {
      result[group] = experts.filter((expert) => expertInGroup(expert, group, directions)).length
      return result
    }, {})
  }, [directions, experts, groups])

  useEffect(() => {
    let cancelled = false
    void backend.expertDirections()
      .then((result) => {
        if (!cancelled) setDirections(result.items)
      })
      .catch(() => {
        if (!cancelled) setDirections([])
      })
    return () => {
      cancelled = true
    }
  }, [])

  useEffect(() => {
    let cancelled = false
    const timeout = window.setTimeout(() => {
      if (!cancelled) setLoading(true)
      void backend.experts({ search: search.trim(), available: availableOnly })
        .then((result) => {
          if (!cancelled) setExperts(result.items.map(mapBackendExpert))
        })
        .catch(() => {
          if (!cancelled) setExperts([])
        })
        .finally(() => {
          if (!cancelled) setLoading(false)
        })
    }, 220)
    return () => {
      cancelled = true
      window.clearTimeout(timeout)
    }
  }, [availableOnly, search])

  const heroItems = heroSlides.length ? heroSlides : fallbackHeroSlides

  useEffect(() => {
    const timer = window.setInterval(() => {
      setActiveHero((current) => (current + 1) % heroItems.length)
    }, 5200)
    return () => window.clearInterval(timer)
  }, [heroItems.length])

  function moveHero(step: number) {
    setActiveHero((current) => (current + step + heroItems.length) % heroItems.length)
  }

  const showExpertJoin = !user?.expertProfileStatus && (!user?.expertApplicationStatus || ['rejected', 'withdrawn'].includes(user.expertApplicationStatus))

  return (
    <>
      <ScrollReveal />

      <section className="bg-white py-10">
        <div className="mx-auto grid max-w-[1280px] gap-12 px-6 lg:grid-cols-[0.9fr_1.1fr] lg:items-center">
          <div data-reveal="left">
            <h1 className="text-[34px] font-extrabold leading-tight text-ink md:text-[46px]">专家平台</h1>
            <p className="mt-5 max-w-2xl text-base leading-8 text-muted">
              汇聚政策研究、数据治理、智慧城市、产业数字化与人工智能等方向专家，面向项目研判、方案评审和专题咨询提供预约服务。
            </p>
            <p className="mt-4 max-w-2xl text-base leading-8 text-text-body">
              用户可以先浏览专家背景与专业方向，再进入专家主页选择咨询时段并提交问题。
            </p>
          </div>
          <div data-reveal="right" className="overflow-hidden rounded-[4px] bg-bg">
            {heroItems[activeHero]?.imageUrl ? (
              <img
                src={heroItems[activeHero].imageUrl}
                alt={heroItems[activeHero].label}
                className="h-[292px] w-full rounded-[4px] object-cover"
              />
            ) : (
              <ImagePlaceholder label={`专家平台主视觉：${heroItems[activeHero]?.label || '专家平台主视觉'}`} className="h-[292px] w-full rounded-[4px]" />
            )}
            <div className="flex items-center justify-between px-4 py-3">
              <div className="flex gap-2">
                {heroItems.map((item, index) => (
                  <button
                    key={`${item.label}-${index}`}
                    type="button"
                    onClick={() => setActiveHero(index)}
                    className={`h-1.5 rounded-full transition-all ${activeHero === index ? 'w-9 bg-brand' : 'w-4 bg-line-dark hover:bg-muted'}`}
                    aria-label={`切换专家平台主视觉 ${index + 1}`}
                  />
                ))}
              </div>
              <div className="flex gap-2">
                <button type="button" onClick={() => moveHero(-1)} className="grid h-8 w-8 place-items-center rounded-[4px] border border-line bg-white text-muted hover:border-brand hover:text-brand" aria-label="上一张专家平台主视觉">
                  <ChevronLeft className="h-4 w-4" />
                </button>
                <button type="button" onClick={() => moveHero(1)} className="grid h-8 w-8 place-items-center rounded-[4px] border border-line bg-white text-muted hover:border-brand hover:text-brand" aria-label="下一张专家平台主视觉">
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="bg-bg py-12">
        <div className={`mx-auto grid max-w-[1280px] gap-8 px-6 transition-[grid-template-columns] duration-300 ${filtersOpen ? 'lg:grid-cols-[236px_1fr]' : 'lg:grid-cols-[64px_1fr]'}`}>
          <aside className="h-fit border-y border-line bg-white lg:sticky lg:top-28" data-reveal="left">
            <div className="flex items-center justify-between border-b border-line px-4 py-3">
              {filtersOpen && <div className="text-sm font-extrabold text-ink">专家方向</div>}
              <button
                type="button"
                onClick={() => setFiltersOpen((value) => !value)}
                className="grid h-9 w-9 place-items-center rounded-[4px] border border-line text-muted hover:border-brand hover:text-brand"
                aria-label={filtersOpen ? '收起专家方向筛选' : '展开专家方向筛选'}
              >
                {filtersOpen ? <PanelLeftClose className="h-4 w-4" /> : <PanelLeftOpen className="h-4 w-4" />}
              </button>
            </div>
            {filtersOpen ? (
              <div className="max-h-[360px] overflow-y-auto">
                {groups.map((group) => {
                  const isActive = activeGroup === group
                  return (
                    <button
                      key={group}
                      type="button"
                      onClick={() => setActiveGroup(group)}
                      className={`group flex w-full items-center justify-between border-b border-line px-4 py-4 text-left text-sm font-bold transition-colors last:border-b-0 ${
                        isActive ? 'bg-brand-light text-brand' : 'text-text-body hover:bg-brand-light hover:text-brand'
                      }`}
                    >
                      <span>{group}</span>
                      <span className={`text-xs ${isActive ? 'text-brand' : 'text-soft group-hover:text-brand'}`}>{groupCounts[group] || 0}</span>
                    </button>
                  )
                })}
              </div>
            ) : (
              <button
                type="button"
                onClick={() => setFiltersOpen(true)}
                className="flex h-[180px] w-full items-center justify-center px-3 text-xs font-extrabold text-muted hover:text-brand"
              >
                <span className="[writing-mode:vertical-rl]">筛选方向</span>
              </button>
            )}
          </aside>

          <div className="space-y-8">
            <div data-reveal="fade" className="grid gap-4 bg-white p-5 md:grid-cols-[1fr_auto] md:items-end">
              <div>
                <h2 className="text-2xl font-extrabold text-ink">{activeGroup === '全部' ? '专家资源' : activeGroup}</h2>
                <p className="mt-3 text-sm leading-7 text-muted">
                  {loading ? '正在加载专家资源...' : activeGroup === '全部' ? `共 ${filteredExperts.length} 位专家，可按方向筛选查看。` : `共 ${filteredExperts.length} 位相关专家。`}
                </p>
              </div>
              <div className="grid gap-3 sm:grid-cols-[260px_auto]">
                <label className="relative block">
                  <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-soft" />
                  <input
                    value={search}
                    onChange={(event) => setSearch(event.target.value)}
                    placeholder="搜索姓名、机构、职务"
                    className="h-10 w-full rounded-[4px] border border-line bg-white pl-9 pr-3 text-sm font-bold outline-none focus:border-brand"
                  />
                </label>
                <label className="flex h-10 items-center gap-2 rounded-[4px] border border-line bg-white px-3 text-sm font-bold text-muted">
                  <input type="checkbox" checked={availableOnly} onChange={(event) => setAvailableOnly(event.target.checked)} className="accent-brand" />
                  只看可预约
                </label>
              </div>
            </div>

            {filteredExperts.length === 0 ? (
              <div className="bg-white px-6 py-14 text-center text-sm font-bold text-muted">暂无符合条件的专家。</div>
            ) : (
              <div className="grid gap-5 lg:grid-cols-2" data-reveal-group>
                {filteredExperts.map((expert) => {
                  const unavailable = expert.acceptingOrders === false || expert.availabilityStatus === 'unavailable'
                  return (
                    <article key={expert.id} data-reveal="lift" className="group bg-white transition-all hover:-translate-y-1 hover:shadow-[0_18px_45px_rgba(15,23,42,0.09)]">
                      <Link href={`/experts/${expert.slug}`} className="grid gap-5 p-5 md:grid-cols-[132px_1fr]">
                        <ExpertPhoto expert={expert} className="h-40 w-full rounded-[4px]" />
                        <div className="flex min-h-[220px] flex-col justify-between">
                          <div>
                            <div className="flex items-start justify-between gap-4">
                              <div>
                                <h3 className="text-2xl font-extrabold text-ink transition-colors group-hover:text-brand">{expert.name}</h3>
                                <p className="mt-1 text-sm leading-6 text-muted">{expert.title}</p>
                                <p className="text-sm leading-6 text-muted">{expert.organization}</p>
                              </div>
                              <span className={`shrink-0 text-xs font-extrabold ${unavailable ? 'text-soft' : 'text-brand'}`}>
                                {availabilityText(expert)}
                              </span>
                            </div>
                            <p className="mt-4 line-clamp-3 text-sm leading-7 text-text-body">{expert.homepageIntro || expert.bio}</p>
                            <div className="mt-4 flex flex-wrap gap-2">
                              {(expert.directions?.length ? expert.directions : expert.specialties).map((tag) => (
                                <span key={tag} className="bg-bg px-2.5 py-1 text-xs font-bold text-text-body">{tag}</span>
                              ))}
                            </div>
                          </div>
                          <div className="mt-4 grid gap-3 border-t border-line pt-4 md:grid-cols-[1fr_auto] md:items-center">
                            <div className="text-xs leading-5 text-muted">
                              咨询参考价
                              <span className="ml-2 font-extrabold text-text-body">¥{expert.pricePerHour.toLocaleString()}/小时</span>
                            </div>
                            <div className="inline-flex items-center text-sm font-extrabold text-brand">
                              查看专家主页
                              <ArrowRight className="ml-2 h-4 w-4 transition-transform group-hover:translate-x-1" />
                            </div>
                          </div>
                        </div>
                      </Link>
                    </article>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      </section>

      <section className="bg-white py-16">
        <div className="mx-auto grid max-w-[1280px] gap-10 px-6 lg:grid-cols-[300px_1fr]">
          <div data-reveal="left">
            <h2 className="text-2xl font-extrabold text-ink">预约流程</h2>
            <p className="mt-4 text-sm leading-7 text-muted">专家确认后进入咨询流程，订单与进度会保留在个人中心。</p>
          </div>
          <div className="relative pb-8 pt-6" data-reveal-group>
            <div className="absolute left-0 right-0 top-[44px] hidden h-px bg-line md:block" />
            <div className="grid gap-6 md:grid-cols-5">
              {flow.map((item, index) => (
                <div key={item} data-reveal="lift" className="relative">
                  <div className="relative z-10 flex h-10 w-10 items-center justify-center rounded-full border border-brand bg-white text-xs font-extrabold text-brand shadow-[0_0_0_6px_white]">
                    {String(index + 1).padStart(2, '0')}
                  </div>
                  <div className="mt-6 text-base font-extrabold text-ink">{item}</div>
                  <div className="mt-3 text-xs leading-5 text-muted">
                    {index === 0 ? '进入专家主页' : index === 1 ? '说明咨询背景' : index === 2 ? '锁定可约时间' : index === 3 ? '生成预约记录' : '确认后开始服务'}
                  </div>
                  <div className="mt-3 h-px w-10 bg-brand/25 md:hidden" />
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {showExpertJoin && (
        <section className="bg-bg py-16">
          <div className="mx-auto grid max-w-[1280px] gap-8 px-6 lg:grid-cols-[0.9fr_1.1fr] lg:items-center">
            <div data-reveal="left">
              <div className="text-sm font-extrabold text-brand">成为专家</div>
              <h2 className="mt-3 text-3xl font-extrabold leading-tight text-ink">把你的行业经验接入研究院专家网络</h2>
              <p className="mt-5 text-sm leading-8 text-muted">
                面向政策研究、数据治理、智慧城市、产业数字化、人工智能、安全合规等方向开放专家入驻。通过审核后，可参与平台咨询预约、项目评审、专题研讨和课程共创。
              </p>
              <Link href="/experts/join" className="mt-7 inline-flex h-10 items-center rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark">
                申请成为专家
              </Link>
            </div>
            <div data-reveal="right" className="grid gap-3 sm:grid-cols-3">
              {[
                ['资料提交', '填写个人背景、专家方向、项目经验和代表成果。'],
                ['资质审核', '运营团队核对材料，并设置价格、分成和发布状态。'],
                ['开放预约', '审核通过后进入专家资源库，承接咨询与项目需求。'],
              ].map(([title, text], index) => (
                <div key={title} className="rounded-[4px] border border-line bg-white p-5 shadow-[0_10px_28px_rgba(15,23,42,0.04)]">
                  <div className="text-xs font-extrabold text-brand">0{index + 1}</div>
                  <div className="mt-3 text-base font-extrabold text-ink">{title}</div>
                  <p className="mt-3 text-xs leading-6 text-muted">{text}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}
    </>
  )
}
