import { useCallback, useMemo, useState } from 'react'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { Cell, CellGroup, ConfigProvider, Popup, Tag, TextArea } from '@nutui/nutui-react-taro'

import { getCreditCompany } from '@/api/credit/creditCompany'
import type { CreditCompany } from '@/api/credit/creditCompany/model'
import { listUsers } from '@/api/system/user'
import type { User } from '@/api/system/user/model'
import FixedButton from '@/components/FixedButton'

type CustomerStatus = '保护期内' | '已签约' | '已完成' | '保护期外'

const STATUS_OPTIONS: CustomerStatus[] = ['保护期内', '已签约', '已完成', '保护期外']
const PENDING_EDIT_STORAGE_KEY = 'credit_company_pending_edit_map'

const safeParseJSON = <T,>(v: any): T | null => {
  try {
    if (!v) return null
    if (typeof v === 'object') return v as T
    if (typeof v === 'string') return JSON.parse(v) as T
    return null
  } catch (_e) {
    return null
  }
}

const splitPhones = (raw?: string) => {
  const text = String(raw || '').trim()
  if (!text) return []
  return text
    .split(/[\s,，;；、\n\r]+/g)
    .map(s => s.trim())
    .filter(Boolean)
}

const getCompanyPhones = (c?: CreditCompany | null) => {
  if (!c) return []
  const arr = [...splitPhones(c.tel), ...splitPhones(c.moreTel)]
  return Array.from(new Set(arr))
}

const getCompanyIndustry = (c?: CreditCompany | null) => {
  if (!c) return ''
  return String(
    c.nationalStandardIndustryCategories6 ||
      c.nationalStandardIndustryCategories2 ||
      c.nationalStandardIndustryCategories ||
      c.institutionType ||
      ''
  ).trim()
}

type PendingEdit = {
  status: CustomerStatus
  remark: string
  submittedAt: string
}

const loadPendingMap = (): Record<string, PendingEdit> => {
  try {
    const raw = Taro.getStorageSync(PENDING_EDIT_STORAGE_KEY)
    return safeParseJSON<Record<string, PendingEdit>>(raw) || {}
  } catch (_e) {
    return {}
  }
}

const savePendingMap = (map: Record<string, PendingEdit>) => {
  try {
    Taro.setStorageSync(PENDING_EDIT_STORAGE_KEY, map)
  } catch (_e) {
    // ignore
  }
}

