import { Input, Picker, Text, Textarea, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendExpertBooking } from '@/api/backend'
import { MetaRow, Page } from '@/components/ui'
import { ensureLoggedIn, getToken, getUser } from '@/stores/storage'
import { toast } from '@/utils/nav'

function statusLabel(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 '已拒绝'
  if (status === 'cancelled') return '已取消'
  return '处理中'
}

function formatTime(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')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function localValue(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')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function datePart(value: string) {
  return value.split(' ')[0] || ''
}

function timePart(value: string) {
  return value.split(' ')[1] || '09:00'
}

function withDate(value: string, nextDate: string) {
  return `${nextDate} ${timePart(value)}`
}

function withTime(value: string, nextTime: string) {
  return `${datePart(value)} ${nextTime}`
}

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

export default function ExpertBookingDetailPage() {
  const [booking, setBooking] = useState<BackendExpertBooking | null>(null)
  const [loading, setLoading] = useState(true)
  const [rescheduleForm, setRescheduleForm] = useState({ startsAt: '', endsAt: '', reason: '' })
  const [disputeReason, setDisputeReason] = useState('')

  useLoad((query) => {
    const id = String(query.id || '')
    const user = ensureLoggedIn(`/pages/account/expert-bookings/detail/index?id=${encodeURIComponent(id)}`)
    const token = getToken()
    if (!user || !token || !id) return
    setLoading(true)
    backend.accountExpertBooking(token, id)
      .then((item) => {
        setBooking(item)
        setRescheduleForm({
          startsAt: localValue(item.startsAt),
          endsAt: localValue(item.endsAt),
          reason: ''
        })
      })
      .catch((error) => toast(error instanceof Error ? error.message : '专家预约详情加载失败'))
      .finally(() => setLoading(false))
  })

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

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

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

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

  function copy(value?: string, message = '链接已复制') {
    if (!value) {
      toast('暂未提供链接')
      return
    }
    void Taro.setClipboardData({ data: value })
    toast(message)
  }

  if (loading) {
    return (
      <Page title="预约详情">
        <View className="flow-section"><Text className="row-sub">正在同步预约详情...</Text></View>
      </Page>
    )
  }

  if (!booking) {
    return (
      <Page title="预约详情">
        <View className="flow-section"><Text className="row-sub">预约不存在或无权访问。</Text></View>
      </Page>
    )
  }

  const user = getUser()
  const isBookingUser = booking.userId === user?.id
  const canRespondChange = Boolean(booking.pendingChange) && isBookingUser && booking.pendingChange?.requesterType !== 'user'

  return (
    <Page title="预约详情" subtle={`${booking.bookingNo} · ${statusLabel(booking.status)}`}>
      <View className="booking-detail-hero">
        <Text className="status-pill">{statusLabel(booking.status)}</Text>
        <Text className="booking-detail-title">{booking.expert.name} 专家咨询</Text>
        <Text className="booking-detail-sub">{booking.expert.title || '专家咨询'} · {booking.expert.organization || '大连市大数据研究院'}</Text>
      </View>

      <View className="flow-section">
        <MetaRow label="预约时间" value={`${formatTime(booking.startsAt)} 至 ${formatTime(booking.endsAt)}`} />
        <MetaRow label="联系人" value={booking.contactName || booking.user.displayName || '-'} />
        <MetaRow label="联系电话" value={booking.contactPhone || booking.user.phone || '-'} />
        <MetaRow label="当前状态" value={statusLabel(booking.status)} />
      </View>

      <View className="flow-section">
        <Text className="flow-section-title">咨询资料</Text>
        <View className="staff-text-block">
          <Text className="staff-text-label">咨询问题</Text>
          <Text className="staff-text-value">{booking.question || '未填写咨询问题'}</Text>
        </View>
        <View className="staff-text-block">
          <Text className="staff-text-label">背景资料</Text>
          <Text className="staff-text-value">{booking.background || '暂未补充背景资料'}</Text>
        </View>
        {(booking.materialFiles || []).length > 0 && (
          <View className="file-list">
            {(booking.materialFiles || []).map((file) => (
              <View key={file.id} className="file-line" onClick={() => copy(file.url, '资料链接已复制')}>
                <Text>{file.fileName || file.id}</Text>
                <Text className="arrow">复制</Text>
              </View>
            ))}
          </View>
        )}
      </View>

      <View className="flow-section">
        <Text className="flow-section-title">会议信息</Text>
        <MetaRow label="会议方式" value={booking.meetingMethod || booking.meetingPlatform || '待专家补充'} />
        <MetaRow label="会议号" value={booking.meetingNo || '-'} />
        <MetaRow label="会议密码" value={booking.meetingPassword || '-'} />
        <View className="staff-text-block">
          <Text className="staff-text-label">会议备注</Text>
          <Text className="staff-text-value">{booking.meetingNote || '专家确认后会补充会议资料。'}</Text>
        </View>
        {booking.meetingUrl ? <View className="ghost-btn" onClick={() => copy(booking.meetingUrl, '会议链接已复制')}>复制会议链接</View> : null}
      </View>

      {booking.pendingChange && (
        <View className="flow-section soft-warn">
          <Text className="flow-section-title">改期申请</Text>
          <Text className="row-sub">{formatTime(booking.pendingChange.requestedStartsAt)} 至 {formatTime(booking.pendingChange.requestedEndsAt)}</Text>
          <Text className="row-sub">{booking.pendingChange.reason || '未填写原因'}</Text>
          {canRespondChange ? (
            <View className="inline-actions">
              <View className="primary-btn compact" onClick={() => respondReschedule('accepted')}>同意改期</View>
              <View className="ghost-btn compact" onClick={() => respondReschedule('rejected')}>拒绝</View>
            </View>
          ) : <Text className="row-sub">等待对方确认</Text>}
        </View>
      )}

      {isBookingUser && booking.status === 'confirmed' && !booking.pendingChange && (
        <View className="flow-section">
          <Text className="flow-section-title">申请改期</Text>
          <View className="meta-grid compact">
            <Picker mode="date" value={datePart(rescheduleForm.startsAt)} onChange={(event) => setRescheduleForm((current) => ({ ...current, startsAt: withDate(current.startsAt, String(event.detail.value)) }))}>
              <View><Text className="meta-label">新开始日期</Text><Text className="meta-value">{datePart(rescheduleForm.startsAt)}</Text></View>
            </Picker>
            <Picker mode="time" value={timePart(rescheduleForm.startsAt)} onChange={(event) => setRescheduleForm((current) => ({ ...current, startsAt: withTime(current.startsAt, String(event.detail.value)) }))}>
              <View><Text className="meta-label">新开始时间</Text><Text className="meta-value">{timePart(rescheduleForm.startsAt)}</Text></View>
            </Picker>
            <Picker mode="date" value={datePart(rescheduleForm.endsAt)} onChange={(event) => setRescheduleForm((current) => ({ ...current, endsAt: withDate(current.endsAt, String(event.detail.value)) }))}>
              <View><Text className="meta-label">新结束日期</Text><Text className="meta-value">{datePart(rescheduleForm.endsAt)}</Text></View>
            </Picker>
            <Picker mode="time" value={timePart(rescheduleForm.endsAt)} onChange={(event) => setRescheduleForm((current) => ({ ...current, endsAt: withTime(current.endsAt, String(event.detail.value)) }))}>
              <View><Text className="meta-label">新结束时间</Text><Text className="meta-value">{timePart(rescheduleForm.endsAt)}</Text></View>
            </Picker>
          </View>
          <Input className="flow-input" value={rescheduleForm.reason} placeholder="改期原因" onInput={(event) => setRescheduleForm((current) => ({ ...current, reason: String(event.detail.value) }))} />
          <View className="ghost-btn" onClick={requestReschedule}>提交改期申请</View>
        </View>
      )}

      {isBookingUser && booking.status === 'pending_user_confirm' && (
        <View className="flow-section soft-warn">
          <Text className="flow-section-title">专家已提交完成</Text>
          <Text className="row-sub">请确认本次咨询是否完成。如服务结果存在问题，可填写原因发起争议。</Text>
          <View className="primary-btn" onClick={confirmCompletion}>确认完成</View>
          <Textarea className="flow-textarea" value={disputeReason} placeholder="争议原因" onInput={(event) => setDisputeReason(String(event.detail.value))} />
          <View className="ghost-btn danger-text" onClick={disputeCompletion}>发起争议</View>
        </View>
      )}

      <View className="detail-spacer" />
      {booking.status === 'pending_payment' && (
        <View className="bottom-bar">
          <View className="primary-btn" onClick={() => Taro.navigateTo({ url: `/pages/checkout/index?expertBookingId=${encodeURIComponent(booking.id)}` })}>去支付</View>
        </View>
      )}
    </Page>
  )
}
