import React, { useEffect, useCallback } from 'react';
import { useOutfitSearchStore, useOutfitSearchActions, useOutfitSearchSelectors } from '../store/outfitSearchStore';
import { OutfitSearchPanel } from '../components/outfit/OutfitSearchPanel';
import { SearchResults } from '../components/outfit/SearchResults';

import { SearchRequest } from '../types/outfitSearch';
import { Search, Image, MessageCircle, RotateCcw, Sparkles } from 'lucide-react';

/**
 * 服装搭配主页面
 * 遵循 Tauri 开发规范的页面组件设计原则
 */
export const OutfitMatch: React.FC = () => {
  // 移除tab状态，统一为一个搜索界面

  // 状态管理
  const {
    searchConfig,
    searchResults,
    updateSearchConfig,
    executeSearch,
    setSelectedImage,
    clearErrors,
    analyzeImage,
  } = useOutfitSearchStore();

  // 辅助函数
  const { resetAll } = useOutfitSearchActions();

  // 选择器
  const { useSearchState, useAnalysisState } = useOutfitSearchSelectors();

  // 获取各种状态
  const searchState = useSearchState();
  const analysisState = useAnalysisState();

  // 页面初始化
  useEffect(() => {
    // 清除之前的错误
    clearErrors();

    // 可以在这里加载默认搜索结果
    // quickSearch('model');
  }, [clearErrors]);

  // 处理搜索
  const handleSearch = useCallback((request: SearchRequest) => {
    executeSearch(request);
  }, [executeSearch]);

  // 处理图像选择
  const handleImageSelect = useCallback((imagePath: string | null) => {
    setSelectedImage(imagePath);
  }, [setSelectedImage]);

  // 处理图像分析
  const handleAnalyzeImage = useCallback((imagePath: string) => {
    analyzeImage({
      image_path: imagePath,
      image_name: imagePath.split('/').pop() || imagePath,
    });
  }, [analyzeImage]);

  // 处理页面变化
  const handlePageChange = useCallback((page: number) => {
    const lastQuery = searchResults.length > 0 ? 'model' : 'model'; // 这里应该从历史记录获取
    const request: SearchRequest = {
      query: lastQuery,
      config: searchConfig,
      page_size: 9,
      page_offset: (page - 1) * 9,
    };
    executeSearch(request);
  }, [searchConfig, executeSearch, searchResults.length]);

  // 处理搜索结果项选择
  const handleResultSelect = useCallback((result: any) => {
    console.log('Selected result:', result);
    // 这里可以实现详情查看或其他操作
  }, []);

  // 处理重置
  const handleReset = useCallback(() => {
    resetAll();
  }, [resetAll]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50/30 to-gray-50">
      {/* 固定顶部导航栏 */}
      <div className="page-header py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="icon-container primary w-10 h-10">
              <Sparkles className="w-5 h-5" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-high-emphasis">
                服装搭配智能搜索
              </h1>
              <p className="text-xs text-medium-emphasis hidden sm:block">
                AI驱动的智能搭配推荐系统
              </p>
            </div>
          </div>

          {/* 快速操作按钮 */}
          <div className="flex items-center gap-2">
            <button
              onClick={handleReset}
              className="btn btn-outline btn-sm hover-lift"
              title="重置所有设置"
            >
              <RotateCcw className="w-4 h-4" />
              <span className="hidden sm:inline ml-2">重置</span>
            </button>
          </div>
        </div>
      </div>

      {/* 主要内容区域 - 可滚动 */}
      <div className="content-container pt-6 pb-12">

        {/* 主要内容区域 - 响应式布局 */}
        <div className="grid grid-cols-1 lg:grid-cols-[400px_1fr] gap-6 lg:gap-8 animate-fade-in">
          <div className="space-y-6 order-2 lg:order-1">
            <OutfitSearchPanel
              config={searchConfig}
              onConfigChange={updateSearchConfig}
              onSearch={handleSearch}
              isLoading={searchState.isSearching}
              analysisResult={analysisState.result}
              onImageSelect={handleImageSelect}
              onAnalyzeImage={handleAnalyzeImage}
              selectedImage={analysisState.selectedImage}
              isAnalyzing={analysisState.isAnalyzing}
              analysisError={analysisState.analysisError}
            />
          </div>

          <div className="min-h-[400px] sm:min-h-[600px] order-1 lg:order-2">
            {searchState.results.length > 0 ? (
              <SearchResults
                results={searchState.results}
                totalSize={searchState.results.length}
                currentPage={searchState.currentPage}
                pageSize={9}
                onPageChange={handlePageChange}
                onItemSelect={handleResultSelect}
                isLoading={searchState.isSearching}
              />
            ) : (
              <div className="card h-full flex flex-col items-center justify-center text-center p-6 sm:p-12 animate-fade-in">
                <div className="icon-container purple w-16 h-16 mb-6">
                  <Sparkles className="w-8 h-8" />
                </div>
                <h3 className="text-2xl font-bold text-high-emphasis mb-3">开始您的智能搭配之旅</h3>
                <div className="space-y-2 text-medium-emphasis max-w-md">
                  <p className="flex items-center gap-2 justify-center">
                    <Image className="w-4 h-4" />
                    上传服装图片，AI自动分析并生成筛选条件
                  </p>
                  <p className="flex items-center gap-2 justify-center">
                    <Search className="w-4 h-4" />
                    输入关键词进行精准搜索
                  </p>
                  <p className="flex items-center gap-2 justify-center">
                    <MessageCircle className="w-4 h-4" />
                    向AI顾问咨询搭配建议
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default OutfitMatch;
