import { useEffect, useMemo, useRef, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { Button, CellGroup, Form, Input, Loading, TextArea } from '@nutui/nutui-react-taro'

import type { CreditMpCustomer } from '@/api/credit/creditMpCustomer/model'
import { addCreditMpCustomer, getCreditMpCustomer, updateCreditMpCustomer } from '@/api/credit/creditMpCustomer'

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

  const formRef = useRef<any>(null)
  const [loading, setLoading] = useState(true)
  const [initialValues, setInitialValues] = useState<Partial<CreditMpCustomer>>({})
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    Taro.setNavigationBarTitle({ title: id ? '编辑小程序端客户' : '新增小程序端客户' })
  }, [id])

  useEffect(() => {
    const run = async () => {
      setLoading(true)
      try {
        if (id) {
          const data = await getCreditMpCustomer(id)
          setInitialValues(data || {})
        } else {
          setInitialValues({})
        }
      } catch (e) {
        console.error('加载失败:', e)
        Taro.showToast({ title: (e as any)?.message || '加载失败', icon: 'none' })
      } finally {
        setLoading(false)
      }
    }
    run()
  }, [id])

  const onFinish = async (values: any) => {
    if (submitting) return
    setSubmitting(true)
    try {
      if (id) {
        await updateCreditMpCustomer({ ...values, id })
      } else {
        await addCreditMpCustomer(values)
      }
      Taro.showToast({ title: '操作成功', icon: 'success' })
      setTimeout(() => Taro.navigateBack(), 800)
    } catch (e) {
      console.error('保存失败:', e)
      Taro.showToast({ title: (e as any)?.message || '操作失败', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return <Loading className="px-2">加载中</Loading>
  }

  return (
    <View className="bg-gray-50 min-h-screen px-3 pt-3 pb-6">
      <Form
        ref={formRef}
        divider
        initialValues={initialValues}
        labelPosition="left"
        onFinish={onFinish}
        footer={
          <Button nativeType="submit" type="primary" size="large" loading={submitting} block>
            {id ? '更新' : '保存'}
          </Button>
        }
      >
        <CellGroup>
          <Form.Item
            name="toUser"
            label="拖欠方"
            required
            rules={[{ required: true, message: '请输入拖欠方' }]}
          >
            <Input placeholder="请输入拖欠方/付款方名称" maxLength={50} />
          </Form.Item>

          <Form.Item
            name="price"
            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="province" label="省份">
            <Input placeholder="可选" maxLength={20} />
          </Form.Item>
          <Form.Item name="city" label="城市">
            <Input placeholder="可选" maxLength={20} />
          </Form.Item>
          <Form.Item name="region" label="辖区">
            <Input placeholder="可选" maxLength={20} />
          </Form.Item>

          <Form.Item name="url" label="链接">
            <Input placeholder="可选" maxLength={200} />
          </Form.Item>

          <Form.Item name="files" label="文件">
            <TextArea placeholder="可选（可填文件URL或JSON）" maxLength={1000} rows={3} />
          </Form.Item>

          <Form.Item name="comments" label="备注">
            <TextArea placeholder="可选" maxLength={200} showCount rows={3} />
          </Form.Item>
        </CellGroup>
      </Form>
    </View>
  )
}

