'use client'

import Link from 'next/link'
import { useParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { CalendarClock, FileText, Video } from 'lucide-react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { useApp } from '@/components/providers/AppProvider'
import { assetUrl, backend, type BackendExpertBooking } from '@/lib/backend'

function formatDateTime(value?: string | null, fallback = '时间待确认') {
  if (!value) return fallback
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return fallback
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function localInputFromIso(value?: string | null) {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}T${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function isoFromLocal(value: string) {
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? '' : date.toISOString()
}

function statusText(status: BackendExpertBooking['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'pending_expert') return '待专家确认'
  if (status === 'confirmed') return '预约中'
  if (status === 'pending_user_confirm') return '待确认完成'
  if (status === 'disputed') return '争议处理中'
  if (status === 'completed') return '已完成'
  if (status === 'rejected') return '已拒绝'
  return '已取消'
}

function statusTone(status: BackendExpertBooking['status']) {
  if (status === 'completed') return 'bg-brand/10 text-brand'
  if (status === 'pending_user_confirm') return 'bg-amber-50 text-amber-700'
  if (status === 'disputed') return 'bg-red-50 text-red-700'
  if (status === 'confirmed') return 'bg-green-50 text-green-700'
  if (status === 'pending_payment') return 'bg-amber-50 text-amber-700'
  return 'bg-bg text-muted'
}

function meetingIsOpen(status: BackendExpertBooking['status'], startsAt?: string | null) {
  if (status !== 'confirmed' || !startsAt) return false
  const diff = new Date(startsAt).getTime() - Date.now()
  return diff >= 0 && diff <= 30 * 60 * 1000
}

export default function AccountExpertBookingDetailPage() {
  const params = useParams<{ id: string }>()
  const { user, token } = useApp()
  const [booking, setBooking] = useState<BackendExpertBooking | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [saved, setSaved] = useState('')
  const [disputeReason, setDisputeReason] = useState('')
  const [rescheduleForm, setRescheduleForm] = useState({ startsAt: '', endsAt: '', reason: '' })

  useEffect(() => {
    if (!token || !params.id) return
    let mounted = true
    setLoading(true)
    setError('')
    backend.accountExpertBooking(token, params.id)
      .then((item) => {
        if (!mounted) return
        setBooking(item)
        setRescheduleForm({
          startsAt: localInputFromIso(item.startsAt),
          endsAt: localInputFromIso(item.endsAt),
          reason: '',
        })
      })
      .catch((err) => {
        if (mounted) setError(err instanceof Error ? err.message : '专家预约详情加载失败')
      })
      .finally(() => {
        if (mounted) setLoading(false)
      })
    return () => {
      mounted = false
    }
  }, [params.id, token])

  if (!user) return <AccountAuthPrompt message="登录后可查看专家预约详情。" />

  async function requestReschedule() {
    if (!token || !booking) return
    const startsAt = isoFromLocal(rescheduleForm.startsAt)
    const endsAt = isoFromLocal(rescheduleForm.endsAt)
    if (!startsAt || !endsAt || new Date(startsAt).getTime() >= new Date(endsAt).getTime()) {
      setError('请填写有效的新会议时间')
      return
    }
    try {
      const updated = await backend.createAccountExpertBookingReschedule(token, booking.id, {
        startsAt,
        endsAt,
        reason: rescheduleForm.reason || '用户申请改期',
      })
      setBooking(updated)
      setSaved('改期申请已提交')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '改期申请失败')
    }
  }

  async function respondReschedule(action: 'accepted' | 'rejected') {
    if (!token || !booking?.pendingChange) return
    try {
      const updated = await backend.respondAccountExpertBookingReschedule(token, booking.id, booking.pendingChange.id, {
        action,
        note: action === 'accepted' ? '确认改期' : '拒绝改期',
      })
      setBooking(updated)
      setSaved(action === 'accepted' ? '已确认改期' : '已拒绝改期')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '改期处理失败')
    }
  }

  async function confirmCompletion() {
    if (!token || !booking) return
    try {
      const updated = await backend.confirmAccountExpertBookingCompletion(token, booking.id)
      setBooking(updated)
      setSaved('已确认完成')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '确认完成失败')
    }
  }

  async function disputeCompletion() {
    if (!token || !booking) return
    const reason = disputeReason.trim()
    if (!reason) {
      setError('请填写争议原因')
      return
    }
    try {
      const updated = await backend.disputeAccountExpertBookingCompletion(token, booking.id, reason)
      setBooking(updated)
      setSaved('争议已提交')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '提交争议失败')
    }
  }

  if (loading) {
    return <div className="rounded-[4px] border border-line bg-white p-8 text-sm font-bold text-muted">正在加载专家预约详情...</div>
  }

  if (!booking) {
    return (
      <div className="rounded-[4px] border border-line bg-white p-8">
        <h1 className="text-2xl font-extrabold text-ink">预约不存在或无权访问</h1>
        {error && <p className="mt-3 text-sm font-bold text-muted">{error}</p>}
        <Link href="/account/expert-bookings" className="mt-6 inline-flex rounded-[4px] bg-brand px-5 py-2.5 text-sm font-extrabold text-white">返回专家预约</Link>
      </div>
    )
  }

  const isBookingUser = booking.userId === user.id
  const showMeetingEntry = meetingIsOpen(booking.status, booking.startsAt)
  const canRespondChange = Boolean(booking.pendingChange) && (
    (isBookingUser && booking.pendingChange?.requesterType !== 'user') ||
    (!isBookingUser && booking.pendingChange?.requesterType === 'user')
  )

  return (
    <div className="grid gap-6">
      <nav className="flex items-center gap-2 text-sm font-bold text-muted">
        <Link href="/account/expert-bookings" className="hover:text-brand">专家预约</Link>
        <span>/</span>
        <span className="text-ink">预约详情</span>
      </nav>

      {error && <div className="rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
      {saved && !error && <div className="rounded-[4px] bg-green-50 px-4 py-3 text-sm font-bold text-green">{saved}</div>}

      <section className="grid gap-6 lg:grid-cols-[1fr_340px]">
        <div className="rounded-[4px] border border-line bg-white p-7">
          <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
            <div>
              <span className={`inline-flex rounded-[4px] px-3 py-1.5 text-xs font-extrabold ${statusTone(booking.status)}`}>{statusText(booking.status)}</span>
              <h1 className="mt-4 text-3xl font-extrabold leading-10 text-ink">{booking.expert.name} 专家咨询</h1>
              <p className="mt-2 text-sm font-bold text-muted">{booking.bookingNo || booking.id}</p>
            </div>
            <div className="rounded-[4px] bg-bg px-4 py-3 text-sm font-extrabold text-ink">
              {formatDateTime(booking.startsAt)}
            </div>
          </div>

          <div className="mt-8 grid gap-4 md:grid-cols-2">
            <div className="rounded-[4px] bg-bg p-4">
              <div className="text-xs font-extrabold text-muted">专家</div>
              <div className="mt-2 text-lg font-extrabold text-ink">{booking.expert.name}</div>
              <div className="mt-1 text-sm font-bold leading-6 text-muted">{booking.expert.title} · {booking.expert.organization}</div>
            </div>
            <div className="rounded-[4px] bg-bg p-4">
              <div className="text-xs font-extrabold text-muted">联系人</div>
              <div className="mt-2 text-lg font-extrabold text-ink">{booking.contactName || booking.user.displayName || '平台用户'}</div>
              <div className="mt-1 text-sm font-bold text-muted">{booking.contactPhone || booking.user.contactPhone || booking.user.phone || '未填写手机号'}</div>
            </div>
          </div>

          <div className="mt-8 divide-y divide-line">
            <div className="grid gap-2 py-5 md:grid-cols-[120px_1fr]">
              <div className="text-sm font-extrabold text-muted">咨询问题</div>
              <div className="whitespace-pre-wrap text-sm font-bold leading-7 text-ink">{booking.question || '未填写咨询问题'}</div>
            </div>
            <div className="grid gap-2 py-5 md:grid-cols-[120px_1fr]">
              <div className="text-sm font-extrabold text-muted">背景资料</div>
              <div className="whitespace-pre-wrap text-sm font-bold leading-7 text-ink">{booking.background || '暂未补充背景资料'}</div>
            </div>
            <div className="grid gap-2 py-5 md:grid-cols-[120px_1fr]">
              <div className="text-sm font-extrabold text-muted">上传资料</div>
              {(booking.materialFiles || []).length > 0 ? (
                <div className="grid gap-2">
                  {(booking.materialFiles || []).map((file) => (
                    <a key={file.id} href={assetUrl(file.url || `/api/files/${file.id}`)} className="inline-flex w-fit items-center gap-2 text-sm font-extrabold text-brand hover:text-brand-dark">
                      <FileText className="h-4 w-4" />
                      {file.fileName || file.id}
                    </a>
                  ))}
                </div>
              ) : (
                <div className="text-sm font-bold text-muted">暂未上传资料</div>
              )}
            </div>
          </div>

          {booking.pendingChange && (
            <div className="mt-6 rounded-[4px] border border-amber-200 bg-amber-50 p-4">
              <div className="text-sm font-extrabold text-amber-800">改期申请</div>
              <div className="mt-2 text-sm font-bold leading-7 text-amber-800">
                {formatDateTime(booking.pendingChange.requestedStartsAt)} - {formatDateTime(booking.pendingChange.requestedEndsAt)}
              </div>
              <div className="mt-1 text-sm font-bold text-amber-800">{booking.pendingChange.reason || '未填写原因'}</div>
              {canRespondChange ? (
                <div className="mt-4 flex gap-2">
                  <button type="button" onClick={() => void respondReschedule('accepted')} className="h-9 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white">同意改期</button>
                  <button type="button" onClick={() => void respondReschedule('rejected')} className="h-9 rounded-[4px] border border-line bg-white px-4 text-xs font-extrabold text-muted">拒绝</button>
                </div>
              ) : (
                <div className="mt-3 text-xs font-bold text-amber-700">等待对方确认</div>
              )}
            </div>
          )}

          {isBookingUser && booking.status === 'confirmed' && !booking.pendingChange && (
            <div className="mt-6 rounded-[4px] border border-line bg-bg p-4">
              <div className="text-sm font-extrabold text-ink">申请改期</div>
              <div className="mt-4 grid gap-3 md:grid-cols-2">
                <label className="grid gap-1 text-xs font-bold text-muted">
                  新开始时间
                  <input type="datetime-local" value={rescheduleForm.startsAt} onChange={(event) => setRescheduleForm((current) => ({ ...current, startsAt: event.target.value }))} className="h-10 rounded-[4px] border border-line bg-white px-3 text-sm outline-none focus:border-brand" />
                </label>
                <label className="grid gap-1 text-xs font-bold text-muted">
                  新结束时间
                  <input type="datetime-local" value={rescheduleForm.endsAt} onChange={(event) => setRescheduleForm((current) => ({ ...current, endsAt: event.target.value }))} className="h-10 rounded-[4px] border border-line bg-white px-3 text-sm outline-none focus:border-brand" />
                </label>
              </div>
              <input value={rescheduleForm.reason} onChange={(event) => setRescheduleForm((current) => ({ ...current, reason: event.target.value }))} placeholder="改期原因" className="mt-3 h-10 w-full rounded-[4px] border border-line bg-white px-3 text-sm outline-none focus:border-brand" />
              <button type="button" onClick={() => void requestReschedule()} className="mt-3 h-10 rounded-[4px] border border-line bg-white px-4 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">提交改期申请</button>
            </div>
          )}

          {isBookingUser && booking.status === 'pending_user_confirm' && (
            <div className="mt-6 rounded-[4px] border border-amber-200 bg-amber-50 p-4">
              <div className="text-sm font-extrabold text-amber-800">专家已提交完成</div>
              <p className="mt-2 text-sm font-bold leading-7 text-amber-800">请确认本次咨询是否完成。如服务结果存在问题，可填写原因发起争议。</p>
              <div className="mt-4 flex flex-wrap gap-2">
                <button type="button" onClick={() => void confirmCompletion()} className="h-10 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">确认完成</button>
                <input value={disputeReason} onChange={(event) => setDisputeReason(event.target.value)} placeholder="争议原因" className="h-10 min-w-[220px] flex-1 rounded-[4px] border border-line bg-white px-3 text-sm outline-none focus:border-brand" />
                <button type="button" onClick={() => void disputeCompletion()} className="h-10 rounded-[4px] border border-red-100 bg-white px-5 text-sm font-extrabold text-red-600">发起争议</button>
              </div>
            </div>
          )}
        </div>

        <aside className="grid gap-4">
          <div className="rounded-[4px] border border-line bg-white p-6">
            <div className="flex h-11 w-11 items-center justify-center rounded-[4px] bg-brand/10 text-brand">
              <CalendarClock className="h-5 w-5" />
            </div>
            <h2 className="mt-5 text-xl font-extrabold text-ink">预约时间</h2>
            <p className="mt-3 text-sm font-bold leading-7 text-muted">{formatDateTime(booking.startsAt)} 至 {formatDateTime(booking.endsAt)}</p>
            {booking.status === 'pending_payment' && (
              <Link href="/account/orders" className="mt-5 inline-flex h-10 w-full items-center justify-center rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white">查看订单并支付</Link>
            )}
          </div>

          <div className="rounded-[4px] border border-line bg-white p-6">
            <div className="flex h-11 w-11 items-center justify-center rounded-[4px] bg-brand/10 text-brand">
              <Video className="h-5 w-5" />
            </div>
            <h2 className="mt-5 text-xl font-extrabold text-ink">会议信息</h2>
            <div className="mt-3 grid gap-2 text-sm font-bold leading-6 text-muted">
              <div>方式：{booking.meetingMethod || booking.meetingPlatform || '待专家补充'}</div>
              {booking.meetingNo && <div>会议号：{booking.meetingNo}</div>}
              {booking.meetingPassword && <div>密码：{booking.meetingPassword}</div>}
              {booking.meetingNote && <div className="whitespace-pre-wrap">{booking.meetingNote}</div>}
              {booking.meetingUrl && <div className="break-all">链接：{booking.meetingUrl}</div>}
            </div>
            {showMeetingEntry ? (
              <button type="button" onClick={() => booking.meetingUrl ? window.open(booking.meetingUrl, '_blank') : undefined} className="mt-5 h-10 w-full rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">进入会议</button>
            ) : (
              <p className="mt-5 text-xs font-bold leading-5 text-muted">会议开始前 30 分钟会开放入会入口。</p>
            )}
          </div>
        </aside>
      </section>
    </div>
  )
}
