import React, { useState, useCallback, useRef } from 'react';
import { t } from '@/i18n';
import Taro from '@tarojs/taro';
import CouponCard from '@/components/coupon-card';
import { searchCoupons } from '../../services/coupon';
import type { CouponItem } from '../../services/coupon';
// Taro mini-program component (WeChat / Alipay)

/**
 * E1. 小程序核心页面 - 搜索页
 *
 * 热门搜索标签 + 搜索历史 + 搜索结果
 * 输入内容后展示券列表，点击跳转详情
 */

const hotTags = ['Starbucks', 'Amazon', t('category_food'), t('coupon_sort_discount'), t('category_travel'), 'Nike'];

const SearchPage: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [historyItems, setHistoryItems] = useState<string[]>(() => {
    try {
      const saved = Taro.getStorageSync('search_history');
      return saved ? JSON.parse(saved) : [];
    } catch {
      return [];
    }
  });
  const [results, setResults] = useState<CouponItem[]>([]);
  const [resultTotal, setResultTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const doSearch = useCallback((keyword: string) => {
    if (!keyword.trim()) {
      setResults([]);
      setResultTotal(0);
      setHasSearched(false);
      return;
    }
    setLoading(true);
    setHasSearched(true);
    searchCoupons({ q: keyword.trim() })
      .then((data) => {
        setResults(data.items);
        setResultTotal(data.total);
      })
      .catch(() => {
        setResults([]);
        setResultTotal(0);
      })
      .finally(() => setLoading(false));
  }, []);

  const handleInput = (e: any) => {
    const val = e.detail.value;
    setSearchText(val);
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      doSearch(val);
    }, 500);
  };

  const handleTagOrHistory = (text: string) => {
    setSearchText(text);
    addToHistory(text);
    doSearch(text);
  };

  const addToHistory = (text: string) => {
    const updated = [text, ...historyItems.filter((h) => h !== text)].slice(0, 10);
    setHistoryItems(updated);
    try {
      Taro.setStorageSync('search_history', JSON.stringify(updated));
    } catch {}
  };

  const clearHistory = () => {
    setHistoryItems([]);
    try {
      Taro.removeStorageSync('search_history');
    } catch {}
  };

  const handleResultTap = (coupon: CouponItem) => {
    addToHistory(searchText);
    Taro.navigateTo({ url: `/pages/detail/index?id=${coupon.id}` });
  };

  const formatDiscount = (coupon: CouponItem) => {
    const ratio = coupon.currentPrice / coupon.faceValue;
    return `${(ratio * 10).toFixed(1)}折`;
  };

  const showResults = hasSearched || searchText.length > 0;

  return (
    <view className="search-page">
      {/* Header: Search Input + Cancel */}
      <view className="search-header">
        <view className="search-input-wrap">
          <text className="search-icon">🔍</text>
          <input
            className="search-input"
            placeholder={t('search_placeholder')}
            value={searchText}
            onInput={handleInput}
            onConfirm={() => { addToHistory(searchText); doSearch(searchText); }}
            focus
          />
          {searchText.length > 0 && (
            <text className="search-clear" onClick={() => { setSearchText(''); setResults([]); setResultTotal(0); setHasSearched(false); }}>✕</text>
          )}
        </view>
        <text className="search-cancel" onClick={() => Taro.navigateBack()}>{t('cancel')}</text>
      </view>

      {!showResults ? (
        <scroll-view scrollY className="search-body">
          {/* Hot Tags */}
          <view className="section">
            <text className="section-title">{t('search_hot_keywords')}</text>
            <view className="tag-wrap">
              {hotTags.map((tag, i) => (
                <view key={i} className="hot-tag" onClick={() => handleTagOrHistory(tag)}>
                  <text className="hot-tag-text">{tag}</text>
                </view>
              ))}
            </view>
          </view>

          {/* Search History */}
          {historyItems.length > 0 && (
            <view className="section">
              <view className="section-header">
                <text className="section-title">{t('search_history')}</text>
                <text className="section-clear" onClick={clearHistory}>{t('search_clear_history')}</text>
              </view>
              {historyItems.map((item, i) => (
                <view key={i} className="history-item" onClick={() => handleTagOrHistory(item)}>
                  <text className="history-icon">🕐</text>
                  <text className="history-text">{item}</text>
                </view>
              ))}
            </view>
          )}
        </scroll-view>
      ) : (
        <scroll-view scrollY className="search-results">
          {loading ? (
            <view style={{ textAlign: 'center', padding: '60rpx 0' }}>
              <text style={{ color: '#A0A8BE', fontSize: '26rpx' }}>{t('loading') || '搜索中...'}</text>
            </view>
          ) : (
            <>
              <view className="result-count">
                <text className="result-count-text">{t('search_result_count').replace('{count}', String(resultTotal))}</text>
              </view>
              <view className="result-list">
                {results.length === 0 ? (
                  <view style={{ textAlign: 'center', padding: '60rpx 0' }}>
                    <text style={{ color: '#A0A8BE', fontSize: '26rpx' }}>{t('search_no_results') || '暂无搜索结果'}</text>
                  </view>
                ) : (
                  results.map((coupon) => (
                    <CouponCard
                      key={coupon.id}
                      brand={coupon.brandName || coupon.category}
                      name={coupon.name}
                      price={`¥${coupon.currentPrice.toFixed(2)}`}
                      faceValue={`¥${coupon.faceValue}`}
                      discount={formatDiscount(coupon)}
                      onClick={() => handleResultTap(coupon)}
                    />
                  ))
                )}
              </view>
            </>
          )}
        </scroll-view>
      )}
    </view>
  );
};

