import { useMemo, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { Address, Button, Cell, CellGroup, Form, Input, Radio, TextArea } from '@nutui/nutui-react-taro'
import { ArrowRight, Close } from '@nutui/icons-react-taro'

import FixedButton from '@/components/FixedButton'
import RegionData from '@/api/json/regions-data.json'
import { uploadFile, uploadFileByPath } from '@/api/system/file'
import { addCreditMpCustomer } from '@/api/credit/creditMpCustomer'

import './add.scss'

type Attachment = {
  id: string
  name: string
  url: string
  isImage: boolean
  thumbnail?: string
}

const isHttpUrl = (url?: string) => {
  if (!url) return false
  return /^https?:\/\//i.test(url)
}

const guessFileType = (nameOrUrl?: string) => {
  const s = String(nameOrUrl || '').trim()
  if (!s) return undefined
  const clean = s.split('?')[0].split('#')[0]
  const dot = clean.lastIndexOf('.')
  if (dot < 0) return undefined
  const ext = clean.slice(dot + 1).toLowerCase()
  if (!/^[a-z0-9]+$/.test(ext)) return undefined
  return ext
}

export default function CreditOrderAddPage() {
  const formRef = useRef<any>(null)

  const [cityVisible, setCityVisible] = useState(false)
  const [cityText, setCityText] = useState('')
  const [cityValue, setCityValue] = useState<string[]>([])

  const [attachments, setAttachments] = useState<Attachment[]>([])
  const [uploading, setUploading] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [agree, setAgree] = useState(false)

  const cityOptions = useMemo(() => {
    // NutUI Address options: [{ text, value, children }]
    // @ts-ignore
    return (RegionData || []).map(a => ({
      value: a.label,
      text: a.label,
      children: (a.children || []).map(b => ({
        value: b.label,
        text: b.label
      }))
    }))
  }, [])

  const addUploadedRecords = (
    incoming: Array<{ url?: string; thumbnail?: string; downloadUrl?: string; path?: string; name?: string }>,
    opts: { isImage: boolean }
  ) => {
    const next = incoming
      .map((r, idx) => {
        const url = String(r.url || r.downloadUrl || r.thumbnail || r.path || '').trim()
        if (!url) return null
        const name = String(r.name || (opts.isImage ? `图片${idx + 1}` : `文件${idx + 1}`)).trim()
        const id = `${Date.now()}-${Math.random().toString(16).slice(2)}`
        return { id, name, url, thumbnail: r.thumbnail, isImage: opts.isImage } as Attachment
      })
      .filter(Boolean) as Attachment[]

    if (!next.length) return
    setAttachments(prev => prev.concat(next))
  }

  const chooseAndUploadImages = async () => {
    setUploading(true)
    try {
      // 与用户认证页一致：走 uploadFile() 内部的 chooseImage + uploadFileByPath 流程
      const record = await uploadFile()
      addUploadedRecords([record as any], { isImage: true })
      Taro.showToast({ title: '上传成功', icon: 'success' })
    } catch (e) {
      console.error('上传图片失败:', e)
      Taro.showToast({ title: String((e as any)?.message || '上传失败，请重试'), icon: 'none' })
    } finally {
      setUploading(false)
    }
  }

  const chooseAndUploadDocs = async () => {
    // 微信小程序：从会话/聊天等入口选择文件
    // H5 等环境可能不支持，走 try/catch 提示即可
    let res: any
    try {
      // @ts-ignore
      res = await Taro.chooseMessageFile({
        count: 9,
        type: 'file'
      })
    } catch (e) {
      const msg = String((e as any)?.errMsg || (e as any)?.message || e || '')
      if (msg.includes('cancel')) return
      console.error('选择文件失败:', e)
      Taro.showToast({ title: '当前环境不支持选取文件', icon: 'none' })
      return
    }

    // @ts-ignore
    const tempFiles = (res?.tempFiles || []) as Array<{ path?: string; name?: string }>
    const picked = tempFiles
      .map(f => ({ path: f?.path, name: f?.name }))
      .filter(f => Boolean(f.path)) as Array<{ path: string; name?: string }>
    if (!picked.length) return

    setUploading(true)
    try {
      const uploaded = []
      for (const f of picked) {
        const record = await uploadFileByPath(f.path)
        const name = f?.name
        uploaded.push({ ...(record as any), name: name || (record as any)?.name })
      }
      addUploadedRecords(uploaded, { isImage: false })
      Taro.showToast({ title: '上传成功', icon: 'success' })
    } catch (e) {
      console.error('上传文件失败:', e)
      Taro.showToast({ title: String((e as any)?.message || '上传失败，请重试'), icon: 'none' })
    } finally {
      setUploading(false)
    }
  }

  const chooseAttachment = async () => {
    try {
      const res = await Taro.showActionSheet({
        itemList: ['上传图片', '上传文件']
      })
      if (res.tapIndex === 0) await chooseAndUploadImages()
      if (res.tapIndex === 1) await chooseAndUploadDocs()
    } catch (e) {
      // 用户取消
      const msg = String((e as any)?.errMsg || (e as any)?.message || e || '')
      if (msg.includes('cancel')) return
      console.error('选择上传类型失败:', e)
    }
  }

  const removeAttachment = (id: string) => {
    setAttachments(prev => prev.filter(a => a.id !== id))
  }

  const previewAttachment = async (a: Attachment) => {
    try {
      if (a.isImage) {
        const imgs = attachments.filter(x => x.isImage).map(x => x.url)
        await Taro.previewImage({ urls: imgs, current: a.url })
        return
      }

      let filePath = a.url
      if (isHttpUrl(a.url)) {
        const dl = await Taro.downloadFile({ url: a.url })
        // @ts-ignore
        filePath = dl?.tempFilePath
      }

      const fileType = guessFileType(a.name || a.url)
      const openOpts: any = { filePath, showMenu: true }
      if (fileType) openOpts.fileType = fileType
      await Taro.openDocument(openOpts)
    } catch (e) {
      console.error('预览文件失败:', e)
      Taro.showToast({ title: '无法打开该文件', icon: 'none' })
    }
  }

  const submitSucceed = async (values: any) => {
    const payer = String(values?.payer || '').trim()
    const amount = Number(values?.amount)
    const years = Number(values?.years)
    const remark = String(values?.remark || '').trim()

    if (!payer) {
      Taro.showToast({ title: '请输入拖欠方（付款方）', icon: 'none' })
      return
    }
    if (!Number.isFinite(amount) || amount <= 0) {
      Taro.showToast({ title: '请输入正确的拖欠金额', icon: 'none' })
      return
    }
    if (!Number.isFinite(years) || years <= 0) {
      Taro.showToast({ title: '请输入正确的拖欠年数', icon: 'none' })
      return
    }
    if (!agree) {
      Taro.showToast({ title: '请先同意服务协议', icon: 'none' })
      return
    }

    const [province, city, region] = cityValue
    const files = attachments.map(a => ({
      name: a.name,
      url: a.url,
      thumbnail: a.thumbnail,
      isImage: a.isImage
    }))

    setSubmitting(true)
    try {
      await addCreditMpCustomer({
        toUser: payer,
        price: String(amount),
        years: String(years),
        comments: remark || undefined,
        province: province || undefined,
        city: city || undefined,
        region: region || undefined,
        files: files.length ? JSON.stringify(files) : undefined
      })

      Taro.showToast({ title: '提交成功', icon: 'success' })
      Taro.eventCenter.trigger('credit:order:created', {
        toUser: payer,
        price: String(amount),
        years: String(years),
        comments: remark || undefined,
        province: province || undefined,
        city: city || undefined,
        region: region || undefined,
        files
      })
      setTimeout(() => {
        Taro.navigateBack()
      }, 800)
    } catch (e) {
      console.error('提交失败:', e)
      Taro.showToast({ title: (e as any)?.message || '提交失败，请重试', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

  const submitFailed = (err: any) => {
    console.log('表单校验失败:', err)
  }

  const canSubmit = !uploading && !submitting && agree

  return (
    <View className="credit-order-add-page">
      <Form
        ref={formRef}
        divider
        labelPosition="left"
        onFinish={submitSucceed}
        onFinishFailed={submitFailed}
      >
        <CellGroup>
          <Form.Item
            name="payer"
            label="拖欠方"
            required
            rules={[{ required: true, message: '请输入拖欠方（付款方）' }]}
          >
            <Input placeholder="请输入拖欠方/付款方名称" maxLength={50} />
          </Form.Item>

          <Form.Item
            name="amount"
            label="拖欠金额"
            required
            rules={[{ required: true, message: '请输入拖欠金额' }]}
          >
            <Input placeholder="请输入拖欠金额" type="number" />
          </Form.Item>

          <Form.Item
            name="years"
            label="拖欠几年"
            required
            rules={[{ required: true, message: '请输入拖欠年数' }]}
          >
            <Input placeholder="请输入拖欠年数" type="number" />
          </Form.Item>

          <Form.Item name="remark" label="备注">
            <TextArea placeholder="补充说明（可选）" maxLength={200} showCount rows={3} />
          </Form.Item>
        </CellGroup>
      </Form>

      <CellGroup>
        <Cell
          title="所在城市"
          description={cityText || '请选择（可选）'}
          extra={<ArrowRight color="#cccccc" />}
          onClick={() => setCityVisible(true)}
        />
      </CellGroup>

      <CellGroup title="上传文件（支持图片和文档）">
        <Cell>
          <View className="attachments">
            {attachments.length ? (
              <View className="attachments__list">
                {attachments.map(a => (
                  <View key={a.id} className="attachments__item" onClick={() => previewAttachment(a)}>
                    <Text className="attachments__name">{a.name}</Text>
                    <Text
                      className="attachments__remove"
                      onClick={e => {
                        e.stopPropagation()
                        removeAttachment(a.id)
                      }}
                    >
                      <Close size={12} />
                    </Text>
                  </View>
                ))}
              </View>
            ) : (
              <Text className="attachments__empty">未添加附件</Text>
            )}

            <Button
              size="small"
              type="primary"
              fill="outline"
              loading={uploading}
              disabled={uploading || submitting}
              onClick={chooseAttachment}
            >
              {uploading ? '上传中...' : '添加文件'}
            </Button>
          </View>
        </Cell>
      </CellGroup>

      <View className="agreement py-2 px-3">
        <Radio checked={agree} onClick={() => setAgree(v => !v)} />
        <Text className="agreement__text" onClick={() => setAgree(v => !v)}>
          我已阅读并同意
        </Text>
        <Text className="agreement__link" onClick={() => Taro.navigateTo({ url: '/passport/agreement' })}>
          《服务协议》
        </Text>
      </View>

      <Address
        visible={cityVisible}
        options={cityOptions as any}
        title="选择城市"
        onChange={(value: any[]) => {
          const list = (value || []).filter(Boolean).slice(0, 2).map(v => String(v))
          setCityValue(list)
          const txt = list.join(' ')
          setCityText(txt || '')
          setCityVisible(false)
        }}
        onClose={() => setCityVisible(false)}
      />

      <FixedButton
        text={submitting ? '提交中...' : '提交需求'}
        disabled={!canSubmit}
        onClick={() => formRef.current?.submit()}
      />
    </View>
  )
}
