import { Image, Input, ScrollView, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useRef, useState, type CSSProperties, type ReactNode } from 'react'
import { tapLight } from '@/utils/feedback'
import serviceAgentImage from '@/assets/service-modules/agent.png'
import serviceConsultingImage from '@/assets/service-modules/consulting.png'
import serviceCourseImage from '@/assets/service-modules/course.png'
import serviceDataImage from '@/assets/service-modules/data.png'
import serviceEventImage from '@/assets/service-modules/event.png'
import serviceExpertImage from '@/assets/service-modules/expert.png'
import cartIconImage from '@/assets/icons/remix-shopping-cart-2-line.svg'
import './ui.css'

type DrawerTouchEvent = {
  touches?: Array<{ clientY: number }>
  changedTouches?: Array<{ clientY: number }>
  stopPropagation?: () => void
}

export function Page({ children, title, subtle }: { children?: ReactNode; title?: string; subtle?: string }) {
  return (
    <View className="page">
      {title && (
        <View className="page-head">
          <Text className="page-title">{title}</Text>
          {subtle && <Text className="page-subtle">{subtle}</Text>}
        </View>
      )}
      {children}
    </View>
  )
}

export function AppTopBar({ title, right }: { title: string; right?: ReactNode }) {
  return (
    <View className="app-topbar">
      <Text className="app-back">‹</Text>
      <Text className="app-title">{title}</Text>
      <View className="app-right">{right}</View>
    </View>
  )
}

export function Section({ title, children, action }: { title: string; children: ReactNode; action?: ReactNode }) {
  return (
    <View className="section">
      <View className="section-head">
        <Text className="section-title">{title}</Text>
        {action}
      </View>
      {children}
    </View>
  )
}

function searchInputPlaceholder(text: string) {
  const target = text.replace(/^搜索/, '').trim()
  if (!target || target.length > 10 || target.includes('、')) return '请输入关键词'
  return `请输入${target}关键词`
}

export function SearchPill({ text = '搜索课程、活动、数据服务、专家', url = '/pages/search/index', placeholder }: { text?: string; url?: string; placeholder?: string }) {
  function openSearch() {
    tapLight()
    const separator = url.includes('?') ? '&' : '?'
    Taro.navigateTo({ url: `${url}${separator}placeholder=${encodeURIComponent(placeholder || searchInputPlaceholder(text))}` })
  }

  return (
    <View className="search-pill" onClick={openSearch}>
      <Text className="search-pill-text">{text}</Text>
    </View>
  )
}

export function CartDot() {
  return (
    <View className="cart-dot">
      <View className="cart-icon-plate">
        <Image className="cart-icon" src={cartIconImage} mode="aspectFit" />
      </View>
    </View>
  )
}

export function EmptyState({ title, text, action, compact = false }: { title: string; text?: string; action?: ReactNode; compact?: boolean }) {
  return (
    <View className={compact ? 'empty compact' : 'empty'}>
      <Text className="empty-title">{title}</Text>
      {text && <Text className="empty-text">{text}</Text>}
      {action && <View className="empty-action">{action}</View>}
    </View>
  )
}

export function StatusSide({ value, orange }: { value: string; orange?: boolean }) {
  return <View className={orange ? 'status-side orange' : 'status-side'}><Text>{value}</Text></View>
}

const visualLabels: Record<string, string> = {
  platform: '平台',
  services: '服务',
  course: '课程',
  event: '活动',
  data: '数据',
  agent: '智能体',
  expert: '专家',
  consulting: '咨询',
  membership: '会员'
}

const serviceGlyphs: Record<string, string> = {
  consulting: serviceConsultingImage,
  expert: serviceExpertImage,
  course: serviceCourseImage,
  event: serviceEventImage,
  data: serviceDataImage,
  agent: serviceAgentImage
}

export function ServiceGlyph({ type }: { type: string }) {
  const glyphType = serviceGlyphs[type] ? type : 'consulting'
  return <Image className={`service-glyph service-glyph-${glyphType}`} src={serviceGlyphs[glyphType]} mode="aspectFit" />
}

export function ProductImage({ src, className = 'product-image', label, style }: { src?: string; className?: string; label?: string; style?: CSSProperties }) {
  if (src && /^(https?:|data:|blob:)/.test(src)) {
    return <Image className={`${className} real-product-image`} src={src} mode="aspectFill" style={style} />
  }
  const key = src && visualLabels[src] ? src : 'platform'
  return (
    <View className={`${className} visual-card visual-${key}`} style={style}>
      <View className="visual-mark" />
      <Text className="visual-label">{label || visualLabels[key] || '服务'}</Text>
    </View>
  )
}

