import React, { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { convertFileSrc } from '@tauri-apps/api/core';
import { SimpleAnalysisDisplay } from '../../components/outfit/SimpleAnalysisDisplay';
import { Upload, Loader2, AlertCircle, Image } from 'lucide-react';
import { AnalyzeImageResponse } from '../../types/outfitSearch';

/**
 * 丰富分析结果演示页面
 * 展示如何使用丰富的图像分析功能
 */
export const EnrichedAnalysisDemo: React.FC = () => {
  const [selectedImagePath, setSelectedImagePath] = useState<string | null>(null);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysisResult, setAnalysisResult] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  // 选择图片文件
  const handleSelectImage = async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [
          {
            name: '图片文件',
            extensions: ['jpg', 'jpeg', 'png', 'webp', 'bmp']
          }
        ]
      });

      if (selected && typeof selected === 'string') {
        setSelectedImagePath(selected);
        setError(null);
        setAnalysisResult(null);
      }
    } catch (err) {
      console.error('选择图片失败:', err);
      setError('选择图片失败: ' + (err as Error).message);
    }
  };

  // 分析图片
  const handleAnalyze = async () => {
    if (!selectedImagePath) {
      setError('请先选择一张图片');
      return;
    }

    setIsAnalyzing(true);
    setError(null);

    try {
      console.log('开始分析图片:', selectedImagePath);

      // 1. 首先调用图片分析API
      const imageName = selectedImagePath.split(/[/\\]/).pop() || 'unknown.jpg';
      const analysisResponse: AnalyzeImageResponse = await invoke('analyze_outfit_image', {
        request: {
          image_path: selectedImagePath,
          image_name: imageName
        }
      });

      console.log('图片分析完成:', analysisResponse);
      setAnalysisResult(analysisResponse.result);

    } catch (err) {
      console.error('分析失败:', err);
      setError('分析失败: ' + (err as Error).message);
    } finally {
      setIsAnalyzing(false);
    }
  };

  // 清除结果
  const handleClearResults = () => {
    setSelectedImagePath(null);
    setAnalysisResult(null);
    setError(null);
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            🎨 AI 服装分析演示
          </h1>
          <p className="text-gray-600">
            使用真实的AI引擎分析服装搭配图片，获得详细的风格解读和色彩分析
          </p>
        </div>

        {/* 操作区域 */}
        <div className="bg-white rounded-lg shadow-lg p-6 mb-8">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 图片选择 */}
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">选择图片</h3>
              <div className="space-y-4">
                <button
                  onClick={handleSelectImage}
                  className="w-full border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors cursor-pointer"
                >
                  <Upload className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                  <p className="text-gray-600">点击选择图片文件</p>
                  <p className="text-sm text-gray-400 mt-1">支持 JPG, PNG, WebP, BMP 格式</p>
                </button>

                {selectedImagePath && (
                  <div className="bg-gray-50 p-4 rounded-lg">
                    <p className="text-sm text-gray-600 mb-2">已选择文件:</p>
                    <p className="text-sm font-mono text-gray-800 break-all">{selectedImagePath}</p>
                  </div>
                )}

                {selectedImagePath && (
                  <div className="mt-4">
                    <img
                      src={convertFileSrc(selectedImagePath)}
                      alt="Selected"
                      className="w-full h-48 object-cover rounded-lg"
                      onError={() => {
                        console.log('图片预览加载失败:', selectedImagePath);
                        setError('图片预览加载失败，请重新选择图片');
                      }}
                    />
                  </div>
                )}
              </div>
            </div>

            {/* 操作按钮 */}
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">分析操作</h3>
              <div className="space-y-4">
                <button
                  onClick={handleAnalyze}
                  disabled={!selectedImagePath || isAnalyzing}
                  className="w-full btn-primary flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isAnalyzing ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      分析中...
                    </>
                  ) : (
                    <>
                      <Image className="w-4 h-4" />
                      分析图片
                    </>
                  )}
                </button>

                {(selectedImagePath || analysisResult) && (
                  <button
                    onClick={handleClearResults}
                    disabled={isAnalyzing}
                    className="w-full btn-secondary flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <AlertCircle className="w-4 h-4" />
                    清除结果
                  </button>
                )}

                {analysisResult && !isAnalyzing && (
                  <div className="bg-green-50 p-4 rounded-lg">
                    <h4 className="font-medium text-green-900 mb-2">✅ 分析完成</h4>
                    <p className="text-sm text-green-800">
                      图片分析已完成，请查看下方的详细分析结果
                    </p>
                  </div>
                )}

                <div className="bg-blue-50 p-4 rounded-lg">
                  <h4 className="font-medium text-blue-900 mb-2">💡 功能说明</h4>
                  <ul className="text-sm text-blue-800 space-y-1">
                    <li>• 使用真实的AI图像分析引擎</li>
                    <li>• 详细的颜色分析和色彩和谐度评估</li>
                    <li>• 风格一致性和复杂度分析</li>
                    <li>• 产品匹配度统计和建议</li>
                    <li>• 环境适配性和拍摄质量评估</li>
                    <li>• 个性化搭配建议和场合推荐</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="mt-6 bg-red-50 border border-red-200 rounded-lg p-4">
              <div className="flex items-center gap-2">
                <AlertCircle className="w-5 h-5 text-red-500" />
                <span className="text-red-800 font-medium">分析失败</span>
              </div>
              <p className="text-red-700 mt-1">{error}</p>
            </div>
          )}
        </div>

        {/* 分析结果展示 */}
        {analysisResult && (
          <SimpleAnalysisDisplay analysisResult={analysisResult} />
        )}

        {/* 使用说明 */}
        {!analysisResult && (
          <div className="bg-white rounded-lg shadow-lg p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">📖 使用说明</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <h4 className="font-medium text-gray-900 mb-2">操作步骤</h4>
                <ol className="text-sm text-gray-600 space-y-1">
                  <li>1. 点击"选择图片文件"按钮</li>
                  <li>2. 选择一张服装搭配图片</li>
                  <li>3. 点击"分析图片"开始AI分析</li>
                  <li>4. 等待分析完成，查看丰富的分析报告</li>
                  <li>5. 展开各个分析区域查看详细信息</li>
                </ol>
              </div>
              <div>
                <h4 className="font-medium text-gray-900 mb-2">分析内容</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>• 真实AI引擎驱动的图像分析</li>
                  <li>• 服装颜色和环境色彩分析</li>
                  <li>• 色彩和谐度和温度匹配</li>
                  <li>• 风格标签识别和一致性评估</li>
                  <li>• 产品类别统计和匹配度分析</li>
                  <li>• 环境类型和拍摄质量评估</li>
                </ul>
              </div>
            </div>

            <div className="mt-6 bg-yellow-50 p-4 rounded-lg">
              <h4 className="font-medium text-yellow-900 mb-2">⚠️ 注意事项</h4>
              <ul className="text-sm text-yellow-800 space-y-1">
                <li>• 请选择清晰的服装搭配图片以获得最佳分析效果</li>
                <li>• 支持的格式：JPG、PNG、WebP、BMP</li>
                <li>• 分析过程可能需要几秒钟时间，请耐心等待</li>
                <li>• 分析结果基于AI模型，仅供参考</li>
              </ul>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
