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

import RegionData from '@/api/json/regions-data.json'
import { addCreditCompany, pageCreditCompany } from '@/api/credit/creditCompany'
import type { CreditCompany } from '@/api/credit/creditCompany/model'
import FixedButton from '@/components/FixedButton'

const shortRegion = (label?: string) => {
  const v = String(label || '').trim()
  if (!v) return ''
  return v
    .replace(/壮族自治区|回族自治区|维吾尔自治区|自治区/g, '')
    .replace(/省|市/g, '')
}

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

  const [name, setName] = useState('')
  const [code, setCode] = useState('')
  const [industry, setIndustry] = useState('')
  const [contact, setContact] = useState('')
  const [phones, setPhones] = useState<string[]>([''])
  const [province, setProvince] = useState('广西壮族自治区')
  const [city, setCity] = useState('南宁市')
  const [detailAddress, setDetailAddress] = useState('')
  const [projectName, setProjectName] = useState('')

  const [regionVisible, setRegionVisible] = useState(false)
  const [submitting, setSubmitting] = 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,
        children: (b.children || []).map(c => ({
          value: c.label,
          text: c.label
        }))
      }))
    }))
  }, [])

  const updatePhone = (idx: number, v: string) => {
    setPhones(prev => prev.map((p, i) => (i === idx ? v : p)))
  }

  const addPhone = () => {
    setPhones(prev => prev.concat(''))
  }

  const removePhone = (idx: number) => {
    setPhones(prev => prev.filter((_, i) => i !== idx))
  }

  const submit = async () => {
    if (submitting) return

    const companyName = name.trim()
    if (!companyName) {
      Taro.showToast({ title: '请输入客户名称', icon: 'none' })
      return
    }

    const firstPhone = String(phones?.[0] || '').trim()
    if (!firstPhone) {
      Taro.showToast({ title: '请输入客户联系方式', icon: 'none' })
      return
    }

    setSubmitting(true)
    try {
      // 先查重：公司名称/统一代码
      const keywords = (code.trim() || companyName).trim()
      const existsRes = await pageCreditCompany({ page: 1, limit: 1, keywords } as any)
      const exists = ((existsRes?.list || []) as CreditCompany[]).some(c => c?.deleted !== 1)
      if (exists) {
        await Taro.showModal({
          title: '提示',
          content: '该公司信息已存在，请联系管理员核实',
          showCancel: false
        })
        return
      }

      const moreTel = phones
        .slice(1)
        .map(p => String(p || '').trim())
        .filter(Boolean)
        .join(',')

      const payload: CreditCompany = {
        name: companyName,
        matchName: companyName,
        code: code.trim() || undefined,
        tel: firstPhone,
        moreTel: moreTel || undefined,
        province,
        city,
        address: detailAddress.trim() || undefined,
        nationalStandardIndustryCategories: industry.trim() || undefined,
        comments: [
          contact.trim() ? `联系人：${contact.trim()}` : '',
          projectName.trim() ? `项目：${projectName.trim()}` : ''
        ]
          .filter(Boolean)
          .join('；') || undefined
      }

      await addCreditCompany(payload)
      Taro.showToast({ title: '添加成功', icon: 'success' })
      setTimeout(() => {
        Taro.navigateBack()
      }, 500)
    } catch (e) {
      console.error('添加客户失败:', e)
      Taro.showToast({ title: '添加失败，请重试', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

  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">
          <View className="px-3 pt-2 pb-2 text-sm text-gray-500">
            <Text>所有输入框右侧默认提示：请输入</Text>
          </View>

          <CellGroup>
            <Cell title="客户名称*">
              <Input value={name} onChange={setName} placeholder="请输入" />
            </Cell>
            <Cell title="统一代码">
              <Input value={code} onChange={setCode} placeholder="请输入" />
            </Cell>
            <Cell title="所属行业">
              <Input value={industry} onChange={setIndustry} placeholder="请输入" />
            </Cell>
            <Cell title="客户联系人">
              <Input value={contact} onChange={setContact} placeholder="请输入" />
            </Cell>

            <Cell title="客户联系方式*">
              <View className="w-full">
                {phones.map((p, idx) => (
                  <View key={idx} className={idx === 0 ? '' : 'mt-2'}>
                    <View className="flex items-center gap-2">
                      <View className="flex-1">
                        <Input value={p} onChange={(v) => updatePhone(idx, v)} placeholder="请输入" />
                      </View>
                      {idx > 0 && (
                        <Button
                          size="small"
                          fill="outline"
                          type="danger"
                          icon={<Close />}
                          onClick={() => removePhone(idx)}
                        >
                          删除
                        </Button>
                      )}
                    </View>
                  </View>
                ))}
                <View className="mt-2">
                  <Text className="text-red-500" onClick={addPhone}>
                    +添加其他手机号码
                  </Text>
                </View>
              </View>
            </Cell>

            <Cell
              title="所在省份"
              description={shortRegion(province) || '请选择'}
              onClick={() => setRegionVisible(true)}
            />
            <Cell
              title="所在地级市"
              description={shortRegion(city) || '请选择'}
              onClick={() => setRegionVisible(true)}
            />
            <Cell title="详细地址">
              <Input value={detailAddress} onChange={setDetailAddress} placeholder="请输入" />
            </Cell>
            <Cell title="项目名称">
              <Input value={projectName} onChange={setProjectName} placeholder="请输入" />
            </Cell>
          </CellGroup>
        </View>

        <Address
          visible={regionVisible}
          options={cityOptions as any}
          title="选择省市"
          onChange={(value: any[]) => {
            const arr = (value || []).filter(Boolean)
            if (arr[0]) setProvince(arr[0])
            if (arr[1]) setCity(arr[1])
            setRegionVisible(false)
          }}
          onClose={() => setRegionVisible(false)}
        />

        <FixedButton
          text={submitting ? '提交中...' : '确定'}
          background="#ef4444"
          disabled={submitting}
          onClick={submit}
        />
      </ConfigProvider>
    </View>
  )
}