export function Field({ label, value, onInput, placeholder }: { label: string; value: string; onInput: (value: string) => void; placeholder?: string }) {
  return (
    <View className="field">
      <Text className="field-label">{label}</Text>
      <Input className="field-input" value={value} placeholder={placeholder || label} onInput={(event) => onInput(String(event.detail.value))} />
    </View>
  )
}

export function MetaRow({ label, value }: { label: string; value?: string | number }) {
  return (
    <View className="meta-row">
      <Text className="meta-row-label">{label}</Text>
      <Text className="meta-row-value">{value || '-'}</Text>
    </View>
  )
}

export function BottomDrawer({ title, children, footer, onClose, className = '' }: { title: string; children: ReactNode; footer?: ReactNode; onClose: () => void; className?: string }) {
  const [dragY, setDragY] = useState(0)
  const [expanded, setExpanded] = useState(false)
  const [isDragging, setIsDragging] = useState(false)
  const startY = useRef(0)
  const dragging = useRef(false)

  function touchY(event: DrawerTouchEvent) {
    return event.touches?.[0]?.clientY ?? event.changedTouches?.[0]?.clientY ?? 0
  }

  function startDrag(event: DrawerTouchEvent) {
    event.stopPropagation?.()
    dragging.current = true
    setIsDragging(true)
    startY.current = touchY(event)
  }

  function moveDrag(event: DrawerTouchEvent) {
    if (!dragging.current) return
    event.stopPropagation?.()
    const delta = touchY(event) - startY.current
    setDragY(delta > 0 ? Math.min(delta, 280) : 0)
  }

  function endDrag(event: DrawerTouchEvent) {
    if (!dragging.current) return
    event.stopPropagation?.()
    dragging.current = false
    setIsDragging(false)
    const delta = touchY(event) - startY.current
    setDragY(0)
    if (expanded && delta > 64) {
      setExpanded(false)
      return
    }
    if (!expanded && delta > 118) {
      onClose()
      return
    }
    if (delta < -52) {
      setExpanded(true)
    }
  }

  const style: CSSProperties | undefined = dragY ? { transform: `translate3d(0, ${dragY}px, 0)` } : undefined

  return (
    <View className="drawer-mask" catchMove onClick={onClose}>
      <View className={`bottom-drawer ${expanded ? 'expanded' : ''} ${isDragging ? 'dragging' : ''} ${className}`} style={style} catchMove onClick={(event) => event.stopPropagation()}>
        <View className="drawer-drag-zone" onTouchStart={startDrag} onTouchMove={moveDrag} onTouchEnd={endDrag} onTouchCancel={endDrag}>
          <View className="drawer-handle" />
          <View className="drawer-head">
            <Text className="drawer-title">{title}</Text>
          </View>
        </View>
        {children}
        {footer && <View className="drawer-footer">{footer}</View>}
      </View>
    </View>
  )
}

export function ConfirmDrawer({ title, content, confirmText = '确认', cancelText = '取消', onCancel, onConfirm }: { title: string; content: string; confirmText?: string; cancelText?: string; onCancel: () => void; onConfirm: () => void }) {
  return (
    <BottomDrawer
      title={title}
      onClose={onCancel}
      className="confirm-drawer"
      footer={(
        <View className="btn-row">
          <View className="ghost-btn" onClick={onCancel}>{cancelText}</View>
          <View className="primary-btn" onClick={onConfirm}>{confirmText}</View>
        </View>
      )}
    >
      <Text className="confirm-drawer-content">{content}</Text>
    </BottomDrawer>
  )
}

export function AgreementModal({ title, onClose }: { title: string; onClose: () => void }) {
  return (
    <BottomDrawer
      title={title}
      onClose={onClose}
      className="agreement-drawer"
    >
      <ScrollView scrollY className="agreement-scroll">
        <Text className="agreement-text">
          本条款用于说明线上购买、订单生成、服务开通、资料提交、下载使用与售后联系等事项。用户提交购买前应确认商品类型、价格、联系方式和发票信息。购买成功后，系统会按商品拆分生成独立订单，并在个人中心对应入口形成履约记录。数据服务、课程、活动、智能体、专家预约和规划咨询按照各自页面展示的规则提供服务。
        </Text>
        <Text className="agreement-text">
          如因用户提交信息不完整影响服务推进，平台可通过联系电话或站内记录提示补充。正式版本中，条款内容应由平台运营维护版本号，并记录用户确认时间。
        </Text>
      </ScrollView>
    </BottomDrawer>
  )
}
