import React from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState, useEffect } from 'react'
import { Input } from '@nutui/nutui-react-taro'
import ProductCard from '@/components/common/ProductCard'
import EmptyState from '@/components/common/EmptyState'
import type { ShopGoods, ShopGoodsParam } from '@/api/shop/shopGoods/model'
import { pageShopGoods } from '@/api/shop/shopGoods'
import { useScrollHeight } from '@/hooks/useScrollHeight'

definePageConfig({
  navigationBarTitleText: '搜索',
})

const SearchPage: React.FC = () => {
  const [keyword, setKeyword] = useState('')
  const [list, setList] = useState<ShopGoods[]>([])
  const [loading, setLoading] = useState(false)
  const scrollHeight = useScrollHeight(44)

  const [history, setHistory] = useState<string[]>([])

  useEffect(() => {
    const saved = Taro.getStorageSync('search_history')
    if (saved) setHistory(JSON.parse(saved))
  }, [])

  const doSearch = async (kw?: string) => {
    const q = kw || keyword
    if (!q.trim()) return
    setLoading(true)
    try {
      const params: ShopGoodsParam = { keywords: q, isShow: 1, page: 1, limit: 20 }
      const res = await pageShopGoods(params)
      setList(res?.list || [])
      // 保存搜索历史
      const newHistory = [q, ...history.filter(h => h !== q)].slice(0, 10)
      setHistory(newHistory)
      Taro.setStorageSync('search_history', JSON.stringify(newHistory))
    } catch { /* ignore */ }
    setLoading(false)
  }

  const clearHistory = () => {
    setHistory([])
    Taro.removeStorageSync('search_history')
  }

  return (
    <View className='min-h-screen bg-white'>
      {/* 搜索栏 */}
      <View className='flex items-center gap-2 px-3 py-2'>
        <Input
          className='flex-1 bg-gray-100 rounded-full px-3 py-1 text-sm'
          placeholder='搜索商品'
          value={keyword}
          onChange={val => setKeyword(val)}
          onConfirm={() => doSearch()}
        />
        <Text className='text-sm text-green-600' onClick={() => doSearch()}>搜索</Text>
      </View>

      <ScrollView scrollY style={{ height: scrollHeight }}>
        {list.length > 0 ? (
          <View className='grid grid-cols-2 gap-2 px-3 py-2'>
            {list.map(item => (
              <ProductCard key={item.goodsId} product={item} />
            ))}
          </View>
        ) : !loading && keyword === '' ? (
          <View className='px-3 pt-4'>
            {history.length > 0 && (
              <View className='mb-4'>
                <View className='flex justify-between items-center mb-2'>
                  <Text className='text-sm font-medium text-gray-700'>搜索历史</Text>
                  <Text className='text-xs text-gray-400' onClick={clearHistory}>清空</Text>
                </View>
                <View className='flex flex-wrap gap-2'>
                  {history.map((h, i) => (
                    <View
                      key={i}
                      className='px-3 py-1 bg-gray-100 rounded-full'
                      onClick={() => { setKeyword(h); doSearch(h) }}
                    >
                      <Text className='text-xs text-gray-600'>{h}</Text>
                    </View>
                  ))}
                </View>
              </View>
            )}
            <View className='mb-2'>
              <Text className='text-sm font-medium text-gray-700 mb-2 block'>热门搜索</Text>
              <View className='flex flex-wrap gap-2'>
                {['羽毛球拍', '球鞋', '运动服', '手胶'].map((h) => (
                  <View
                    key={h}
                    className='px-3 py-1 bg-gray-100 rounded-full'
                    onClick={() => { setKeyword(h); doSearch(h) }}
                  >
                    <Text className='text-xs text-gray-600'>{h}</Text>
                  </View>
                ))}
              </View>
            </View>
          </View>
        ) : (
          <EmptyState text='未找到相关商品' />
        )}
      </ScrollView>
    </View>
  )
}

export default SearchPage
