import React, { useState, useCallback, useEffect } from 'react';
import {
  Search,
  X,
  Loader2,
  Sparkles,
  RefreshCw,
  AlertCircle,
  Settings,
} from 'lucide-react';
import { MaterialSearchPanelProps, MaterialSearchResponse } from '../../types/outfitRecommendation';
import MaterialSearchService from '../../services/materialSearchService';
import { MaterialSearchResults } from './index';
import { EmptyState } from '../EmptyState';

/**
 * 素材检索面板组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const MaterialSearchPanel: React.FC<MaterialSearchPanelProps> = ({
  recommendation,
  isVisible,
  onClose,
  onMaterialSelect,
  className = '',
}) => {
  // 状态管理
  const [searchResponse, setSearchResponse] = useState<MaterialSearchResponse | null>(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(9);
  const [searchQuery, setSearchQuery] = useState('');
  const [showAdvanced, setShowAdvanced] = useState(false);

  // 生成并执行检索
  const handleGenerateAndSearch = useCallback(async () => {
    if (!recommendation) return;

    setIsGenerating(true);
    setError(null);

    try {
      const result = await MaterialSearchService.generateAndSearch(
        recommendation,
        currentPage,
        pageSize,
        {
          include_colors: true,
          include_styles: true,
          include_occasions: true,
          include_seasons: false,
        }
      );

      setSearchQuery(result.queryResponse.query);
      setSearchResponse(result.searchResponse);
    } catch (err) {
      console.error('生成并检索失败:', err);
      setError(err instanceof Error ? err.message : '生成并检索失败');
    } finally {
      setIsGenerating(false);
    }
  }, [recommendation, currentPage, pageSize]);

  // 重新搜索
  const handleRefresh = useCallback(async () => {
    if (!searchQuery || !recommendation) return;

    setIsSearching(true);
    setError(null);

    try {
      const response = await MaterialSearchService.quickSearch(
        recommendation.id,
        searchQuery,
        currentPage,
        pageSize
      );
      setSearchResponse(response);
    } catch (err) {
      console.error('重新搜索失败:', err);
      setError(err instanceof Error ? err.message : '重新搜索失败');
    } finally {
      setIsSearching(false);
    }
  }, [searchQuery, recommendation, currentPage, pageSize]);

  // 页面变化处理
  const handlePageChange = useCallback(async (page: number) => {
    if (!searchQuery || !recommendation) return;

    setCurrentPage(page);
    setIsSearching(true);
    setError(null);

    try {
      const response = await MaterialSearchService.quickSearch(
        recommendation.id,
        searchQuery,
        page,
        pageSize
      );
      setSearchResponse(response);
    } catch (err) {
      console.error('分页搜索失败:', err);
      setError(err instanceof Error ? err.message : '分页搜索失败');
    } finally {
      setIsSearching(false);
    }
  }, [searchQuery, recommendation, pageSize]);

  // 关闭面板
  const handleClose = useCallback(() => {
    setSearchResponse(null);
    setSearchQuery('');
    setCurrentPage(1);
    setError(null);
    onClose();
  }, [onClose]);

  // 初始化时自动生成检索条件
  useEffect(() => {
    if (isVisible && recommendation && !searchResponse && !isGenerating) {
      handleGenerateAndSearch();
    }
  }, [isVisible, recommendation, searchResponse, isGenerating, handleGenerateAndSearch]);

  if (!isVisible) {
    return null;
  }

  return (
    <div className={`fixed inset-0 z-50 bg-black/50 backdrop-blur-sm animate-fade-in ${className}`}>
      <div className="flex items-center justify-center min-h-screen p-4">
        <div className="bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col animate-fade-in-up">
          {/* 头部 */}
          <div className="flex items-center justify-between p-6 border-b border-gray-200 bg-gradient-to-r from-primary-50 to-blue-50">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-gradient-to-br from-primary-500 to-blue-500 rounded-xl flex items-center justify-center shadow-lg">
                <Search className="w-5 h-5 text-white" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-gray-900">素材库检索</h2>
                <p className="text-sm text-gray-600">
                  为"{recommendation.title}"查找合适的素材
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <button
                onClick={() => setShowAdvanced(!showAdvanced)}
                className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors duration-200 ${
                  showAdvanced 
                    ? 'text-primary-600 bg-primary-50' 
                    : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100'
                }`}
                title="高级设置"
              >
                <Settings className="w-4 h-4" />
              </button>
              
              <button
                onClick={handleRefresh}
                disabled={!searchQuery || isSearching}
                className="flex items-center gap-2 px-3 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                title="刷新结果"
              >
                <RefreshCw className={`w-4 h-4 ${isSearching ? 'animate-spin' : ''}`} />
              </button>

              <button
                onClick={handleClose}
                className="flex items-center gap-2 px-3 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors duration-200"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>

          {/* 搜索信息 */}
          {searchQuery && (
            <div className="px-6 py-3 bg-blue-50 border-b border-blue-100">
              <div className="flex items-center gap-2 text-sm text-blue-800">
                <Sparkles className="w-4 h-4" />
                <span className="font-medium">检索条件:</span>
                <span className="bg-blue-100 px-2 py-1 rounded text-xs font-mono">
                  {searchQuery}
                </span>
              </div>
            </div>
          )}

          {/* 高级设置面板 */}
          {showAdvanced && (
            <div className="px-6 py-4 bg-gray-50 border-b border-gray-200">
              <div className="space-y-4">
                <h4 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
                  <Settings className="w-4 h-4" />
                  高级搜索设置
                </h4>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* 相关性阈值 */}
                  <div>
                    <label className="block text-xs font-medium text-gray-700 mb-2">
                      相关性阈值
                    </label>
                    <select className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                      <option value="HIGH">高 (推荐)</option>
                      <option value="MEDIUM">中等</option>
                      <option value="LOW">低</option>
                      <option value="LOWEST">最低</option>
                    </select>
                  </div>

                  {/* 最大结果数量 */}
                  <div>
                    <label className="block text-xs font-medium text-gray-700 mb-2">
                      最大结果数量
                    </label>
                    <select className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                      <option value="20">20 个</option>
                      <option value="50">50 个 (推荐)</option>
                      <option value="100">100 个</option>
                    </select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {/* 生成选项 */}
                  <div>
                    <label className="block text-xs font-medium text-gray-700 mb-2">
                      包含信息
                    </label>
                    <div className="space-y-2">
                      <label className="flex items-center gap-2">
                        <input type="checkbox" defaultChecked className="rounded border-gray-300 text-primary-600 focus:ring-primary-500" />
                        <span className="text-xs text-gray-600">颜色信息</span>
                      </label>
                      <label className="flex items-center gap-2">
                        <input type="checkbox" defaultChecked className="rounded border-gray-300 text-primary-600 focus:ring-primary-500" />
                        <span className="text-xs text-gray-600">风格信息</span>
                      </label>
                      <label className="flex items-center gap-2">
                        <input type="checkbox" defaultChecked className="rounded border-gray-300 text-primary-600 focus:ring-primary-500" />
                        <span className="text-xs text-gray-600">场合信息</span>
                      </label>
                    </div>
                  </div>

                  {/* 环境过滤 */}
                  <div>
                    <label className="block text-xs font-medium text-gray-700 mb-2">
                      环境标签
                    </label>
                    <div className="flex flex-wrap gap-1">
                      {['室内', '户外', '办公室', '聚会', '约会'].map((tag) => (
                        <button
                          key={tag}
                          className="px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded transition-colors duration-200"
                        >
                          {tag}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* 类别过滤 */}
                  <div>
                    <label className="block text-xs font-medium text-gray-700 mb-2">
                      服装类别
                    </label>
                    <div className="flex flex-wrap gap-1">
                      {['上衣', '下装', '外套', '鞋子', '配饰'].map((category) => (
                        <button
                          key={category}
                          className="px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded transition-colors duration-200"
                        >
                          {category}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>

                <div className="flex items-center justify-between pt-3 border-t border-gray-200">
                  <button className="text-xs text-gray-500 hover:text-gray-700">
                    重置为默认设置
                  </button>
                  <button className="px-3 py-1 bg-primary-500 text-white rounded text-xs hover:bg-primary-600 transition-colors duration-200">
                    应用设置
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* 主要内容 */}
          <div className="flex-1 overflow-y-auto min-h-0">
            {/* 错误状态 */}
            {error && (
              <div className="p-6">
                <div className="flex items-center gap-3 p-4 bg-red-50 border border-red-200 rounded-lg">
                  <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
                  <div>
                    <p className="text-sm font-medium text-red-800">检索失败</p>
                    <p className="text-sm text-red-600">{error}</p>
                  </div>
                  <button
                    onClick={handleGenerateAndSearch}
                    className="ml-auto px-3 py-1 bg-red-100 hover:bg-red-200 text-red-700 rounded text-sm transition-colors duration-200"
                  >
                    重试
                  </button>
                </div>
              </div>
            )}

            {/* 生成中状态 */}
            {isGenerating && (
              <div className="p-6">
                <EmptyState
                  variant="default"
                  icon={<Loader2 className="w-12 h-12 text-primary-500 animate-spin" />}
                  title="正在生成检索条件..."
                  description="AI正在分析穿搭方案，为您生成最佳的素材检索条件"
                  size="md"
                  className="py-12"
                />
              </div>
            )}

            {/* 搜索结果 */}
            {searchResponse && !isGenerating && (
              <div className="flex-1 min-h-0 overflow-y-auto">
                <MaterialSearchResults
                  results={searchResponse.results}
                  totalSize={searchResponse.total_size}
                  currentPage={searchResponse.current_page}
                  pageSize={searchResponse.page_size}
                  isLoading={isSearching}
                  error={error || undefined}
                  onPageChange={handlePageChange}
                  onMaterialSelect={onMaterialSelect}
                  className="p-6"
                />
              </div>
            )}

            {/* 空状态 */}
            {!searchResponse && !isGenerating && !error && (
              <div className="p-6">
                <EmptyState
                  variant="default"
                  icon={<Search className="w-12 h-12 text-gray-400" />}
                  title="准备开始检索"
                  description="点击生成按钮开始为您的穿搭方案检索合适的素材"
                  actionText="生成检索条件"
                  onAction={handleGenerateAndSearch}
                  size="md"
                  className="py-12"
                />
              </div>
            )}
          </div>

          {/* 底部操作栏 */}
          <div className="flex items-center justify-between p-6 border-t border-gray-200 bg-gray-50">
            <div className="text-sm text-gray-600">
              {searchResponse && (
                <span>
                  找到 {searchResponse.total_size} 个素材，
                  用时 {MaterialSearchService.formatSearchTime(searchResponse.search_time_ms)}
                </span>
              )}
            </div>
            
            <div className="flex items-center gap-3">
              <button
                onClick={handleGenerateAndSearch}
                disabled={isGenerating || isSearching}
                className="flex items-center gap-2 px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isGenerating ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    生成中...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4" />
                    重新生成
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MaterialSearchPanel;
