'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { useApp } from '@/components/providers/AppProvider'
import { assetUrl, backend, type BackendExpertBooking } from '@/lib/backend'

function formatDateTime(value?: string) {
  if (!value) return '时间待确认'
  const date = new Date(value)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${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-amber-50 text-amber-700'
  if (status === 'pending_expert') return 'bg-bg text-muted'
  return 'bg-bg text-soft'
}

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

export default function AccountExpertBookingsPage() {
  const { user, token } = useApp()
  const [bookings, setBookings] = useState<BackendExpertBooking[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [saved, setSaved] = useState('')
  const [rescheduleForms, setRescheduleForms] = useState<Record<string, { startsAt: string; endsAt: string; reason: string }>>({})
  const [disputeReasons, setDisputeReasons] = useState<Record<string, string>>({})

  async function reload() {
    if (!token) return
    setLoading(true)
    await backend.accountExpertBookings(token)
      .then((result) => {
        setBookings(result.items)
        setError('')
      })
      .catch((err) => setError(err instanceof Error ? err.message : '专家预约加载失败'))
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    void reload()
  }, [token])

  const userBookings = useMemo(() => {
    if (!user?.id) return bookings
    return bookings.filter((booking) => booking.userId === user.id)
  }, [bookings, user?.id])

  if (!user) return <AccountAuthPrompt message="登录后可查看专家预约和咨询进度。" />

  function rescheduleDraft(booking: BackendExpertBooking) {
    return rescheduleForms[booking.id] || {
      startsAt: localInputFromIso(booking.startsAt),
      endsAt: localInputFromIso(booking.endsAt),
      reason: '',
    }
  }

  async function requestReschedule(booking: BackendExpertBooking) {
    if (!token) return
    const draft = rescheduleDraft(booking)
    const startsAt = isoFromLocal(draft.startsAt)
    const endsAt = isoFromLocal(draft.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: draft.reason || '用户申请改期' })
      setBookings((items) => items.map((item) => (item.id === updated.id ? updated : item)))
      setSaved('改期申请已提交，等待专家确认')
    } catch (err) {
      setError(err instanceof Error ? err.message : '改期申请失败')
    }
  }

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

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

  async function disputeCompletion(booking: BackendExpertBooking) {
    if (!token) return
    const reason = (disputeReasons[booking.id] || '').trim()
    if (!reason) {
      setError('请填写争议原因')
      return
    }
    try {
      const updated = await backend.disputeAccountExpertBookingCompletion(token, booking.id, reason)
      setBookings((items) => items.map((item) => (item.id === updated.id ? updated : item)))
      setSaved('已提交争议')
    } 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>
  }

  return (
    <div>
      {error && <div className="mb-4 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
      {saved && !error && <div className="mb-4 rounded-[4px] bg-green-50 px-4 py-3 text-sm font-bold text-green">{saved}</div>}
      {userBookings.length === 0 ? (
        <AccountEmptyState title="暂无专家预约" description="预约专家后，确认时间、咨询背景和后续记录会在这里展示。" />
      ) : (
        <section className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {userBookings.map((booking) => {
            const expert = booking.expert
            const showMeetingEntry = meetingIsOpen(booking.status, booking.startsAt)

            return (
              <article
                key={booking.id}
                className="group block overflow-hidden rounded-[4px] border border-line bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)] transition hover:border-brand/30 hover:bg-[#f8fbff]"
              >
                <div className="p-4">
                  <div className="grid grid-cols-[104px_1fr] gap-4">
                    {expert.photoUrl ? (
                      <img src={assetUrl(expert.photoUrl)} alt={`${expert.name}专家照片`} className="aspect-[3/4] rounded-[4px] object-cover" />
                    ) : (
                      <div
                        className="flex aspect-[3/4] items-center justify-center rounded-[4px] border border-dashed border-[#9db6d3] bg-[#edf4fb] text-center text-xs font-extrabold leading-5 text-[#55749c]"
                        aria-label={`${expert.name}专家照片`}
                      >
                        {expert.name}专家照片
                      </div>
                    )}
                    <div className="min-w-0 pt-1">
                      <div className="text-2xl font-extrabold leading-8 text-brand">{expert.name}专家</div>
                      <div className="mt-3 text-sm font-bold leading-6 text-muted">{expert.title}</div>
                      <div className="mt-1 text-sm font-bold leading-6 text-muted">{expert.organization}</div>
                    </div>
                  </div>
                  <div className="mt-4 border-t border-line pt-3 text-sm font-extrabold text-ink">
                    {formatDateTime(booking.startsAt)}
                  </div>
                  <div className="mt-2 line-clamp-2 text-sm leading-6 text-muted">{booking.question || booking.background || '未填写咨询问题'}</div>
                  <Link href={`/account/expert-bookings/${booking.id}`} className="mt-4 inline-flex h-9 items-center rounded-[4px] border border-line px-4 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
                    查看详情
                  </Link>
                  {(booking.meetingPlatform || booking.meetingNo || booking.meetingUrl || booking.meetingNote) && (
                    <div className="mt-4 rounded-[4px] bg-bg p-3 text-xs font-bold leading-6 text-muted">
                      <div className="font-extrabold text-ink">会议信息</div>
                      <div className="mt-1">平台：{booking.meetingPlatform || '待补充'}{booking.meetingNo ? ` · 会议号 ${booking.meetingNo}` : ''}</div>
                      {booking.meetingUrl && <div className="break-all">链接：{booking.meetingUrl}</div>}
                      {booking.meetingPassword && <div>密码：{booking.meetingPassword}</div>}
                      {booking.meetingNote && <div>{booking.meetingNote}</div>}
                    </div>
                  )}
                  {booking.pendingChange && (
                    <div className="mt-4 rounded-[4px] border border-amber-200 bg-amber-50 p-3 text-xs font-bold leading-6 text-amber-800">
                      改期申请：{formatDateTime(booking.pendingChange.requestedStartsAt)} · {booking.pendingChange.reason || '未填写原因'}
                      {booking.pendingChange.requesterType !== 'user' ? (
                        <div className="mt-2 flex gap-2">
                          <button onClick={() => void respondReschedule(booking, 'accepted')} className="h-8 rounded-[4px] bg-brand px-3 text-xs font-extrabold text-white">同意改期</button>
                          <button onClick={() => void respondReschedule(booking, 'rejected')} className="h-8 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted">拒绝</button>
                        </div>
                      ) : <div className="mt-1 text-amber-700">等待专家确认</div>}
                    </div>
                  )}
                  {booking.status === 'confirmed' && !booking.pendingChange && (
                    <div className="mt-4 grid gap-2">
                      <div className="rounded-[4px] bg-bg px-3 py-2 text-xs font-bold leading-6 text-muted">
                        原预约时间：{formatDateTime(booking.startsAt)} - {formatDateTime(booking.endsAt).replace(/^\d+月\d+日 /, '')}
                      </div>
                      <div className="grid gap-2 md:grid-cols-2">
                        <label className="grid gap-1 text-xs font-bold text-muted">
                          新开始时间
                          <input type="datetime-local" value={rescheduleDraft(booking).startsAt} onChange={(event) => setRescheduleForms((current) => ({ ...current, [booking.id]: { ...rescheduleDraft(booking), startsAt: event.target.value } }))} className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                        </label>
                        <label className="grid gap-1 text-xs font-bold text-muted">
                          新结束时间
                          <input type="datetime-local" value={rescheduleDraft(booking).endsAt} onChange={(event) => setRescheduleForms((current) => ({ ...current, [booking.id]: { ...rescheduleDraft(booking), endsAt: event.target.value } }))} className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                        </label>
                      </div>
                      <input value={rescheduleDraft(booking).reason} onChange={(event) => setRescheduleForms((current) => ({ ...current, [booking.id]: { ...rescheduleDraft(booking), reason: event.target.value } }))} placeholder="改期原因" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                      <button type="button" onClick={() => void requestReschedule(booking)} className="h-9 rounded-[4px] border border-line text-xs font-extrabold text-muted hover:border-brand hover:text-brand">申请改期</button>
                    </div>
                  )}
                  {booking.status === 'pending_user_confirm' && (
                    <div className="mt-4 rounded-[4px] border border-amber-200 bg-amber-50 p-3">
                      <div className="text-xs font-bold leading-6 text-amber-800">专家已提交完成，请确认服务结果。如有问题可填写原因发起争议。</div>
                      <div className="mt-3 flex flex-wrap gap-2">
                        <button type="button" onClick={() => void confirmCompletion(booking)} className="h-9 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white">确认完成</button>
                        <input value={disputeReasons[booking.id] || ''} onChange={(event) => setDisputeReasons((current) => ({ ...current, [booking.id]: event.target.value }))} placeholder="争议原因" className="h-9 min-w-[180px] flex-1 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                        <button type="button" onClick={() => void disputeCompletion(booking)} className="h-9 rounded-[4px] border border-red-100 bg-white px-4 text-xs font-extrabold text-red-600">发起争议</button>
                      </div>
                    </div>
                  )}
                </div>
                <div className={`border-t border-line px-4 py-3 text-center text-sm font-extrabold ${showMeetingEntry ? 'bg-amber-50 text-amber-800' : statusTone(booking.status)}`}>
                  {showMeetingEntry ? (
                    <div className="flex flex-col items-center gap-2">
                      <div>会议即将开始，请进入会议</div>
                      <button type="button" onClick={() => booking.meetingUrl ? window.open(booking.meetingUrl, '_blank') : undefined} className="h-9 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark">
                        进入会议
                      </button>
                    </div>
                  ) : (
                    statusText(booking.status)
                  )}
                </div>
              </article>
            )
          })}
        </section>
      )}
    </div>
  )
}
