import Taro, {useShareAppMessage, useShareTimeline} from '@tarojs/taro'
import {Image, Text, View} from '@tarojs/components'
import {useEffect, useState} from 'react'
import Banner from './Banner'
import iconShop from '@/assets/tabbar/shop.png'
import iconFind from '@/assets/tabbar/find.png'
import iconKefu from '@/assets/tabbar/kefu.png'
import './index.scss'
import navTo from "@/utils/common";
import {getByCode as getArticleByCode, pageCmsArticle} from '@/api/cms/cmsArticle'
import type {CmsArticle} from '@/api/cms/cmsArticle/model'
import {useUser} from '@/hooks/useUser'

function Home() {
  const {isAdmin} = useUser()
  const admin = isAdmin()

  useShareTimeline(() => {
    return {
      title: '易赊宝',
      path: `/pages/index/index`
    }
  })

  useShareAppMessage(() => {
    return {
      title: '易赊宝',
      path: `/pages/index/index`,
      success: function () {
        console.log('分享成功');
      },
      fail: function () {
        console.log('分享失败');
      }
    }
  })

  const onAction = (type: 'progress' | 'guide' | 'kefu') => {
    if (type === 'progress') {
      navTo('/credit/my-order/index', true)
      return
    }

    const textMap = { guide: '业务指南', kefu: '在线客服' } as const
    Taro.showToast({title: `${textMap[type]}（示例）`, icon: 'none'})
  }

  const FAQ_CATEGORY_ID = 4558
  const [faqList, setFaqList] = useState<CmsArticle[]>([])
  const [aboutArticle, setAboutArticle] = useState<CmsArticle | null>(null)

  const loadAbout = async () => {
    try {
      const res = await getArticleByCode('about')
      setAboutArticle(res || null)
    } catch (e) {
      console.error('loadAbout error:', e)
      setAboutArticle(null)
    }
  }

  const loadFaq = async () => {
    try {
      const res = await pageCmsArticle({
        categoryId: FAQ_CATEGORY_ID,
        page: 1,
        limit: 5,
        status: 0
      })
      setFaqList(res?.list || [])
    } catch (e) {
      console.error('loadFaq error:', e)
      setFaqList([])
      Taro.showToast({title: '常见问题加载失败', icon: 'none'})
    }
  }

  useEffect(() => {
    loadFaq().then()
    loadAbout().then()
  }, [])

  const aboutText =
    (aboutArticle?.comments || '')
      .replace(/<[^>]*>/g, '')
      .replace(/&nbsp;|&#160;/g, ' ')
      .trim() ||
    '易赊宝是提供专业回款咨询服务的小程序！我们重视企业需求，加速回款咨询服务能力助力企业资金流动畅通循环，服务团队全国覆盖。'

  return (
    <View className='home'>
      <View className='bannerCard'>
        {/* 顶部活动主视觉：使用 Banner 组件 */}
        <Banner />

      </View>

      {!admin && (
        <View className='actionCard'>
          <View className='actionRow'>
            <View className='actionItem' onClick={() => onAction('progress')}>
              <View className='actionIcon'>
                <Image className='actionIconImg' src={iconShop} mode='aspectFit' />
              </View>
              <Text className='actionLabel'>查询进度</Text>
            </View>

            <View className='actionItem' onClick={() => onAction('guide')}>
              <View className='actionIcon'>
                <Image className='actionIconImg' src={iconFind} mode='aspectFit' />
              </View>
              <Text className='actionLabel'>业务指南</Text>
            </View>

            <View className='actionItem' onClick={() => onAction('kefu')}>
              <View className='actionIcon'>
                <Image className='actionIconImg' src={iconKefu} mode='aspectFit' />
              </View>
              <Text className='actionLabel'>在线客服</Text>
            </View>
          </View>
        </View>
      )}

      <View className='sectionCard'>
        <View className='sectionHeader'>
          <View className='sectionAccent' />
          <Text className='sectionTitle'>简介</Text>
          <Text
            className='sectionMore'
            onClick={() => {
              if (aboutArticle?.articleId) {
                navTo(`/cms/detail/index?id=${aboutArticle.articleId}`)
              } else {
                Taro.showToast({title: '暂无简介内容', icon: 'none'})
              }
            }}
          >
            更多
          </Text>
        </View>

        <View className='introBox'>
          <Text className='introText'>
            {aboutText}
          </Text>
        </View>

        {admin && (
          <View className='ctaWrap gap-3'>
            <View className='ctaBtn' onClick={() => navTo('/credit/company/index', true)}>
              <Text className='ctaBtnText'>客户管理</Text>
            </View>
            <View className='ctaBtn' onClick={() => navTo('/credit/order/index', true)}>
              <Text className='ctaBtnText'>订单管理</Text>
            </View>
            <View className='ctaBtn' onClick={() => navTo('/credit/data/index', true)}>
              <Text className='ctaBtnText'>数据查询</Text>
            </View>
            <View className='ctaBtn' onClick={() => navTo('/credit/customer/index', true)}>
              <Text className='ctaBtnText'>客户联系人管理</Text>
            </View>
          </View>
        )}

        {!admin && (
          <View className='ctaWrap'>
            <View className='ctaBtn' onClick={() => navTo('/credit/order/add', true)}>
              <Text className='ctaBtnText'>发需求</Text>
            </View>
            <Text className='ctaHint'>提出您的述求，免费获取解决方案</Text>
          </View>
        )}
      </View>

      {!admin && (
        <View className='sectionCard'>
          <View className='sectionHeader'>
            <View className='sectionAccent' />
            <Text className='sectionTitle'>常见问题解答</Text>
            <Text
              className='sectionMore'
              onClick={() => navTo(`/cms/category/index?id=${FAQ_CATEGORY_ID}`)}
            >
              更多&gt;&gt;
            </Text>
          </View>

          <View className='faqList'>
            {faqList.length > 0 ? (
              faqList.map((item, idx, arr) => (
                <View
                  key={item.articleId || `${item.title}-${idx}`}
                  className={`faqItem ${idx === arr.length - 1 ? 'faqItemLast' : ''}`}
                  onClick={() => item.articleId && navTo(`/cms/detail/index?id=${item.articleId}`)}
                >
                  <Text className='faqTitle'>{item.title}</Text>
                  <Text className='faqDate'>{(item.createTime || '').slice(0, 10)}</Text>
                </View>
              ))
            ) : (
              <View className='faqItem faqItemLast'>
                <Text className='faqTitle'>暂无常见问题</Text>
                <Text className='faqDate' />
              </View>
            )}
          </View>
        </View>
      )}


      <View className='bottomSpacer' />
    </View>
  )
}

export default Home
