import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import Link from 'next/link'
import { ArrowRight, CalendarDays } from 'lucide-react'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import { getExpert, getExperts, getExpertSlots } from '@/lib/server-experts'
import type { Expert } from '@/types'

export async function generateStaticParams() {
  const experts = await getExperts()
  return experts.map((e) => ({ slug: e.slug }))
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params
  const expert = await getExpert(slug)
  if (!expert) return {}
  return { title: `${expert.name} · 专家咨询` }
}

function availabilityText(expert: Expert, openSlotCount: number) {
  if (expert.acceptingOrders === false) return '专家已停止接单'
  if (expert.availabilityStatus === 'unavailable' || openSlotCount === 0) return '暂无可预约时段'
  if (expert.availabilityStatus === 'this-week') return '本周可预约'
  return '下周可预约'
}

function ExpertPhoto({ expert }: { expert: Expert }) {
  if (expert.photoUrl) {
    return <img src={expert.photoUrl} alt={`${expert.name}专家照片`} className="h-[420px] w-full rounded-[4px] object-cover" />
  }
  return <ImagePlaceholder label={`${expert.name}专家照片：正式头像、访谈或工作场景`} className="h-[420px] w-full rounded-[4px]" />
}

export default async function ExpertDetailPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const expert = await getExpert(slug)
  if (!expert) notFound()

  const slots = await getExpertSlots(slug)
  const openSlots = slots.filter((slot) => slot.status === 'open' && new Date(slot.startsAt).getTime() > Date.now())
  const canBook = expert.acceptingOrders !== false && expert.availabilityStatus !== 'unavailable' && openSlots.length > 0
  const directions = expert.directions?.length ? expert.directions : expert.specialties

  return (
    <>
      <section className="bg-white py-12">
        <div className="mx-auto max-w-[1280px] px-6">
          <div className="mb-8 flex items-center gap-2 text-sm font-bold text-soft">
            <Link href="/experts" className="text-muted hover:text-brand">专家平台</Link>
            <span>/</span>
            <span>{expert.name}</span>
          </div>

          <div className="grid gap-12 lg:grid-cols-[0.92fr_1.08fr] lg:items-center">
            <div>
              <div className={`text-sm font-extrabold ${canBook ? 'text-brand' : 'text-soft'}`}>{availabilityText(expert, openSlots.length)}</div>
              <h1 className="mt-3 text-[34px] font-extrabold leading-tight text-ink md:text-[46px]">{expert.name}</h1>
              <div className="mt-3 text-base leading-7 text-muted">{expert.title} · {expert.organization}</div>
              <p className="mt-7 text-sm leading-8 text-text-body">{expert.homepageIntro || expert.bio}</p>

              <div className="mt-6 flex flex-wrap items-center gap-2">
                <span className="mr-2 text-sm font-bold text-soft">专家方向</span>
                {directions.map((item) => (
                  <span key={item} className="bg-bg px-3 py-2 text-sm font-bold text-text-body">{item}</span>
                ))}
              </div>

              <div className="mt-7 grid gap-5 border-y border-line py-5 sm:grid-cols-2">
                <div className="text-sm">
                  <div className="text-soft">咨询参考价</div>
                  <div className="mt-1 font-extrabold text-ink">¥{expert.pricePerHour.toLocaleString()}/小时</div>
                </div>
                <div className="text-sm">
                  <div className="text-soft">未来 7 天开放时段</div>
                  <div className="mt-1 font-extrabold text-ink">{openSlots.length} 个</div>
                </div>
              </div>

              {canBook ? (
                <Link
                  href={`/experts/${expert.slug}/booking`}
                  className="mt-7 inline-flex h-11 items-center justify-center gap-2 rounded-[4px] bg-brand px-6 text-sm font-extrabold text-white transition-colors hover:bg-brand-dark"
                >
                  预约咨询
                  <ArrowRight className="h-4 w-4" />
                </Link>
              ) : (
                <button type="button" disabled className="mt-7 inline-flex h-11 items-center gap-2 rounded-[4px] bg-bg px-6 text-sm font-extrabold text-soft">
                  <CalendarDays className="h-4 w-4" />
                  无法预约
                </button>
              )}
            </div>

            <ExpertPhoto expert={expert} />
          </div>
        </div>
      </section>

      <section className="bg-bg py-12">
        <div className="mx-auto grid max-w-[1280px] gap-6 px-6 lg:grid-cols-2">
          <div className="bg-white p-6">
            <h2 className="text-xl font-extrabold text-ink">项目经验</h2>
            <p className="mt-4 whitespace-pre-wrap text-sm leading-8 text-text-body">{expert.projectExperience || '暂未填写项目经验。'}</p>
          </div>
          <div className="bg-white p-6">
            <h2 className="text-xl font-extrabold text-ink">代表成果</h2>
            <p className="mt-4 whitespace-pre-wrap text-sm leading-8 text-text-body">{expert.representativeAchievements || '暂未填写代表成果。'}</p>
          </div>
        </div>
      </section>
    </>
  )
}