export default function CreditCompanyEditPage() {
  const router = useRouter()
  const companyId = Number(router?.params?.id)

  const statusBarHeight = useMemo(() => {
    try {
      const info = Taro.getSystemInfoSync()
      return Number(info?.statusBarHeight || 0)
    } catch (_e) {
      return 0
    }
  }, [])

  const [loading, setLoading] = useState(false)
  const [company, setCompany] = useState<CreditCompany | null>(null)
  const [staffList, setStaffList] = useState<User[]>([])
  const [statusPickerVisible, setStatusPickerVisible] = useState(false)

  const [customerStatus, setCustomerStatus] = useState<CustomerStatus>('保护期内')
  const [remark, setRemark] = useState('')
  const [pending, setPending] = useState(false)
  const [pendingAt, setPendingAt] = useState<string | undefined>(undefined)
  const [submitting, setSubmitting] = useState(false)

  const ensureStaffLoaded = useCallback(async () => {
    if (staffList.length) return
    try {
      const res = await listUsers({ isStaff: true } as any)
      setStaffList((res || []) as User[])
    } catch (_e) {
      // ignore (只影响“跟进人”展示)
    }
  }, [staffList.length])

  const staffNameMap = useMemo(() => {
    const map = new Map<number, string>()
    for (const u of staffList) {
      if (!u?.userId) continue
      map.set(u.userId, String(u.realName || u.nickname || u.username || `员工${u.userId}`))
    }
    return map
  }, [staffList])

  const followRealName = useMemo(() => {
    if (!company?.userId) return ''
    return staffNameMap.get(Number(company.userId)) || ''
  }, [company?.userId, staffNameMap])

  const assignDate = useMemo(() => {
    // 兼容：接口未提供“分配日期”字段时，用 updateTime/createTime 兜底展示
    return String(company?.updateTime || company?.createTime || '')
  }, [company?.createTime, company?.updateTime])

  const pendingKey = useMemo(() => (Number.isFinite(companyId) && companyId > 0 ? String(companyId) : ''), [companyId])

  const loadCompany = useCallback(async () => {
    if (!Number.isFinite(companyId) || companyId <= 0) {
      Taro.showToast({ title: '参数错误', icon: 'none' })
      return
    }

    setLoading(true)
    try {
      const data = await getCreditCompany(companyId)
      setCompany(data)

      // 从本地 pending map 恢复“待审核”状态与内容（纯前端模拟）
      const map = loadPendingMap()
      const pendingEdit = pendingKey ? map[pendingKey] : undefined
      if (pendingEdit) {
        setCustomerStatus(pendingEdit.status)
        setRemark(pendingEdit.remark)
        setPending(true)
        setPendingAt(pendingEdit.submittedAt)
      } else {
        setCustomerStatus('保护期内')
        setRemark('')
        setPending(false)
        setPendingAt(undefined)
      }
    } catch (e) {
      console.error('加载客户信息失败:', e)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }, [companyId, pendingKey])

  useDidShow(() => {
    loadCompany().then()
    ensureStaffLoaded().then()
  })

  const submitOrWithdraw = async () => {
    if (submitting) return
    if (!pendingKey) return

    // 撤回修改
    if (pending) {
      setSubmitting(true)
      try {
        const map = loadPendingMap()
        delete map[pendingKey]
        savePendingMap(map)
        setPending(false)
        setPendingAt(undefined)
        Taro.showToast({ title: '已撤回，可重新修改', icon: 'success' })
      } finally {
        setSubmitting(false)
      }
      return
    }

    // 提交修改（仅备注 + 状态），进入待审核（纯前端模拟）
    const r = remark.trim()
    if (!r) {
      Taro.showToast({ title: '请填写备注信息', icon: 'none' })
      return
    }

    setSubmitting(true)
    try {
      const map = loadPendingMap()
      const now = new Date().toISOString()
      map[pendingKey] = { status: customerStatus, remark: r, submittedAt: now }
      savePendingMap(map)

      setPending(true)
      setPendingAt(now)
      Taro.showToast({ title: '提交成功，等待审核', icon: 'success' })
    } finally {
      setSubmitting(false)
    }
  }

  const phones = useMemo(() => getCompanyPhones(company), [company])
  const industry = useMemo(() => getCompanyIndustry(company), [company])
  const companyName = String(company?.matchName || company?.name || '')

  return (
    <View className="bg-pink-50 min-h-screen">
      <ConfigProvider>
        <View className="fixed z-50 top-0 left-0 right-0 bg-pink-50" style={{ paddingTop: `${statusBarHeight}px` }}>
          <View className="px-4 h-10 flex items-center justify-between text-sm text-gray-900">
            <Text className="font-medium">12:00</Text>
            <View className="flex items-center gap-2 text-xs text-gray-600">
              <Text>信号</Text>
              <Text>Wi-Fi</Text>
              <Text>电池</Text>
            </View>
          </View>

          <View className="px-4 pb-2 flex items-center justify-between">
            <Text className="text-sm text-gray-700" onClick={() => Taro.navigateBack()}>
              返回
            </Text>
            <Text className="text-base font-semibold text-gray-900">修改客户信息</Text>
            <View className="flex items-center gap-3">
              <View className="w-7 h-7 rounded-full border border-gray-300 flex items-center justify-center text-gray-700">
                <Text>...</Text>
              </View>
              <View className="w-7 h-7 rounded-full border border-gray-300" />
            </View>
          </View>
        </View>

        <View style={{ paddingTop: `${statusBarHeight + 80}px` }} className="max-w-md mx-auto px-3">
          {loading ? (
            <View className="py-12 text-center text-gray-500">
              <Text>加载中...</Text>
            </View>
          ) : (
            <>
              <CellGroup>
                <Cell title="客户名称" description={companyName || '-'} />
                <Cell title="统一代码" description={String(company?.code || '-')} />
                <Cell
                  title="所属行业"
                  description={
                    <Text className="text-red-500">
                      {industry || '-'}
                    </Text>
                  }
                />
                <Cell title="客户联系人" description={String((company as any)?.contactName || '-')} />
                <Cell
                  title="客户联系方式"
                  description={
                    phones.length ? (
                      <View className="flex flex-col">
                        {phones.map(p => (
                          <Text key={p} className="text-gray-600">
                            {p}
                          </Text>
                        ))}
                      </View>
                    ) : (
                      '-'
                    )
                  }
                />
                <Cell title="地址" description={String(company?.address || '-')} />
                <Cell
                  title="跟进人"
                  description={
                    <Text className="text-blue-600">
                      {followRealName || '未分配'}
                    </Text>
                  }
                />
                <Cell title="分配日期" description={assignDate || '-'} />
                <Cell
                  title="客户状态"
                  description={
                    <View className="flex items-center gap-2">
                      <Text className={customerStatus === '保护期内' ? 'text-green-600' : 'text-gray-700'}>
                        {customerStatus}
                      </Text>
                      {pending && <Tag type="warning">待审核</Tag>}
                    </View>
                  }
                  onClick={() => {
                    if (pending) return
                    setStatusPickerVisible(true)
                  }}
                />
              </CellGroup>

              <View className="mt-3 px-1">
                <View className="text-sm text-gray-700 mb-2">修改内容备注信息</View>
                <TextArea
                  placeholder="请输入客户最新信息情况，管理员审核通过后，客户信息才可变更！"
                  value={remark}
                  onChange={(v) => setRemark(v)}
                  rows={4}
                  maxLength={500}
                  showCount
                  autoHeight
                  disabled={pending}
                />
                {pending && (
                  <View className="mt-2 text-xs text-gray-500">
                    已提交审核{pendingAt ? `：${pendingAt}` : ''}
                  </View>
                )}
              </View>
            </>
          )}
        </View>

        <Popup
          visible={statusPickerVisible}
          position="bottom"
          style={{ height: '45vh' }}
          onClose={() => setStatusPickerVisible(false)}
        >
          <View className="p-4">
            <View className="flex items-center justify-between mb-3">
              <Text className="text-base font-medium">选择客户状态</Text>
              <Text className="text-sm text-gray-500" onClick={() => setStatusPickerVisible(false)}>
                关闭
              </Text>
            </View>
            <CellGroup>
              {STATUS_OPTIONS.map(s => (
                <Cell
                  key={s}
                  title={<Text className={s === customerStatus ? 'text-blue-600' : ''}>{s}</Text>}
                  onClick={() => {
                    setCustomerStatus(s)
                    setStatusPickerVisible(false)
                  }}
                />
              ))}
            </CellGroup>
          </View>
        </Popup>

        <FixedButton
          text={submitting ? '处理中...' : pending ? '撤回修改' : '确定修改'}
          background="#ef4444"
          disabled={loading || submitting}
          onClick={submitOrWithdraw}
        />
      </ConfigProvider>
    </View>
  )
}