export default SearchPage;

/*
CSS (index.scss):

.search-page { background: #F8F9FC; min-height: 100vh; }

.search-header {
  display: flex; align-items: center;
  padding: 20rpx 32rpx; background: white;
  border-bottom: 1rpx solid #F1F3F8;
}
.search-input-wrap {
  flex: 1; display: flex; align-items: center;
  height: 72rpx; padding: 0 24rpx;
  background: #F1F3F8; border-radius: 999rpx;
}
.search-icon { font-size: 28rpx; margin-right: 12rpx; flex-shrink: 0; }
.search-input { flex: 1; font-size: 28rpx; color: #141723; background: transparent; }
.search-clear {
  font-size: 24rpx; color: #A0A8BE; margin-left: 12rpx;
  width: 40rpx; height: 40rpx; display: flex; align-items: center; justify-content: center;
}
.search-cancel { font-size: 28rpx; color: #6C5CE7; margin-left: 24rpx; flex-shrink: 0; }

.search-body { padding: 0 32rpx; height: calc(100vh - 112rpx); }
.search-results { padding: 0 32rpx; height: calc(100vh - 112rpx); }

.section { margin-top: 32rpx; }
.section-header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 20rpx;
}
.section-title { font-size: 30rpx; font-weight: 600; color: #141723; }
.section-clear { font-size: 24rpx; color: #A0A8BE; }

.tag-wrap { display: flex; flex-wrap: wrap; gap: 16rpx; margin-top: 20rpx; }
.hot-tag {
  padding: 12rpx 28rpx; background: #F3F1FF;
  border-radius: 999rpx; border: 1rpx solid rgba(108,92,231,0.12);
}
.hot-tag-text { font-size: 26rpx; color: #6C5CE7; }

.history-item {
  display: flex; align-items: center; padding: 20rpx 0;
  border-bottom: 1rpx solid #F1F3F8;
}
.history-icon { font-size: 24rpx; margin-right: 16rpx; color: #A0A8BE; }
.history-text { font-size: 28rpx; color: #5C6478; }

.result-count { padding: 20rpx 0; }
.result-count-text { font-size: 24rpx; color: #A0A8BE; }
.result-list { padding-bottom: 40rpx; }
*/
