'use client'

import Link from 'next/link'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { useApp } from '@/components/providers/AppProvider'
import {
  backend,
  type BackendExpert,
  type BackendExpertApplication,
  type BackendExpertBooking,
  type BackendExpertSlot,
  type BackendExpertWallet,
  type BackendExpertWithdrawal,
  yuan,
  cents,
} from '@/lib/backend'

function formatDateTime(value?: string | null) {
  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 bookingStatusLabel(status: BackendExpertBooking['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'pending_expert') return '待确认'
  if (status === 'confirmed') return '已确认'
  if (status === 'rejected') return '已拒绝'
  if (status === 'cancelled') return '已取消'
  if (status === 'pending_user_confirm') return '待用户确认'
  if (status === 'disputed') return '争议中'
  return '已完成'
}

function applicationStatusLabel(status?: BackendExpertApplication['status']) {
  if (status === 'pending') return '待审核'
  if (status === 'approved') return '已通过'
  if (status === 'rejected') return '未通过'
  if (status === 'withdrawn') return '已撤回'
  return '未申请'
}

function withdrawalStatusLabel(status: BackendExpertWithdrawal['status']) {
  if (status === 'completed') return '已完成'
  if (status === 'rejected') return '已驳回'
  return '待处理'
}

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

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')}`
}

const scheduleHours = Array.from({ length: 9 }, (_, index) => 8 + index)

function startOfToday() {
  const date = new Date()
  date.setHours(0, 0, 0, 0)
  return date
}

function addDays(date: Date, days: number) {
  const next = new Date(date)
  next.setDate(next.getDate() + days)
  return next
}

function slotDate(day: Date, hour: number) {
  const date = new Date(day)
  date.setHours(hour, 0, 0, 0)
  return date
}

function localSlotKey(value?: string | Date) {
  const date = value instanceof Date ? value : value ? new Date(value) : null
  if (!date || 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')}:00`
}

function formatScheduleDay(value: Date) {
  return `${value.getMonth() + 1}/${value.getDate()}`
}

function weekday(value: Date) {
  return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][value.getDay()]
}

function slotStatusText(slot?: BackendExpertSlot) {
  if (!slot) return '未开放'
  if (slot.status === 'open') return '可约'
  if (slot.status === 'booked') return '已约'
  return '未开放'
}

function slotStatusClass(slot?: BackendExpertSlot) {
  if (slot?.status === 'open') return 'border-green bg-green/10 text-green'
  if (slot?.status === 'booked') return 'cursor-not-allowed border-brand bg-brand-light text-brand'
  return 'border-line bg-white text-soft hover:border-brand hover:text-brand'
}

export default function AccountExpertHomePage() {
  const { user, token } = useApp()
  const [application, setApplication] = useState<BackendExpertApplication | null>(null)
  const [profile, setProfile] = useState<BackendExpert | null>(null)
  const [bookings, setBookings] = useState<BackendExpertBooking[]>([])
  const [slots, setSlots] = useState<BackendExpertSlot[]>([])
  const [withdrawals, setWithdrawals] = useState<BackendExpertWithdrawal[]>([])
  const [wallet, setWallet] = useState<BackendExpertWallet | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [saved, setSaved] = useState('')
  const [withdrawOpen, setWithdrawOpen] = useState(false)
  const [withdrawDraft, setWithdrawDraft] = useState({ amount: '1000', payeeName: '', bankAccount: '', bankName: '' })
  const [meetingForms, setMeetingForms] = useState<Record<string, { method: string; platform: string; no: string; url: string; password: string; note: string }>>({})
  const [rescheduleForms, setRescheduleForms] = useState<Record<string, { startsAt: string; endsAt: string; reason: string }>>({})
  const today = useMemo(() => startOfToday(), [])
  const scheduleDays = useMemo(() => Array.from({ length: 7 }, (_, index) => addDays(today, index)), [today])
  const slotsByKey = useMemo(() => new Map(slots.map((slot) => [localSlotKey(slot.startsAt), slot])), [slots])

  const reload = useCallback(async () => {
    if (!token) return
    setLoading(true)
    try {
      const [nextApplication, nextProfile, nextBookings, nextWithdrawals, nextWallet] = await Promise.all([
        backend.accountExpertApplication(token),
        backend.accountExpertProfile(token),
        backend.accountExpertBookings(token),
        backend.accountExpertWithdrawals(token),
        backend.accountExpertWallet(token).catch(() => null),
      ])
      setApplication(nextApplication)
      setProfile(nextProfile)
      setBookings(nextBookings.items)
      setWithdrawals(nextWithdrawals.items)
      setWallet(nextWallet)
      if (nextProfile) {
        const nextSlots = await backend.accountExpertSlots(token, { from: today.toISOString(), to: addDays(today, 8).toISOString() }).catch(() => ({ items: [] }))
        setSlots(nextSlots.items)
      } else {
        setSlots([])
      }
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家工作台加载失败')
    } finally {
      setLoading(false)
    }
  }, [today, token])

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

  const expertBookings = useMemo(() => {
    if (!profile) return []
    return bookings.filter((booking) => booking.expertId === profile.id)
  }, [bookings, profile])

  const pendingBookings = expertBookings.filter((booking) => booking.status === 'pending_expert')
  const activeBookings = expertBookings.filter((booking) => ['pending_payment', 'pending_expert', 'confirmed', 'pending_user_confirm', 'disputed'].includes(booking.status))
  const completedBookings = expertBookings.filter((booking) => booking.status === 'completed')

  async function toggleAccepting() {
    if (!token || !profile) return
    try {
      const updated = await backend.setAccountExpertAccepting(token, !profile.acceptingOrders)
      setProfile(updated)
      setSaved(updated.acceptingOrders ? '已恢复接单' : '已停止接单')
    } catch (err) {
      setError(err instanceof Error ? err.message : '接单状态更新失败')
    }
  }

  function meetingDraft(booking: BackendExpertBooking) {
    return meetingForms[booking.id] || {
      method: booking.meetingMethod || 'online',
      platform: booking.meetingPlatform || '',
      no: booking.meetingNo || '',
      url: booking.meetingUrl || '',
      password: booking.meetingPassword || '',
      note: booking.meetingNote || '',
    }
  }

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

  function meetingPayload(booking: BackendExpertBooking) {
    const draft = meetingDraft(booking)
    return {
      meetingMethod: draft.method,
      meetingPlatform: draft.platform,
      meetingNo: draft.no,
      meetingUrl: draft.url,
      meetingPassword: draft.password,
      meetingNote: draft.note,
    }
  }

  async function updateBooking(booking: BackendExpertBooking, status: BackendExpertBooking['status'], payload: Record<string, unknown> = {}) {
    if (!token) return
    try {
      const updated = await backend.updateAccountExpertBooking(token, booking.id, {
        status,
        statusReason: status === 'rejected' ? '专家暂无法接单' : '',
        ...payload,
      })
      setBookings((items) => items.map((item) => (item.id === updated.id ? updated : item)))
      setSaved('预约状态已更新')
    } catch (err) {
      setError(err instanceof Error ? err.message : '预约状态更新失败')
    }
  }

  async function saveMeeting(booking: BackendExpertBooking) {
    await updateBooking(booking, booking.status, meetingPayload(booking))
  }

  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 toggleSlotHour(day: Date, hour: number) {
    if (!token) return
    const startsAt = slotDate(day, hour)
    const endsAt = slotDate(day, hour + 1)
    const current = slotsByKey.get(localSlotKey(startsAt))
    if (current?.status === 'booked') return
    try {
      const nextStatus = current?.status === 'open' ? 'closed' : 'open'
      const slot = await backend.saveAccountExpertSlot(token, { startsAt: startsAt.toISOString(), endsAt: endsAt.toISOString(), status: nextStatus })
      setSlots((items) => [slot, ...items.filter((item) => item.id !== slot.id)])
      setSaved(nextStatus === 'open' ? '已开放该时段' : '已关闭该时段')
    } catch (err) {
      setError(err instanceof Error ? err.message : '排期保存失败')
    }
  }

  async function submitWithdrawal() {
    if (!token) return
    const amount = cents(Number(withdrawDraft.amount || 0))
    if (!amount || !withdrawDraft.payeeName || !withdrawDraft.bankAccount || !withdrawDraft.bankName) {
      setError('请完整填写提现金额和收款信息')
      return
    }
    try {
      const created = await backend.createExpertWithdrawal(token, {
        amount,
        payeeName: withdrawDraft.payeeName,
        bankAccount: withdrawDraft.bankAccount,
        bankName: withdrawDraft.bankName,
      })
      setWithdrawals((items) => [created, ...items])
      setWithdrawOpen(false)
      setWithdrawDraft({ amount: '1000', payeeName: '', bankAccount: '', bankName: '' })
      setSaved('提现申请已提交')
    } catch (err) {
      setError(err instanceof Error ? err.message : '提现申请提交失败')
    }
  }

  if (!user) return <AccountAuthPrompt message="登录后可查看专家申请进度。" />

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

  if (!profile) {
    const isPending = application?.status === 'pending'
    const isApproved = application?.status === 'approved'
    const isRejected = application?.status === 'rejected'
    const title = isPending
      ? '专家申请审核中'
      : isApproved
        ? '专家申请已通过'
        : isRejected
          ? '专家申请未通过'
          : '当前没有专家申请'
    const description = isRejected
      ? `未通过原因：${application?.rejectReason || '请根据后台意见完善材料。'}`
      : isPending
        ? '平台运营审核完成后，通过时会自动生成专家档案并绑定你的通行证。'
        : isApproved
          ? '系统正在准备专家档案，档案生成后这里会显示专家工作台。'
          : '提交专家申请后，这里会显示审核流程。'

    return (
      <section className="rounded-[4px] border border-line bg-white p-8">
        <div className="text-sm font-extrabold text-brand">申请状态：{applicationStatusLabel(application?.status)}</div>
        <h1 className="mt-3 text-2xl font-extrabold text-ink">{title}</h1>
        <p className="mt-3 text-sm leading-7 text-muted">{description}</p>
        <div className="mt-5 text-sm font-bold text-muted">通行证编号：{user.passportNo || application?.passportNo || '待生成'}</div>
        <Link href="/experts/join" className="mt-6 inline-flex h-10 items-center rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">
          {isPending || isApproved ? '查看申请表' : isRejected ? '修改后重新提交' : '去申请'}
        </Link>
        {error && <div className="mt-4 rounded-[4px] bg-bg px-4 py-3 text-sm font-bold text-[#b45309]">{error}</div>}
      </section>
    )
  }

  return (
    <div className="space-y-6">
      {(saved || error) && (
        <div className={`rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || saved}
        </div>
      )}

      <section className="rounded-[4px] border border-line bg-white p-6">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-extrabold text-brand">专家工作台</div>
            <h1 className="mt-2 text-3xl font-extrabold text-ink">{profile.name}</h1>
            <p className="mt-2 text-sm leading-7 text-muted">{profile.title} · {profile.organization}</p>
            <div className="mt-4 flex flex-wrap gap-2">
              {(profile.directions?.length ? profile.directions : profile.specialties).map((item) => (
                <span key={item} className="rounded-[4px] bg-bg px-3 py-1.5 text-xs font-bold text-text-body">{item}</span>
              ))}
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href={`/experts/${profile.slug}`} className="h-10 rounded-[4px] border border-line bg-white px-4 py-2.5 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">查看主页</Link>
            <button onClick={() => void toggleAccepting()} className={`h-10 rounded-[4px] px-5 text-sm font-extrabold ${profile.acceptingOrders ? 'bg-brand text-white' : 'border border-line bg-white text-muted hover:border-brand hover:text-brand'}`}>
              {profile.acceptingOrders ? '停止接单' : '恢复接单'}
            </button>
          </div>
        </div>
      </section>

      <section className="grid gap-4 md:grid-cols-4">
        {[
          ['咨询价', `¥${yuan(profile.priceAmount).toLocaleString()}/小时`],
          ['专家分成', `${profile.shareRatio || 80}%`],
          ['已完成预约', `${completedBookings.length} 单`],
          ['可提现余额', `¥${yuan(wallet?.availableAmount || 0).toLocaleString()}`],
          ['提现中', `¥${yuan(wallet?.lockedAmount || 0).toLocaleString()}`],
          ['待结算', `¥${yuan(wallet?.pendingSettlementAmount || 0).toLocaleString()}`],
        ].map(([label, value]) => (
          <div key={label} className="rounded-[4px] border border-line bg-white p-5">
            <div className="text-sm font-extrabold text-muted">{label}</div>
            <div className="mt-2 text-2xl font-extrabold text-ink">{value}</div>
          </div>
        ))}
      </section>

      <section className="grid gap-6 lg:grid-cols-[1fr_360px]">
        <div className="rounded-[4px] border border-line bg-white p-6">
          <div className="flex items-center justify-between gap-4">
            <h2 className="text-lg font-extrabold text-ink">待确认预约</h2>
            <span className="text-sm font-bold text-muted">{pendingBookings.length} 条</span>
          </div>
          <div className="mt-4 divide-y divide-line">
            {pendingBookings.length === 0 ? (
              <div className="py-8 text-center text-sm font-bold text-muted">暂无待确认预约</div>
            ) : pendingBookings.map((booking) => (
              <div key={booking.id} className="grid gap-3 py-4 lg:grid-cols-[1fr_auto] lg:items-center">
                <div>
                  <div className="font-extrabold text-ink">{booking.contactName} · {booking.contactPhone}</div>
                  <div className="mt-1 text-sm font-bold text-muted">{formatDateTime(booking.startsAt)} · {booking.bookingNo}</div>
                  <div className="mt-2 line-clamp-2 text-sm leading-6 text-text-body">{booking.question || booking.background}</div>
                  {(booking.materialFiles || []).length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-2">
                      {(booking.materialFiles || []).map((file) => (
                        <a key={file.id} href={file.url} target="_blank" rel="noreferrer" className="rounded-[3px] bg-bg px-2 py-1 text-xs font-bold text-brand hover:underline">
                          {file.fileName}
                        </a>
                      ))}
                    </div>
                  )}
                  <div className="mt-3 grid gap-2 md:grid-cols-2">
                    <input value={meetingDraft(booking).platform} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), platform: event.target.value } }))} placeholder="会议平台，如飞书/腾讯/Zoom/线下" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                    <input value={meetingDraft(booking).no} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), no: event.target.value } }))} placeholder="会议号/房间号" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                    <input value={meetingDraft(booking).url} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), url: event.target.value } }))} placeholder="会议链接（可选）" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                    <input value={meetingDraft(booking).password} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), password: event.target.value } }))} placeholder="入会密码（可选）" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                  </div>
                  <textarea value={meetingDraft(booking).note} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), note: event.target.value } }))} rows={2} placeholder="会议说明，如请提前准备材料、线下地址等" className="mt-2 w-full rounded-[4px] border border-line p-3 text-xs outline-none focus:border-brand" />
                </div>
                <div className="flex gap-2">
                  <button onClick={() => void updateBooking(booking, 'confirmed', meetingPayload(booking))} className="h-9 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white">确认并发送会议</button>
                  <button onClick={() => void updateBooking(booking, 'rejected')} className="h-9 rounded-[4px] border border-line px-4 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">拒绝</button>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-[4px] border border-line bg-white p-6">
          <h2 className="text-lg font-extrabold text-ink">提现</h2>
          <div className="mt-4 rounded-[4px] bg-bg p-4 text-sm leading-7 text-muted">
            可提现余额以平台结算记录为准；提现申请会锁定对应结算记录，由管理员在后台处理。
          </div>
          <div className="mt-3 grid grid-cols-3 gap-2 text-center text-xs font-bold">
            <div className="rounded-[4px] bg-bg px-2 py-2 text-muted">可提现<br /><span className="text-brand">¥{yuan(wallet?.availableAmount || 0).toLocaleString()}</span></div>
            <div className="rounded-[4px] bg-bg px-2 py-2 text-muted">提现中<br /><span className="text-brand">¥{yuan(wallet?.lockedAmount || 0).toLocaleString()}</span></div>
            <div className="rounded-[4px] bg-bg px-2 py-2 text-muted">已提现<br /><span className="text-brand">¥{yuan(wallet?.withdrawnAmount || 0).toLocaleString()}</span></div>
          </div>
          <button onClick={() => setWithdrawOpen(true)} className="mt-5 h-10 w-full rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">申请提现</button>
        </div>
      </section>

      <section className="grid gap-6 lg:grid-cols-[0.95fr_1.05fr]">
        <div className="rounded-[4px] border border-line bg-white p-6">
          <h2 className="text-lg font-extrabold text-ink">未来 7 天排期</h2>
          <p className="mt-1 text-xs font-bold text-muted">勾选 8:00-17:00 的 1 小时时段；未勾选则用户端不可预约，已约时段不可关闭。</p>
          <div className="mt-4 overflow-x-auto">
            <div className="min-w-[760px]">
              <div className="grid grid-cols-[58px_repeat(7,minmax(88px,1fr))] gap-1">
                <div />
                {scheduleDays.map((day) => (
                  <div key={localSlotKey(day)} className="border border-line bg-bg px-2 py-2 text-center">
                    <div className="text-xs font-extrabold text-ink">{formatScheduleDay(day)}</div>
                    <div className="mt-0.5 text-[11px] font-bold text-soft">{weekday(day)}</div>
                  </div>
                ))}
                {scheduleHours.map((hour) => (
                  <div key={hour} className="contents">
                    <div className="grid h-8 place-items-center border border-line bg-bg text-[11px] font-extrabold text-muted">{hour}:00</div>
                    {scheduleDays.map((day) => {
                      const start = slotDate(day, hour)
                      const slot = slotsByKey.get(localSlotKey(start))
                      return (
                        <button
                          key={`${localSlotKey(day)}-${hour}`}
                          type="button"
                          disabled={slot?.status === 'booked'}
                          onClick={() => void toggleSlotHour(day, hour)}
                          className={`h-8 rounded-[4px] border px-1 text-[11px] font-extrabold ${slotStatusClass(slot)}`}
                        >
                          {slotStatusText(slot)}
                        </button>
                      )
                    })}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="rounded-[4px] border border-line bg-white p-6">
          <h2 className="text-lg font-extrabold text-ink">预约列表</h2>
          <div className="mt-5 max-h-[420px] overflow-y-auto border-t border-line">
            {activeBookings.length === 0 && completedBookings.length === 0 ? (
              <div className="py-8 text-center text-sm font-bold text-muted">暂无预约记录</div>
            ) : [...activeBookings, ...completedBookings].map((booking) => (
              <div key={booking.id} className="grid gap-3 border-b border-line py-4 last:border-b-0 lg:grid-cols-[1fr_auto] lg:items-center">
                <div>
                  <div className="font-extrabold text-ink">{booking.contactName} · {booking.bookingNo}</div>
                  <div className="mt-1 text-sm font-bold text-muted">{formatDateTime(booking.startsAt)} · {bookingStatusLabel(booking.status)}</div>
                  <div className="mt-2 line-clamp-2 text-sm leading-6 text-text-body">{booking.question || booking.background}</div>
                  {(booking.materialFiles || []).length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-2">
                      {(booking.materialFiles || []).map((file) => (
                        <a key={file.id} href={file.url} target="_blank" rel="noreferrer" className="rounded-[3px] bg-bg px-2 py-1 text-xs font-bold text-brand hover:underline">
                          {file.fileName}
                        </a>
                      ))}
                    </div>
                  )}
                  {booking.status === 'confirmed' && (
                    <div className="mt-3">
                      <div className="grid gap-2 md:grid-cols-2">
                        <input value={meetingDraft(booking).platform} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), platform: event.target.value } }))} placeholder="会议平台" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                        <input value={meetingDraft(booking).no} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), no: event.target.value } }))} placeholder="会议号/房间号" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                        <input value={meetingDraft(booking).url} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), url: event.target.value } }))} placeholder="会议链接" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                        <input value={meetingDraft(booking).password} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), password: event.target.value } }))} placeholder="入会密码" className="h-9 rounded-[4px] border border-line px-3 text-xs outline-none focus:border-brand" />
                      </div>
                      <textarea value={meetingDraft(booking).note} onChange={(event) => setMeetingForms((current) => ({ ...current, [booking.id]: { ...meetingDraft(booking), note: event.target.value } }))} rows={2} placeholder="会议说明" className="mt-2 w-full rounded-[4px] border border-line p-3 text-xs outline-none focus:border-brand" />
                    </div>
                  )}
                  {(booking.meetingPlatform || booking.meetingNo || booking.meetingUrl || booking.meetingNote) && (
                    <div className="mt-3 rounded-[4px] bg-bg p-3 text-xs font-bold leading-6 text-muted">
                      会议：{booking.meetingPlatform || '平台待补充'} {booking.meetingNo ? `· ${booking.meetingNo}` : ''}<br />
                      {booking.meetingUrl || '链接待补充'}{booking.meetingPassword ? ` · 密码 ${booking.meetingPassword}` : ''}<br />
                      {booking.meetingNote || ''}
                    </div>
                  )}
                  {booking.pendingChange && (
                    <div className="mt-3 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 !== 'expert' ? (
                        <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' && (
                    <div className="mt-3 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" />
                    </div>
                  )}
                </div>
                {booking.status === 'confirmed' && (
                  <div className="grid gap-2">
                    <button onClick={() => void saveMeeting(booking)} className="h-9 rounded-[4px] border border-line px-4 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">保存会议</button>
                    <button onClick={() => void requestReschedule(booking)} className="h-9 rounded-[4px] border border-line px-4 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">申请改期</button>
                    <button onClick={() => void updateBooking(booking, 'pending_user_confirm')} className="h-9 rounded-[4px] border border-line px-4 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">提交完成</button>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="rounded-[4px] border border-line bg-white p-6">
        <h2 className="text-lg font-extrabold text-ink">提现记录</h2>
        <div className="mt-4 divide-y divide-line">
          {withdrawals.length === 0 ? (
            <div className="py-8 text-center text-sm font-bold text-muted">暂无提现记录</div>
          ) : withdrawals.map((record) => (
            <div key={record.id} className="grid gap-2 py-3 text-sm md:grid-cols-[1fr_120px_120px] md:items-center">
              <div className="font-bold text-muted">{record.bankName} · {formatDateTime(record.createdAt)}</div>
              <div className="font-extrabold text-ink">¥{yuan(record.amount).toLocaleString()}</div>
              <div className="font-extrabold text-brand">{withdrawalStatusLabel(record.status)}</div>
            </div>
          ))}
        </div>
      </section>

      {withdrawOpen && (
        <div className="fixed inset-0 z-50 grid place-items-center bg-ink/36 px-6">
          <div className="w-full max-w-[520px] rounded-[4px] bg-white p-6 shadow-[0_24px_80px_rgba(15,23,42,0.22)]">
            <h2 className="text-2xl font-extrabold text-ink">申请提现</h2>
            <div className="mt-5 grid gap-4">
              <label className="grid gap-2">
                <span className="text-sm font-extrabold text-ink">提现金额（元）</span>
                <input value={withdrawDraft.amount} onChange={(event) => setWithdrawDraft((current) => ({ ...current, amount: event.target.value }))} type="number" min="1" className="h-10 rounded-[4px] border border-line px-3 text-sm font-extrabold text-ink outline-none focus:border-brand" />
              </label>
              <label className="grid gap-2">
                <span className="text-sm font-extrabold text-ink">收款人姓名</span>
                <input value={withdrawDraft.payeeName} onChange={(event) => setWithdrawDraft((current) => ({ ...current, payeeName: event.target.value }))} className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              </label>
              <label className="grid gap-2">
                <span className="text-sm font-extrabold text-ink">银行卡号</span>
                <input value={withdrawDraft.bankAccount} onChange={(event) => setWithdrawDraft((current) => ({ ...current, bankAccount: event.target.value }))} className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              </label>
              <label className="grid gap-2">
                <span className="text-sm font-extrabold text-ink">开户银行</span>
                <input value={withdrawDraft.bankName} onChange={(event) => setWithdrawDraft((current) => ({ ...current, bankName: event.target.value }))} placeholder="例如：招商银行大连分行" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              </label>
            </div>
            <div className="mt-6 flex justify-end gap-3">
              <button onClick={() => setWithdrawOpen(false)} className="h-10 rounded-[4px] border border-line bg-white px-5 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">取消</button>
              <button onClick={() => void submitWithdrawal()} className="h-10 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">提交申请</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
