import { useState, useEffect } from 'react';
import { Navbar } from '@/components/Navbar';
import { MarketOverviewPanel } from '@/components/MarketOverview';
import { HotEventsPanel } from '@/components/HotEvents';
import { ProductCard } from '@/components/ProductCard';
import { ProductDetail } from '@/components/ProductDetail';
import { RiskAlertsPanel } from '@/components/RiskAlerts';
import { marketOverview, hotEvents, futuresProducts, riskAlerts } from '@/data/mockData';
import { Filter, Search, TrendingUp, TrendingDown, Grid3X3, List } from 'lucide-react';
import type { FuturesProduct } from '@/types';

// 视图类型
 type ViewType = 'grid' | 'list';

// 周期筛选选项 (预留用于后续扩展)
// const cycleFilters = [
//   { key: 'all', label: '全部' },
//   { key: 'm5', label: '5分钟' },
//   { key: 'm15', label: '15分钟' },
//   { key: 'm30', label: '30分钟' },
//   { key: 'm60', label: '60分钟' },
// ];

// 品种分类
const categoryFilters = [
  { key: 'all', label: '全部' },
  { key: 'energy', label: '能源' },
  { key: 'metal', label: '金属' },
  { key: 'agriculture', label: '农产品' },
  { key: 'financial', label: '金融' },
];

// 排序选项
const sortOptions = [
  { key: 'successRate', label: '成功率' },
  { key: 'trendScore', label: '趋势强度' },
  { key: 'changePercent', label: '涨跌幅' },
];

