import React, { useState, useCallback } from 'react';
import { Heart, Search, ArrowLeft } from 'lucide-react';
import { OutfitFavorite } from '../../types/outfitFavorite';
import FavoriteOutfitList from '../../components/outfit/FavoriteOutfitList';
import { OutfitFavoriteService } from '../../services/outfitFavoriteService';

/**
 * 穿搭方案收藏管理工具
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const OutfitFavoritesTool: React.FC = () => {
  const [selectedFavorite, setSelectedFavorite] = useState<OutfitFavorite | null>(null);
  const [searchResults, setSearchResults] = useState<any>(null);
  const [isSearching, setIsSearching] = useState(false);
  const [searchError, setSearchError] = useState<string | null>(null);

  // 处理收藏方案选择
  const handleFavoriteSelect = useCallback(async (favorite: OutfitFavorite) => {
    setSelectedFavorite(favorite);
    setIsSearching(true);
    setSearchError(null);

    try {
      const results = await OutfitFavoriteService.searchMaterialsByFavorite(favorite.id);
      setSearchResults(results);
    } catch (error) {
      console.error('基于收藏方案检索素材失败:', error);
      setSearchError(error instanceof Error ? error.message : '检索失败');
    } finally {
      setIsSearching(false);
    }
  }, []);

  // 处理收藏删除
  const handleFavoriteDelete = useCallback((favoriteId: string) => {
    // 如果删除的是当前选中的收藏，清除选择
    if (selectedFavorite?.id === favoriteId) {
      setSelectedFavorite(null);
      setSearchResults(null);
    }
  }, [selectedFavorite]);

  // 返回收藏列表
  const handleBackToList = useCallback(() => {
    setSelectedFavorite(null);
    setSearchResults(null);
    setSearchError(null);
  }, []);

  return (
    <div className="h-full flex flex-col">
      {/* 页面标题 */}
      <div className="page-header flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          {selectedFavorite && (
            <button
              onClick={handleBackToList}
              className="p-2 text-gray-500 hover:text-gray-700 rounded-lg hover:bg-gray-100 transition-colors"
            >
              <ArrowLeft className="w-5 h-5" />
            </button>
          )}
          <div className="w-12 h-12 bg-gradient-to-br from-red-500 to-pink-600 rounded-xl flex items-center justify-center shadow-lg">
            <Heart className="w-6 h-6 text-white fill-current" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-red-600 bg-clip-text text-transparent">
              {selectedFavorite ? '素材检索' : '收藏管理'}
            </h1>
            <p className="text-gray-600 text-lg">
              {selectedFavorite 
                ? `基于"${OutfitFavoriteService.getDisplayName(selectedFavorite)}"的素材检索`
                : '管理您收藏的穿搭方案'
              }
            </p>
          </div>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="flex-1 min-h-0">
        {!selectedFavorite ? (
          /* 收藏列表视图 */
          <div className="card p-6 h-full">
            <FavoriteOutfitList
              onFavoriteSelect={handleFavoriteSelect}
              onFavoriteDelete={handleFavoriteDelete}
              className="h-full"
            />
          </div>
        ) : (
          /* 素材检索结果视图 */
          <div className="h-full flex flex-col">
            {/* 方案信息卡片 */}
            <div className="card p-4 mb-6">
              <div className="flex items-start gap-4">
                <div className="w-12 h-12 bg-gradient-to-br from-red-500 to-pink-600 rounded-xl flex items-center justify-center shadow-lg flex-shrink-0">
                  <Heart className="w-6 h-6 text-white fill-current" />
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="text-lg font-semibold text-gray-900 mb-1">
                    {OutfitFavoriteService.getDisplayName(selectedFavorite)}
                  </h3>
                  <p className="text-gray-600 text-sm mb-2">
                    {OutfitFavoriteService.getDescription(selectedFavorite)}
                  </p>
                  <div className="flex flex-wrap gap-1">
                    {OutfitFavoriteService.getStyleTags(selectedFavorite).slice(0, 3).map((tag, index) => (
                      <span
                        key={index}
                        className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full"
                      >
                        {tag}
                      </span>
                    ))}
                    {OutfitFavoriteService.getOccasions(selectedFavorite).slice(0, 2).map((occasion, index) => (
                      <span
                        key={index}
                        className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full"
                      >
                        {occasion}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* 检索结果 */}
            <div className="card p-6 flex-1 min-h-0">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-semibold text-gray-900">检索结果</h2>
                {searchResults && (
                  <span className="text-sm text-gray-500">
                    找到 {searchResults.total_size} 个结果
                  </span>
                )}
              </div>

              {isSearching ? (
                <div className="flex items-center justify-center py-12">
                  <Search className="w-8 h-8 text-primary-500 animate-pulse" />
                  <span className="ml-3 text-gray-600">正在检索素材...</span>
                </div>
              ) : searchError ? (
                <div className="text-center py-12">
                  <p className="text-red-600 mb-4">{searchError}</p>
                  <button
                    onClick={() => handleFavoriteSelect(selectedFavorite)}
                    className="px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-colors"
                  >
                    重新检索
                  </button>
                </div>
              ) : searchResults ? (
                <div className="h-full overflow-y-auto">
                  {searchResults.results.length > 0 ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {searchResults.results.map((result: any, index: number) => (
                        <div key={result.id || index} className="card p-4 hover:shadow-lg transition-shadow">
                          <img
                            src={result.image_url}
                            alt="Material"
                            className="w-full h-48 object-cover rounded-lg mb-3"
                            onError={(e) => {
                              e.currentTarget.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgdmlld0JveD0iMCAwIDIwMCAyMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIyMDAiIGhlaWdodD0iMjAwIiBmaWxsPSIjRjNGNEY2Ii8+CjxwYXRoIGQ9Ik0xMDAgNzBMMTMwIDEwMEgxMTBWMTMwSDkwVjEwMEg3MEwxMDAgNzBaIiBmaWxsPSIjOUI5QkEwIi8+Cjx0ZXh0IHg9IjEwMCIgeT0iMTUwIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjOUI5QkEwIiBmb250LXNpemU9IjEyIj7lm77niYfliKDpmaTlpLHotKU8L3RleHQ+Cjwvc3ZnPg==';
                            }}
                          />
                          <div className="space-y-2">
                            <p className="text-sm text-gray-600 line-clamp-2">
                              {result.style_description}
                            </p>
                            <div className="flex flex-wrap gap-1">
                              {result.environment_tags?.slice(0, 3).map((tag: string, i: number) => (
                                <span key={i} className="px-2 py-1 bg-gray-100 text-xs rounded-full">
                                  {tag}
                                </span>
                              ))}
                            </div>
                            {result.relevance_score && (
                              <div className="text-xs text-gray-500">
                                相关度: {(result.relevance_score * 100).toFixed(1)}%
                              </div>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-center py-12">
                      <Search className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                      <p className="text-gray-500">没有找到相关素材</p>
                    </div>
                  )}
                </div>
              ) : null}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default OutfitFavoritesTool;
