import { useCallback, useMemo, useState } from 'react'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { Button, ConfigProvider, Empty, Loading, Popup } from '@nutui/nutui-react-taro'
import dayjs from 'dayjs'

import { getCreditMpCustomer } from '@/api/credit/creditMpCustomer'
import type { CreditMpCustomer } from '@/api/credit/creditMpCustomer/model'
import { getCreditCompany } from '@/api/credit/creditCompany'
import type { CreditCompany } from '@/api/credit/creditCompany/model'

type TimelineNode = {
  title: string
  status?: string
  time?: string
  desc?: string
  tag?: string
  actionText?: string
  actionType?: 'detail'
  variant?: 'normal' | 'returned'
}

const safeText = (v: any) => String(v ?? '').trim()

const formatDate = (t?: string) => {
  const txt = safeText(t)
  if (!txt) return ''
  const d = dayjs(txt)
  if (!d.isValid()) return txt
  return d.format('YY-MM-DD')
}

const getCompanyIndustry = (c?: CreditCompany | null) => {
  const anyCompany = (c || {}) as any
  return safeText(
    anyCompany.nationalStandardIndustryCategories6 ||
      anyCompany.nationalStandardIndustryCategories2 ||
      anyCompany.nationalStandardIndustryCategories ||
      anyCompany.institutionType ||
      ''
  )
}

const buildAddress = (c?: CreditCompany | null, fallback?: CreditMpCustomer | null) => {
  const cc = c || ({} as CreditCompany)
  const province = safeText((cc as any).province) || safeText(fallback?.province)
  const city = safeText((cc as any).city) || safeText(fallback?.city)
  const region = safeText((cc as any).region) || safeText(fallback?.region)
  const addr = safeText((cc as any).address)
  return safeText([province, city, region].filter(Boolean).join('') + addr) || safeText([province, city, region].filter(Boolean).join(' '))
}

