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 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 [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-space-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-text-ink">市场概览</h2>
        <span className="text-sm text-text-slate">实时数据更新</span>
      </div>
      
      <MarketOverviewPanel data={marketOverview} />
      
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-space-6">
        <div className="lg:col-span-2">
          <HotEventsPanel events={hotEvents} />
        </div>
        <div>
          <RiskAlertsPanel alerts={riskAlerts} />
        </div>
      </div>
    </div>
  );

  const renderEvents = () => (
    <div className="space-y-space-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-text-ink">热点事件智能分析</h2>
        <span className="text-sm text-text-slate">共 {hotEvents.length} 条事件</span>
      </div>
      <HotEventsPanel events={hotEvents} />
    </div>
  );

  const renderProducts = () => (
    <div className="space-y-space-6">
      {selectedProduct ? (
        <ProductDetail
          product={selectedProduct}
          onBack={() => setSelectedProduct(null)}
        />
      ) : (
        <>
          <div className="p-4 rounded-card border border-border-light bg-white 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-text-slate" />
                <input
                  type="text"
                  placeholder="搜索品种名称或代码..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 rounded-lg bg-surface-snow border border-binanceBorder-light text-text-ink text-sm placeholder:text-text-slate focus:outline-none focus:border-binance-yellow transition-colors"
                />
              </div>
              
              <div className="flex items-center gap-1 p-1 rounded-lg bg-surface-snow border border-border-light">
                <button
                  onClick={() => setViewType('grid')}
                  className={`p-2 rounded-md transition-colors ${viewType === 'grid' ? 'bg-binance-yellow text-text-ink' : 'text-text-secondary hover:text-text-ink'}`}
                >
                  <Grid3X3 className="w-4 h-4" />
                </button>
                <button
                  onClick={() => setViewType('list')}
                  className={`p-2 rounded-md transition-colors ${viewType === 'list' ? 'bg-binance-yellow text-text-ink' : 'text-text-secondary hover:text-text-ink'}`}
                >
                  <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-text-slate" />
                <span className="text-sm text-text-secondary">分类:</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-binance-yellow text-text-ink font-semibold'
                          : 'bg-surface-snow text-text-secondary border border-border-light hover:border-binance-gold'
                      }`}
                    >
                      {filter.label}
                    </button>
                  ))}
                </div>
              </div>
              
              <div className="flex items-center gap-2">
                <span className="text-sm text-text-secondary">排序:</span>
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value)}
                  className="px-3 py-1.5 rounded-lg bg-surface-snow border border-border-light text-text-ink text-sm focus:outline-none focus:border-binance-yellow"
                >
                  {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-text-secondary">
                共 <span className="text-text-ink font-semibold">{filteredProducts.length}</span> 个品种
              </span>
              <div className="flex items-center gap-2 text-sm">
                <span className="flex items-center gap-1 text-semantic-green">
                  <TrendingUp className="w-3 h-3" />
                  {filteredProducts.filter(p => p.change >= 0).length}
                </span>
                <span className="flex items-center gap-1 text-semantic-red">
                  <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-card border border-binanceBorder-light bg-white hover:border-binance-yellow/50 transition-all cursor-pointer"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div>
                        <div className="font-semibold text-text-ink">{product.name}</div>
                        <div className="text-xs text-text-slate">{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-semantic-green/10 text-semantic-green' :
                              trend === 'down' ? 'bg-semantic-red/10 text-semantic-red' :
                              'bg-text-slate/10 text-text-slate'
                            }`}
                          >
                            {key === 'm5' ? '5分' : key === 'm15' ? '15分' : key === 'm30' ? '30分' : '60分'}
                          </span>
                        ))}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className={`font-mono font-semibold ${product.change >= 0 ? 'text-semantic-green' : 'text-semantic-red'}`}>
                        ¥{product.price.toLocaleString()}
                      </div>
                      <div className={`text-sm ${product.change >= 0 ? 'text-semantic-green' : 'text-semantic-red'}`}>
                        {product.change >= 0 ? '+' : ''}{product.changePercent}%
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
          
          {filteredProducts.length === 0 && (
            <div className="text-center py-12">
              <div className="text-text-slate mb-2">未找到匹配的品种</div>
              <button
                onClick={() => {
                  setCategoryFilter('all');
                  setSearchQuery('');
                }}
                className="text-binance-yellow hover:underline"
              >
                清除筛选条件
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );

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

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

export default App;