function App() {
  const [activeTab, setActiveTab] = useState('overview');
  const [selectedProduct, setSelectedProduct] = useState<FuturesProduct | null>(null);
  const [viewType, setViewType] = useState<ViewType>('grid');
  
  // 筛选状态
  const [categoryFilter, setCategoryFilter] = useState('all');
  // const [cycleFilter, setCycleFilter] = useState('all'); // 预留用于周期筛选
  const [sortBy, setSortBy] = useState('successRate');
  const [searchQuery, setSearchQuery] = useState('');

  // 筛选和排序品种
  const filteredProducts = futuresProducts
    .filter((product) => {
      // 分类筛选
      if (categoryFilter !== 'all' && product.category !== categoryFilter) {
        return false;
      }
      // 搜索筛选
      if (searchQuery && !product.name.includes(searchQuery) && !product.code.includes(searchQuery)) {
        return false;
      }
      return true;
    })
    .sort((a, b) => {
      // 排序
      if (sortBy === 'successRate') {
        return b.successRate - a.successRate;
      } else if (sortBy === 'trendScore') {
        return b.trendScore - a.trendScore;
      } else if (sortBy === 'changePercent') {
        return b.changePercent - a.changePercent;
      }
      return 0;
    });

  // 页面加载动画
  const [isLoaded, setIsLoaded] = useState(false);
  useEffect(() => {
    setIsLoaded(true);
  }, []);

  // 渲染市场概览页面
  const renderOverview = () => (
    <div className={`space-y-6 transition-all duration-500 ${isLoaded ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-4'}`}>
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-white">市场概览</h2>
        <span className="text-sm text-[#71717a]">实时数据更新</span>
      </div>
      
      <MarketOverviewPanel data={marketOverview} />
      
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <HotEventsPanel events={hotEvents} />
        </div>
        <div>
          <RiskAlertsPanel alerts={riskAlerts} />
        </div>
      </div>
    </div>
  );

  // 渲染热点事件页面
  const renderEvents = () => (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-white">热点事件智能分析</h2>
        <span className="text-sm text-[#71717a]">共 {hotEvents.length} 条事件</span>
      </div>
      <HotEventsPanel events={hotEvents} />
    </div>
  );

  // 渲染品种分析页面
  const renderProducts = () => (
    <div className="space-y-6">
      {selectedProduct ? (
        <ProductDetail
          product={selectedProduct}
          onBack={() => setSelectedProduct(null)}
        />
      ) : (
        <>
          {/* 筛选工具栏 */}
          <div className="p-4 rounded-xl border border-[#27272a] bg-[#0d0d10] space-y-4">
            <div className="flex flex-wrap items-center gap-4">
              {/* 搜索 */}
              <div className="relative flex-1 min-w-[200px]">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#71717a]" />
                <input
                  type="text"
                  placeholder="搜索品种名称或代码..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 rounded-lg bg-[#09090b] border border-[#27272a] text-white text-sm placeholder:text-[#71717a] focus:outline-none focus:border-[#7dd75a] transition-colors"
                />
              </div>
              
              {/* 视图切换 */}
              <div className="flex items-center gap-1 p-1 rounded-lg bg-[#09090b] border border-[#27272a]">
                <button
                  onClick={() => setViewType('grid')}
                  className={`p-2 rounded-md transition-colors ${viewType === 'grid' ? 'bg-[#7dd75a] text-[#09090b]' : 'text-[#a1a1aa] hover:text-white'}`}
                >
                  <Grid3X3 className="w-4 h-4" />
                </button>
                <button
                  onClick={() => setViewType('list')}
                  className={`p-2 rounded-md transition-colors ${viewType === 'list' ? 'bg-[#7dd75a] text-[#09090b]' : 'text-[#a1a1aa] hover:text-white'}`}
                >
                  <List className="w-4 h-4" />
                </button>
              </div>
            </div>
            
            <div className="flex flex-wrap items-center gap-4">
              {/* 分类筛选 */}
              <div className="flex items-center gap-2">
                <Filter className="w-4 h-4 text-[#71717a]" />
                <span className="text-sm text-[#a1a1aa]">分类:</span>
                <div className="flex gap-1">
                  {categoryFilters.map((filter) => (
                    <button
                      key={filter.key}
                      onClick={() => setCategoryFilter(filter.key)}
                      className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                        categoryFilter === filter.key
                          ? 'bg-[#7dd75a] text-[#09090b] font-medium'
                          : 'bg-[#09090b] text-[#a1a1aa] border border-[#27272a] hover:border-[#3f3f46]'
                      }`}
                    >
                      {filter.label}
                    </button>
                  ))}
                </div>
              </div>
              
              {/* 排序 */}
              <div className="flex items-center gap-2">
                <span className="text-sm text-[#a1a1aa]">排序:</span>
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value)}
                  className="px-3 py-1.5 rounded-lg bg-[#09090b] border border-[#27272a] text-white text-sm focus:outline-none focus:border-[#7dd75a]"
                >
                  {sortOptions.map((option) => (
                    <option key={option.key} value={option.key}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>
          
          {/* 结果统计 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <span className="text-sm text-[#a1a1aa]">
                共 <span className="text-white font-medium">{filteredProducts.length}</span> 个品种
              </span>
              <div className="flex items-center gap-2 text-sm">
                <span className="flex items-center gap-1 text-[#7dd75a]">
                  <TrendingUp className="w-3 h-3" />
                  {filteredProducts.filter(p => p.change >= 0).length}
                </span>
                <span className="flex items-center gap-1 text-[#ef4444]">
                  <TrendingDown className="w-3 h-3" />
                  {filteredProducts.filter(p => p.change < 0).length}
                </span>
              </div>
            </div>
          </div>
          
          {/* 品种列表 */}
          {viewType === 'grid' ? (
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              {filteredProducts.map((product) => (
                <ProductCard
                  key={product.id}
                  product={product}
                  onClick={() => setSelectedProduct(product)}
                />
              ))}
            </div>
          ) : (
            <div className="space-y-2">
              {filteredProducts.map((product) => (
                <div
                  key={product.id}
                  onClick={() => setSelectedProduct(product)}
                  className="p-4 rounded-xl border border-[#27272a] bg-[#0d0d10] hover:border-[#7dd75a]/50 transition-all cursor-pointer"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div>
                        <div className="font-medium text-white">{product.name}</div>
                        <div className="text-xs text-[#71717a]">{product.code}</div>
                      </div>
                      <div className="flex gap-2">
                        {Object.entries(product.cycles).map(([key, trend]) => (
                          <span
                            key={key}
                            className={`px-2 py-1 rounded text-xs ${
                              trend === 'up' ? 'bg-[#7dd75a]/10 text-[#7dd75a]' :
                              trend === 'down' ? 'bg-[#ef4444]/10 text-[#ef4444]' :
                              'bg-[#a1a1aa]/10 text-[#a1a1aa]'
                            }`}
                          >
                            {key === 'm5' ? '5分' : key === 'm15' ? '15分' : key === 'm30' ? '30分' : '60分'}
                          </span>
                        ))}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className={`font-mono font-medium ${product.change >= 0 ? 'text-[#7dd75a]' : 'text-[#ef4444]'}`}>
                        ¥{product.price.toLocaleString()}
                      </div>
                      <div className={`text-sm ${product.change >= 0 ? 'text-[#7dd75a]' : 'text-[#ef4444]'}`}>
                        {product.change >= 0 ? '+' : ''}{product.changePercent}%
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
          
          {filteredProducts.length === 0 && (
            <div className="text-center py-12">
              <div className="text-[#71717a] mb-2">未找到匹配的品种</div>
              <button
                onClick={() => {
                  setCategoryFilter('all');
                  setSearchQuery('');
                }}
                className="text-[#7dd75a] hover:underline"
              >
                清除筛选条件
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );

  // 渲染风险提醒页面
  const renderRisks = () => (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-white">风险提醒</h2>
        <span className="text-sm text-[#71717a]">实时监控</span>
      </div>
      
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <RiskAlertsPanel alerts={riskAlerts} />
        
        <div className="p-6 rounded-xl border border-[#27272a] bg-[#0d0d10]">
          <h3 className="font-semibold text-white mb-4">风险控制建议</h3>
          <div className="space-y-4">
            <div className="p-4 rounded-lg bg-[#ef4444]/5 border border-[#ef4444]/20">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-2 h-2 rounded-full bg-[#ef4444]" />
                <span className="font-medium text-white">高风险环境</span>
              </div>
              <p className="text-sm text-[#a1a1aa]">
                当前地缘政治风险急剧升温，建议控制仓位在30%以下，设置严格止损。
              </p>
            </div>
            
            <div className="p-4 rounded-lg bg-[#f59e0b]/5 border border-[#f59e0b]/20">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-2 h-2 rounded-full bg-[#f59e0b]" />
                <span className="font-medium text-white">持仓管理</span>
              </div>
              <p className="text-sm text-[#a1a1aa]">
                避免隔夜重仓，特别是原油、黄金等波动较大的品种。建议日内交易为主。
              </p>
            </div>
            
            <div className="p-4 rounded-lg bg-[#7dd75a]/5 border border-[#7dd75a]/20">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-2 h-2 rounded-full bg-[#7dd75a]" />
                <span className="font-medium text-white">机会提示</span>
              </div>
              <p className="text-sm text-[#a1a1aa]">
                黄金、原油趋势明确，可关注回调后的做多机会。严格设置止损。
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-[#09090b]">
      <Navbar activeTab={activeTab} onTabChange={setActiveTab} />
      
      <main className="pt-20 pb-8 px-4 sm:px-6 lg:px-8">
        <div className="max-w-7xl mx-auto">
          {activeTab === 'overview' && renderOverview()}
          {activeTab === 'events' && renderEvents()}
          {activeTab === 'products' && renderProducts()}
          {activeTab === 'risks' && renderRisks()}
        </div>
      </main>
    </div>
  );
}

export default App;
