import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Navbar } from '@/components/ui/navbar'
import TDesignSearch from '@/components/tdesign/search'
import './index.css'

// 本地存储搜索历史
const SEARCH_HISTORY_KEY = 'search_history'

const SearchPage: React.FC = () => {
  const [searchValue, setSearchValue] = useState('')
  const [historyWords, setHistoryWords] = useState<string[]>([])
  const [popularWords, setPopularWords] = useState<string[]>([])

  // 获取搜索历史
  const getSearchHistory = (): string[] => {
    try {
      const history = Taro.getStorageSync(SEARCH_HISTORY_KEY)
      return Array.isArray(history) ? history : []
    } catch (error) {
      console.error('获取搜索历史失败:', error)
      return []
    }
  }

  // 保存搜索历史
  const saveSearchHistory = (keyword: string) => {
    try {
      const history = getSearchHistory()
      // 移除重复的关键词
      const filteredHistory = history.filter(word => word !== keyword)
      // 将新关键词添加到前面
      const newHistory = [keyword, ...filteredHistory]
      // 限制历史记录数量
      const limitedHistory = newHistory.slice(0, 10)
      Taro.setStorageSync(SEARCH_HISTORY_KEY, limitedHistory)
      setHistoryWords(limitedHistory)
    } catch (error) {
      console.error('保存搜索历史失败:', error)
    }
  }

  // 清空搜索历史
  const clearSearchHistory = () => {
    try {
      Taro.removeStorageSync(SEARCH_HISTORY_KEY)
      setHistoryWords([])
    } catch (error) {
      console.error('清空搜索历史失败:', error)
    }
  }

  // 获取热门搜索词（模拟数据）
  const getPopularSearchWords = (): string[] => {
    return [
      '洗发水',
      '发膜',
      '染膏',
      '吹风机',
      '干胶',
      '精油'
      // '手机',
      // '笔记本电脑',
      // '耳机',
      // '智能手表',
      // '平板电脑',
      // '数码相机',
      // '游戏机',
      // '智能家居'
    ]
  }

  // 页面显示时加载数据
  useEffect(() => {
    setHistoryWords(getSearchHistory())
    setPopularWords(getPopularSearchWords())
  }, [])

  // 处理搜索提交
  const handleSubmit = (value: string) => {
    if (!value.trim()) return

    // 保存搜索历史
    saveSearchHistory(value.trim())

    // 跳转到搜索结果页面
    Taro.navigateTo({
      url: `/pages/search-result/index?keyword=${encodeURIComponent(value)}`
    })
  }

  // 点击历史搜索项
  const handleHistoryTap = (word: string) => {
    setSearchValue(word)
    // 保存搜索历史
    saveSearchHistory(word)
    Taro.navigateTo({
      url: `/pages/search-result/index?keyword=${encodeURIComponent(word)}`
    })
  }

  // 点击热门搜索项
  const handlePopularTap = (word: string) => {
    setSearchValue(word)
    // 保存搜索历史
    saveSearchHistory(word)
    Taro.navigateTo({
      url: `/pages/search-result/index?keyword=${encodeURIComponent(word)}`
    })
  }

  // 清空搜索历史
  const handleClearHistory = () => {
    clearSearchHistory()
  }

  return (
    <View className="search-page">
      <Navbar
        title="搜索"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
        className="bg-white"
      />

      <ScrollView className="search-page-content" scrollY>
        {/* 搜索栏 */}
        <View className="search-input-container">
          <TDesignSearch
            placeholder="搜索商品..."
            shape="round"
            value={searchValue}
            onChange={(value) => setSearchValue(value)}
            onSubmit={() => handleSubmit(searchValue)}
            onClear={() => setSearchValue('')}
          />
        </View>

        {/* 搜索历史 */}
        {historyWords.length > 0 && (
          <View className="search-section">
            <View className="search-header">
              <Text className="search-title">搜索历史</Text>
              <Text
                className="search-clear"
                onClick={handleClearHistory}
                data-testid="clear-history"
              >
                清空
              </Text>
            </View>
            <View className="search-content">
              {historyWords.map((word: string, index: number) => (
                <View
                  key={index}
                  className="search-item"
                  onClick={() => handleHistoryTap(word)}
                  data-testid="history-item"
                >
                  <Text className="search-item-text">{word}</Text>
                </View>
              ))}
            </View>
          </View>
        )}

        {/* 热门搜索 */}
        {popularWords.length > 0 && (
          <View className="search-section">
            <View className="search-header">
              <Text className="search-title">热门搜索</Text>
            </View>
            <View className="search-content">
              {popularWords.map((word: string, index: number) => (
                <View
                  key={index}
                  className="search-item"
                  onClick={() => handlePopularTap(word)}
                  data-testid="popular-item"
                >
                  <Text className="search-item-text">{word}</Text>
                </View>
              ))}
            </View>
          </View>
        )}

        {/* 空状态 */}
        {historyWords.length === 0 && popularWords.length === 0 && (
          <View className="empty-state" data-testid="empty-state">
            <View className="i-heroicons-magnifying-glass-20-solid empty-icon" />
            <Text className="empty-text">暂无搜索记录</Text>
            <Text className="empty-subtext">输入关键词搜索商品</Text>
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default SearchPage