'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { AlertTriangle, Home, RefreshCw } from 'lucide-react'
import { useEffect, useMemo } from 'react'
import { BrandLogo } from '@/components/shared/BrandLogo'
import { BRAND_NAME } from '@/lib/brand'
import { captureWebException } from '@/lib/sentry-lite'

function fallbackHref(pathname: string) {
  if (pathname.startsWith('/admin')) return '/admin'
  if (pathname.startsWith('/staff')) return '/staff'
  if (pathname.startsWith('/account')) return '/account'
  return '/'
}

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  const pathname = usePathname()
  const backHref = fallbackHref(pathname)
  const incidentId = useMemo(() => {
    if (error.digest) return error.digest.slice(0, 12).toUpperCase()
    return `WEB-${Date.now().toString(36).toUpperCase()}`
  }, [error.digest])

  useEffect(() => {
    console.error('Global app error', { incidentId, error })
    void captureWebException(error, { incidentId, pathname })
  }, [error, incidentId, pathname])

  return (
    <section className="min-h-[calc(100vh-70px)] bg-bg px-5 py-10 md:px-8 md:py-14">
      <div className="mx-auto flex w-full max-w-[980px] flex-col gap-6">
        <div className="flex items-center gap-3">
          <BrandLogo className="h-10 w-10 rounded-full bg-white shadow-sm" />
          <div>
            <div className="text-sm font-bold text-ink">{BRAND_NAME}</div>
            <div className="text-xs text-muted">服务状态</div>
          </div>
        </div>

        <div className="border border-line bg-white">
          <div className="border-b border-line px-5 py-4 md:px-7">
            <div className="flex items-center gap-3">
              <span className="grid h-9 w-9 place-items-center border border-amber/25 bg-[#fff8eb] text-amber">
                <AlertTriangle className="h-5 w-5" />
              </span>
              <div>
                <h1 className="text-xl font-bold text-ink md:text-2xl">页面暂时无法打开</h1>
                <p className="mt-1 text-sm text-muted">系统已记录这次异常，请稍后重试或返回工作台。</p>
              </div>
            </div>
          </div>

          <div className="grid gap-5 px-5 py-6 md:grid-cols-[1fr_auto] md:items-end md:px-7">
            <div className="space-y-3 text-sm text-text-body">
              <div className="grid gap-2 sm:grid-cols-2">
                <div className="border border-line bg-bg px-4 py-3">
                  <div className="text-xs text-muted">错误编号</div>
                  <div className="mt-1 font-mono text-sm font-semibold text-ink">{incidentId}</div>
                </div>
                <div className="border border-line bg-bg px-4 py-3">
                  <div className="text-xs text-muted">当前路径</div>
                  <div className="mt-1 truncate font-mono text-sm text-ink">{pathname || '/'}</div>
                </div>
              </div>
              <p className="text-sm leading-7 text-muted">
                如果重试后仍然出现此提示，请把错误编号发给管理员，方便我们定位这次请求。
              </p>
            </div>

            <div className="flex flex-wrap gap-3 md:justify-end">
              <button
                type="button"
                onClick={reset}
                className="inline-flex h-11 items-center gap-2 bg-brand px-5 text-sm font-bold text-white hover:bg-brand-dark"
              >
                <RefreshCw className="h-4 w-4" />
                重试
              </button>
              <Link
                href={backHref}
                className="inline-flex h-11 items-center gap-2 border border-line bg-white px-5 text-sm font-bold text-ink hover:border-brand hover:text-brand"
              >
                <Home className="h-4 w-4" />
                {backHref === '/' ? '返回首页' : '返回工作台'}
              </Link>
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}
