'use client'

import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useEffect } from 'react'
import { Trash2 } from 'lucide-react'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { useApp } from '@/components/providers/AppProvider'

const typeLabel = {
  course: '课程',
  event: '活动',
  data: '数据服务',
  agent: '智能体',
  expert: '专家',
  consulting: '咨询',
  membership: '会员',
}

export function CartPageClient() {
  const router = useRouter()
  const { cartItems, removeCartItem, clearCart, user } = useApp()
  const needsOnboarding = Boolean(user && !user.onboardingCompleted)
  const regularCartItems = cartItems.filter((item) => item.type !== 'expert')
  const visibleCartItems = user && !needsOnboarding ? regularCartItems : []
  const visibleCartTotal = visibleCartItems.reduce((sum, item) => sum + item.price, 0)
  const isEmptyState = !user || needsOnboarding || visibleCartItems.length === 0

  useEffect(() => {
    if (needsOnboarding) router.replace('/onboarding?redirect=%2Fcart')
  }, [needsOnboarding, router])

  if (needsOnboarding) {
    return (
      <section className="grid min-h-[calc(100vh-70px)] place-items-center bg-bg px-6">
        <div className="text-sm font-extrabold text-muted">跳转中...</div>
      </section>
    )
  }

  return (
    <>
      <section className="min-h-[calc(100dvh-106px)] bg-bg pb-10 pt-[22px]">
        <div className="mx-auto max-w-[1280px] px-6 lg:pr-[416px]">
          <div className={`rounded-[4px] border border-line bg-white ${isEmptyState ? 'min-h-[504px]' : ''}`}>
            <div className="flex items-center justify-between px-6 py-4">
              <div className="text-lg font-extrabold text-ink">购物车</div>
              {user && visibleCartItems.length > 0 && (
                <button type="button" onClick={clearCart} className="text-sm font-bold text-muted hover:text-brand">
                  清空购物车
                </button>
              )}
            </div>

            {!user ? (
              <AccountEmptyState title="尚未登录" />
            ) : visibleCartItems.length === 0 ? (
              <AccountEmptyState title="购物车还是空的" />
            ) : (
              <div className="divide-y divide-line">
                {visibleCartItems.map((item) => (
                  <div key={`${item.type}-${item.id}`} className="flex flex-col gap-4 px-6 py-5 md:flex-row md:items-center">
                    <div className="grid h-12 w-12 shrink-0 place-items-center rounded-[4px] bg-brand-light text-xs font-extrabold text-brand">
                      {typeLabel[item.type]}
                    </div>
                    <div className="min-w-0 flex-1">
                      <Link href={item.href} className="font-bold text-ink hover:text-brand">{item.title}</Link>
                      {item.meta && <div className="mt-1 text-sm text-muted">{item.meta}</div>}
                    </div>
                    <div className="flex items-center justify-between gap-4 md:min-w-40">
                      <div className="text-lg font-extrabold text-brand">{item.price === 0 ? '免费' : `¥${item.price.toLocaleString()}`}</div>
                      <button
                        type="button"
                        onClick={() => removeCartItem(item.id, item.type)}
                        className="grid h-9 w-9 place-items-center rounded-[4px] border border-line text-muted hover:border-brand hover:text-brand"
                        aria-label={`移除 ${item.title}`}
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <aside className="mt-6 h-fit rounded-[4px] border border-line bg-white p-6 lg:fixed lg:right-[max(1.5rem,calc((100vw-1280px)/2+1.5rem))] lg:top-32 lg:mt-0 lg:w-[360px]">
            <div className="text-lg font-extrabold text-ink">结算摘要</div>
            <div className="mt-5 space-y-3 text-sm">
              <div className="flex justify-between text-muted">
                <span>商品数量</span>
                <span>{visibleCartItems.length}</span>
              </div>
              <div className="flex justify-between text-muted">
                <span>会员折扣</span>
                <span>结算页计算</span>
              </div>
              <div className="border-t border-line pt-4">
                <div className="flex justify-between">
                  <span className="font-bold text-ink">小计</span>
                  <span className="text-2xl font-extrabold text-brand">¥{(user ? visibleCartTotal : 0).toLocaleString()}</span>
                </div>
              </div>
            </div>
            <button
              type="button"
              onClick={() => {
                if (!user) {
                  router.push('/login-required?redirect=%2Fcart&action=cart')
                  return
                }
                router.push('/checkout')
              }}
              disabled={user ? visibleCartItems.length === 0 : false}
              className="mt-6 w-full rounded-[4px] bg-brand py-3 text-sm font-extrabold text-white hover:bg-brand-dark disabled:cursor-not-allowed disabled:bg-line-dark"
            >
              {user ? '去结算' : '登录后结算'}
            </button>
          </aside>
        </div>
      </section>
    </>
  )
}