export default function CreditMyOrderDetailPage() {
  const router = useRouter()
  const id = useMemo(() => {
    const n = Number((router?.params as any)?.id)
    return Number.isFinite(n) && n > 0 ? n : undefined
  }, [router?.params])

  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [tipVisible, setTipVisible] = useState(true)

  const [demand, setDemand] = useState<CreditMpCustomer | null>(null)
  const [company, setCompany] = useState<CreditCompany | null>(null)

  const reload = useCallback(async () => {
    setError(null)
    setLoading(true)
    try {
      if (!id) throw new Error('缺少需求ID')
      const d = await getCreditMpCustomer(id)
      setDemand(d as CreditMpCustomer)

      const companyId = Number((d as any)?.companyId)
      if (Number.isFinite(companyId) && companyId > 0) {
        try {
          const c = await getCreditCompany(companyId)
          setCompany(c as CreditCompany)
        } catch (_e) {
          setCompany(null)
        }
      } else {
        setCompany(null)
      }
    } catch (e) {
      console.error('加载需求详情失败:', e)
      setDemand(null)
      setCompany(null)
      setError(String((e as any)?.message || '加载失败'))
    } finally {
      setLoading(false)
    }
  }, [id])

  useDidShow(() => {
    reload().then()
  })

  const displayName = useMemo(() => {
    const c = company as any
    return safeText(c?.matchName || c?.name) || safeText(demand?.toUser) || '广西万宇工程建设有限公司'
  }, [company, demand?.toUser])

  const unifiedCode = useMemo(() => safeText((company as any)?.code) || '823339008887788', [company])
  const industry = useMemo(() => getCompanyIndustry(company) || '建筑业', [company])
  const phone = useMemo(() => safeText((company as any)?.tel) || '15878179339', [company])
  const address = useMemo(() => buildAddress(company, demand) || '广西南宁市西乡塘区北大中心10栋11号', [company, demand])

  const topFollower = useMemo(() => safeText((company as any)?.followRealName || (company as any)?.userRealName) || '罗天东', [company])
  const topDate = useMemo(() => {
    const t = safeText((company as any)?.assignDate || (company as any)?.assignTime || company?.updateTime || company?.createTime || demand?.createTime)
    return formatDate(t) || '25-11-10'
  }, [company, demand?.createTime])

  const topStatus = useMemo(() => safeText((company as any)?.customerStatus || (company as any)?.statusText) || '保护期内', [company])

  const timeline = useMemo<TimelineNode[]>(() => {
    const returned = safeText(demand?.statusTxt).includes('退回')
    const base: TimelineNode[] = [
      {
        title: '第一步：加微信前沟通',
        status: '审核通过',
        time: '2025-11-11',
        actionText: '查看详情',
        actionType: 'detail'
      },
      { title: '已受理', desc: `负责人：${topFollower || 'XXX'}`, time: '2025-01-01 11:30:30' },
      { title: '材料提交与梳理（第二步节点完成）', desc: '审核评估', time: '2025-01-01 11:30:30', tag: '第二步完成' },
      { title: '合同已签订（第五步节点完成）', desc: '项目启动', time: '2025-01-01 11:30:30', tag: '第五步完成' },
      {
        title: '执行回款（第六步节点完成）',
        desc: '部分回款：金额\n全部回款：金额',
        time: '2025-03-12 11:30:30',
        tag: '第六步完成'
      },
      { title: '完结', desc: '已办结/已终止', time: '2025-01-01 11:30:30' }
    ]

    if (returned) {
      base.splice(2, 0, {
        title: '已退回',
        variant: 'returned',
        desc: '原因：需求不清晰，请重新提交',
        time: '2025-01-01 11:30:30'
      })
    } else {
      base.push({
        title: '已退回',
        variant: 'returned',
        desc: '原因：需求不清晰，请重新提交',
        time: '2025-01-01 11:30:30'
      })
    }
    return base
  }, [demand?.statusTxt, topFollower])

  const onNodeAction = async (node: TimelineNode) => {
    if (node.actionType === 'detail') {
      Taro.showToast({ title: '查看详情（示例）', icon: 'none' })
    }
  }

  return (
    <View className="bg-pink-50 min-h-screen">
      <ConfigProvider>
        <View className="max-w-md mx-auto px-4 pb-12 pt-3">
          <View className="bg-white rounded-xl border border-pink-100 p-3">
            <View className="flex items-start justify-between gap-3">
              <View className="min-w-0">
                <Text className="text-base font-semibold text-gray-900">{displayName}</Text>
                <View className="mt-1 text-xs text-gray-500">统一代码：{unifiedCode}</View>
              </View>

              <View className="shrink-0 text-right">
                <View className="text-xs text-gray-700">{topFollower}</View>
                <View className="text-xs text-gray-500 mt-1">{topDate}</View>
                <View className="mt-1 inline-flex items-center gap-1 px-2 py-1 rounded-full bg-green-50 border border-green-200">
                  <View className="w-2 h-2 rounded-full bg-green-500" />
                  <Text className="text-xs text-green-700">{topStatus}</Text>
                </View>
              </View>
            </View>

            <View className="mt-3 grid grid-cols-1 gap-2 text-sm text-gray-700">
              <View className="flex items-center justify-between">
                <Text className="text-gray-500">所属行业</Text>
                <Text className="font-medium">{industry}</Text>
              </View>
              <View className="flex items-center justify-between">
                <Text className="text-gray-500">客户联系方式</Text>
                <Text className="font-medium">{phone}</Text>
              </View>
              <View className="flex items-start justify-between gap-3">
                <Text className="text-gray-500 shrink-0">地址</Text>
                <Text className="font-medium text-right">{address}</Text>
              </View>
            </View>
          </View>

          {loading ? (
            <View className="mt-3 bg-white rounded-xl border border-pink-100 py-10 flex justify-center">
              <Loading>加载中...</Loading>
            </View>
          ) : error ? (
            <View className="mt-3 bg-white rounded-xl border border-pink-100 py-10">
              <Empty description={error} />
              <View className="mt-2 flex justify-center">
                <Button size="small" type="primary" onClick={reload}>
                  重试
                </Button>
              </View>
            </View>
          ) : (
            <View className="mt-3 bg-white rounded-xl border border-pink-100 p-3">
              <View className="flex items-center justify-between">
                <Text className="text-sm font-semibold text-gray-900">我的需求进度</Text>
                <Text className="text-xs text-gray-400">时间线</Text>
              </View>

              <View className="mt-3">
                {timeline.map((n, idx) => {
                  const isLast = idx === timeline.length - 1
                  const isReturned = n.variant === 'returned'
                  const circleClass = isReturned ? 'bg-red-600' : 'bg-red-500'
                  const lineClass = isReturned ? 'bg-red-200' : 'bg-red-200'
                  const tag = safeText(n.tag)
                  const status = safeText(n.status)
                  const time = safeText(n.time)
                  const desc = safeText(n.desc)

                  return (
                    <View key={`${n.title}-${idx}`} className="flex items-stretch">
                      <View className="w-6 flex flex-col items-center">
                        <View className={`w-3 h-3 rounded-full mt-1 ${circleClass}`} />
                        {!isLast && <View className={`flex-1 w-[2px] ${lineClass}`} />}
                      </View>

                      <View className="flex-1 pb-4">
                        <View className="flex items-start justify-between gap-3">
                          <View className="min-w-0">
                            <Text className={`text-sm font-semibold ${isReturned ? 'text-red-600' : 'text-gray-900'}`}>
                              {n.title}
                            </Text>
                            {(status || time) && (
                              <View className="mt-1 text-xs text-gray-500 flex flex-wrap gap-x-3 gap-y-1">
                                {!!status && <Text>状态：{status}</Text>}
                                {!!time && <Text>时间：{time}</Text>}
                              </View>
                            )}
                          </View>

                          {!!tag && (
                            <View className="shrink-0 px-2 py-1 rounded-full bg-yellow-100 border border-yellow-200">
                              <Text className="text-xs text-yellow-800">{tag}</Text>
                            </View>
                          )}
                        </View>

                        {!!desc && (
                          <View className="mt-2 text-xs text-gray-700 whitespace-pre-line">
                            <Text>{desc}</Text>
                          </View>
                        )}

                        {!!n.actionText && (
                          <View className="mt-2">
                            <Button
                              size="small"
                              type="primary"
                              style={{ background: '#22c55e', borderColor: '#22c55e' }}
                              onClick={() => onNodeAction(n)}
                            >
                              {n.actionText}
                            </Button>
                          </View>
                        )}
                      </View>
                    </View>
                  )
                })}
              </View>
            </View>
          )}
        </View>

        <View
          className="fixed right-4 bottom-6 w-11 h-11 rounded-full bg-red-500 flex items-center justify-center shadow-lg"
          onClick={() => setTipVisible(true)}
        >
          <Text className="text-white text-lg font-semibold">?</Text>
        </View>

        <Popup
          visible={tipVisible}
          position="bottom"
          onClose={() => setTipVisible(false)}
          style={{ borderTopLeftRadius: '12px', borderTopRightRadius: '12px' }}
        >
          <View className="px-4 py-4 bg-white">
            <View className="flex items-center justify-between">
              <Text className="text-base font-semibold text-gray-900">进度查询</Text>
              <Text className="text-sm text-gray-500" onClick={() => setTipVisible(false)}>
                关闭
              </Text>
            </View>
            <View className="mt-3 text-sm text-gray-700 leading-6">
              <View>1. 查询进度：可查看自己发布的需求的处理状态、处理结果；</View>
              <View>2. 若可接单会安排给销售员，可跟踪项目每一步状态；若不可接，状态为退回。</View>
            </View>
          </View>
        </Popup>
      </ConfigProvider>
    </View>
  )
}

