import React from 'react';
import { OutfitAnalysisResult } from '../../types/outfitSearch';
import { ColorUtils } from '../../utils/colorUtils';
import { Tag, MapPin, Sparkles, X, Palette } from 'lucide-react';

/**
 * 从可能不完整的JSON字符串中提取风格描述
 */
const extractStyleDescription = (styleDesc: string | undefined): string => {
  if (!styleDesc) return '';

  // 如果是完整的描述文本，直接返回
  if (!styleDesc.includes('```json') && !styleDesc.includes('{')) {
    return styleDesc;
  }

  try {
    // 尝试从JSON字符串中提取信息
    let jsonStr = styleDesc;

    // 移除markdown标记
    if (jsonStr.includes('```json')) {
      jsonStr = jsonStr.replace(/```json\s*/, '').replace(/```.*$/, '');
    }

    // 尝试解析JSON
    const parsed = JSON.parse(jsonStr);

    // 构建描述文本
    const parts = [];
    if (parsed.environment_tags && parsed.environment_tags.length > 0) {
      parts.push(`环境：${parsed.environment_tags.join('、')}`);
    }
    if (parsed.style_description) {
      parts.push(parsed.style_description);
    }

    return parts.join('，') || '已识别服装风格特征';
  } catch (error) {
    // JSON解析失败，尝试提取可读文本
    const cleanText = styleDesc
      .replace(/```json\s*/, '')
      .replace(/```.*$/, '')
      .replace(/[{}"\[\]]/g, '')
      .replace(/\s+/g, ' ')
      .trim();

    return cleanText || '已完成图像分析';
  }
};

interface AnalysisResultsPanelProps {
  analysisResult: OutfitAnalysisResult | null;
  onClearAnalysis: () => void;
}

/**
 * 图像分析结果面板组件
 * 显示分析结果并作为筛选条件的可视化展示
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const AnalysisResultsPanel: React.FC<AnalysisResultsPanelProps> = ({
  analysisResult,
  onClearAnalysis,
}) => {
  if (!analysisResult) return null;

  // 处理不完整的分析结果
  const processedResult = {
    ...analysisResult,
    style_description: extractStyleDescription(analysisResult.style_description),
    products: analysisResult.products || [],
    environment_tags: analysisResult.environment_tags || [],
  };

  // 检查是否有有效的分析内容
  const hasValidContent =
    processedResult.style_description ||
    processedResult.products.length > 0 ||
    processedResult.environment_tags.length > 0;

  if (!hasValidContent) return null;

  return (
    <div className="analysis-results-panel">
      <div className="panel-header">
        <div className="flex items-center gap-2">
          <div className="icon-container primary w-8 h-8">
            <Sparkles className="w-4 h-4" />
          </div>
          <h3 className="panel-title">AI分析结果已应用为筛选条件</h3>
        </div>
        <button
          onClick={onClearAnalysis}
          className="clear-button"
          title="清除分析结果"
        >
          <X className="w-4 h-4" />
        </button>
      </div>

      <div className="analysis-content">
        {/* 风格描述 */}
        {processedResult.style_description && (
          <div className="analysis-item">
            <div className="item-header">
              <Sparkles className="w-4 h-4 text-purple-500" />
              <span className="item-label">分析结果</span>
            </div>
            <p className="style-description">{processedResult.style_description}</p>
          </div>
        )}

        {/* 颜色信息 */}
        {(analysisResult.dress_color_pattern || analysisResult.environment_color_pattern) && (
          <div className="analysis-item">
            <div className="item-header">
              <Palette className="w-4 h-4 text-pink-500" />
              <span className="item-label">颜色分析</span>
            </div>
            <div className="color-analysis">
              {analysisResult.dress_color_pattern && (
                <div className="color-item">
                  <span className="color-label">服装主色调：</span>
                  <div
                    className="color-preview"
                    style={{ backgroundColor: ColorUtils.hsvToHex(analysisResult.dress_color_pattern) }}
                    title={`HSV: ${JSON.stringify(analysisResult.dress_color_pattern)}`}
                  />
                </div>
              )}
              {analysisResult.environment_color_pattern && (
                <div className="color-item">
                  <span className="color-label">环境色调：</span>
                  <div
                    className="color-preview"
                    style={{ backgroundColor: ColorUtils.hsvToHex(analysisResult.environment_color_pattern) }}
                    title={`HSV: ${JSON.stringify(analysisResult.environment_color_pattern)}`}
                  />
                </div>
              )}
            </div>
          </div>
        )}

        {/* 环境标签 */}
        {processedResult.environment_tags.length > 0 && !processedResult.environment_tags.includes('Unknown') && (
          <div className="analysis-item">
            <div className="item-header">
              <MapPin className="w-4 h-4 text-green-500" />
              <span className="item-label">环境场景</span>
            </div>
            <div className="tags-container">
              {processedResult.environment_tags.map((tag, index) => (
                <span key={index} className="tag environment-tag">
                  {tag}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* 服装单品 */}
        {processedResult.products.length > 0 && (
          <div className="analysis-item">
            <div className="item-header">
              <Tag className="w-4 h-4 text-blue-500" />
              <span className="item-label">识别的服装单品</span>
            </div>
            <div className="products-grid">
              {processedResult.products.map((product, index) => (
                <div key={index} className="product-card">
                  <div className="product-header">
                    <span className="product-category">{product.category}</span>
                    {product.color_pattern && (
                      <div
                        className="color-preview"
                        style={{ backgroundColor: ColorUtils.hsvToHex(product.color_pattern) }}
                        title={`颜色: ${ColorUtils.hsvToHex(product.color_pattern)}`}
                      />
                    )}
                  </div>
                  <p className="product-description">{product.description}</p>
                  {product.design_styles && product.design_styles.length > 0 && (
                    <div className="design-styles">
                      {product.design_styles.map((style, styleIndex) => (
                        <span key={styleIndex} className="tag style-tag">
                          {style}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      <style>{`
        .analysis-results-panel {
          background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
          border: 1px solid #cbd5e1;
          border-radius: 12px;
          padding: 16px;
          margin-bottom: 20px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .panel-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          padding-bottom: 12px;
          border-bottom: 1px solid #e2e8f0;
        }

        .panel-title {
          font-size: 14px;
          font-weight: 600;
          color: #334155;
          margin: 0;
        }

        .clear-button {
          padding: 6px;
          background: #ef4444;
          color: white;
          border: none;
          border-radius: 6px;
          cursor: pointer;
          transition: all 0.2s;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .clear-button:hover {
          background: #dc2626;
          transform: scale(1.05);
        }

        .analysis-content {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }

        .analysis-item {
          background: white;
          border-radius: 8px;
          padding: 12px;
          border: 1px solid #e2e8f0;
        }

        .item-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
        }

        .item-label {
          font-size: 13px;
          font-weight: 600;
          color: #475569;
        }

        .style-description {
          font-size: 14px;
          color: #64748b;
          margin: 0;
          line-height: 1.5;
        }

        .tags-container {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
        }

        .tag {
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 12px;
          font-weight: 500;
        }

        .environment-tag {
          background: #dcfce7;
          color: #166534;
          border: 1px solid #bbf7d0;
        }

        .style-tag {
          background: #dbeafe;
          color: #1e40af;
          border: 1px solid #bfdbfe;
        }

        .products-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 12px;
        }

        .product-card {
          background: #f8fafc;
          border: 1px solid #e2e8f0;
          border-radius: 8px;
          padding: 12px;
        }

        .product-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
        }

        .product-category {
          font-size: 13px;
          font-weight: 600;
          color: #475569;
        }

        .color-preview {
          width: 20px;
          height: 20px;
          border-radius: 4px;
          border: 1px solid #e2e8f0;
          cursor: pointer;
        }

        .product-description {
          font-size: 12px;
          color: #64748b;
          margin: 0 0 8px 0;
          line-height: 1.4;
        }

        .design-styles {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
        }

        .color-analysis {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .color-item {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .color-label {
          font-size: 13px;
          font-weight: 500;
          color: #475569;
          min-width: 80px;
        }

        @media (max-width: 640px) {
          .products-grid {
            grid-template-columns: 1fr;
          }

          .panel-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
          }

          .color-analysis {
            gap: 8px;
          }

          .color-item {
            flex-direction: column;
            align-items: flex-start;
            gap: 4px;
          }

          .color-label {
            min-width: auto;
          }
        }
      `}</style>
    </div>
  );
};

export default AnalysisResultsPanel;
