/**
 * 穿搭照片生成页面
 * 集成 ComfyUI 工作流的穿搭照片生成功能
 */

import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  ArrowLeft,
  Sparkles,
  History,
  Settings,
  AlertCircle,
  CheckCircle,
  User
} from 'lucide-react';
import { OutfitPhotoGenerator } from '../components/outfit/OutfitPhotoGenerator';
import { OutfitPhotoGenerationHistory } from '../components/outfit/OutfitPhotoGenerationHistory';
import { ComfyUISettingsPanel } from '../components/outfit/ComfyUISettingsPanel';
import { LoadingSpinner } from '../components/LoadingSpinner';
import { TabNavigation } from '../components/TabNavigation';
import type { Model } from '../types/model';
import type { OutfitPhotoGenerationResponse, ComfyUISettings } from '../types/outfitPhotoGeneration';
import { modelService } from '../services/modelService';
import { OutfitPhotoGenerationService } from '../services/outfitPhotoGenerationService';

interface OutfitPhotoGenerationPageProps {
  projectId?: string;
  modelId?: string;
}

const TABS = [
  { id: 'generator', label: '生成器', icon: Sparkles },
  { id: 'history', label: '历史记录', icon: History },
  { id: 'settings', label: '设置', icon: Settings }
];

export const OutfitPhotoGenerationPage: React.FC<OutfitPhotoGenerationPageProps> = ({
  projectId: propProjectId,
  modelId: propModelId
}) => {
  const { projectId: paramProjectId, modelId: paramModelId } = useParams<{
    projectId?: string;
    modelId?: string;
  }>();
  const navigate = useNavigate();

  // 使用 props 或 URL 参数
  const projectId = propProjectId || paramProjectId;
  const modelId = propModelId || paramModelId;

  // 状态管理
  const [activeTab, setActiveTab] = useState('generator');
  const [model, setModel] = useState<Model | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [comfyUISettings, setComfyUISettings] = useState<ComfyUISettings | null>(null);
  const [connectionStatus, setConnectionStatus] = useState<'unknown' | 'connected' | 'failed'>('unknown');

  // 加载模特信息
  const loadModel = useCallback(async () => {
    if (!modelId) {
      setError('未指定模特ID');
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      
      const modelData = await modelService.getModelById(modelId);
      setModel(modelData);
    } catch (err) {
      console.error('加载模特信息失败:', err);
      setError(err instanceof Error ? err.message : '加载模特信息失败');
    } finally {
      setLoading(false);
    }
  }, [modelId]);

  // 加载 ComfyUI 设置
  const loadComfyUISettings = useCallback(async () => {
    try {
      const settings = await OutfitPhotoGenerationService.getComfyUISettings();
      setComfyUISettings(settings);
      
      // 如果启用了 ComfyUI，测试连接
      if (settings.enabled) {
        const connected = await OutfitPhotoGenerationService.testComfyUIConnection();
        setConnectionStatus(connected ? 'connected' : 'failed');
      }
    } catch (err) {
      console.error('加载 ComfyUI 设置失败:', err);
    }
  }, []);

  // 初始加载
  useEffect(() => {
    loadModel();
    loadComfyUISettings();
  }, [loadModel, loadComfyUISettings]);

  // 处理生成完成
  const handleGenerationComplete = useCallback((response: OutfitPhotoGenerationResponse) => {
    console.log('生成完成:', response);
    // 切换到历史记录标签页查看结果
    setActiveTab('history');
  }, []);

  // 处理重试生成
  const handleRetryGeneration = useCallback((generationId: string) => {
    console.log('重试生成:', generationId);
    // 可以在这里添加重试逻辑或通知
  }, []);

  // 处理设置变更
  const handleSettingsChange = useCallback((settings: ComfyUISettings) => {
    setComfyUISettings(settings);
    // 重新测试连接
    if (settings.enabled) {
      OutfitPhotoGenerationService.testComfyUIConnection().then(connected => {
        setConnectionStatus(connected ? 'connected' : 'failed');
      });
    } else {
      setConnectionStatus('unknown');
    }
  }, []);

  // 返回上一页
  const handleGoBack = useCallback(() => {
    if (projectId) {
      navigate(`/projects/${projectId}`);
    } else if (modelId) {
      navigate(`/models/${modelId}`);
    } else {
      navigate('/models');
    }
  }, [navigate, projectId, modelId]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <LoadingSpinner size="large" />
          <p className="mt-4 text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-2">加载失败</h2>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={handleGoBack}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            返回
          </button>
        </div>
      </div>
    );
  }

  if (!model) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <User className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-2">模特不存在</h2>
          <p className="text-gray-600 mb-4">未找到指定的模特信息</p>
          <button
            onClick={handleGoBack}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            返回
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 头部导航 */}
      <div className="bg-white border-b border-gray-200 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center gap-4">
              <button
                onClick={handleGoBack}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <ArrowLeft className="w-5 h-5" />
              </button>
              
              <div>
                <h1 className="text-xl font-semibold text-gray-900 flex items-center gap-2">
                  <Sparkles className="w-6 h-6 text-purple-500" />
                  穿搭照片生成
                </h1>
                <p className="text-sm text-gray-600">
                  模特: {model.name}
                  {projectId && ` • 项目: ${projectId}`}
                </p>
              </div>
            </div>

            {/* 连接状态指示器 */}
            <div className="flex items-center gap-2">
              {comfyUISettings?.enabled && (
                <div className={`flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${
                  connectionStatus === 'connected'
                    ? 'text-green-700 bg-green-100'
                    : connectionStatus === 'failed'
                    ? 'text-red-700 bg-red-100'
                    : 'text-gray-700 bg-gray-100'
                }`}>
                  {connectionStatus === 'connected' ? (
                    <>
                      <CheckCircle className="w-3 h-3" />
                      ComfyUI 已连接
                    </>
                  ) : connectionStatus === 'failed' ? (
                    <>
                      <AlertCircle className="w-3 h-3" />
                      ComfyUI 连接失败
                    </>
                  ) : (
                    <>
                      <AlertCircle className="w-3 h-3" />
                      ComfyUI 状态未知
                    </>
                  )}
                </div>
              )}
              
              {!comfyUISettings?.enabled && (
                <div className="flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium text-orange-700 bg-orange-100">
                  <AlertCircle className="w-3 h-3" />
                  ComfyUI 未启用
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 标签页导航 */}
        <div className="mb-6">
          <TabNavigation
            tabs={TABS}
            activeTab={activeTab}
            onTabChange={setActiveTab}
          />
        </div>

        {/* 标签页内容 */}
        <div className="space-y-6">
          {activeTab === 'generator' && (
            <div>
              {!comfyUISettings?.enabled ? (
                <div className="bg-orange-50 border border-orange-200 rounded-lg p-6 text-center">
                  <AlertCircle className="w-12 h-12 text-orange-500 mx-auto mb-4" />
                  <h3 className="text-lg font-semibold text-orange-900 mb-2">ComfyUI 未启用</h3>
                  <p className="text-orange-700 mb-4">
                    请先在设置页面启用并配置 ComfyUI 服务器连接
                  </p>
                  <button
                    onClick={() => setActiveTab('settings')}
                    className="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors"
                  >
                    前往设置
                  </button>
                </div>
              ) : connectionStatus === 'failed' ? (
                <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
                  <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
                  <h3 className="text-lg font-semibold text-red-900 mb-2">ComfyUI 连接失败</h3>
                  <p className="text-red-700 mb-4">
                    无法连接到 ComfyUI 服务器，请检查服务器状态和网络连接
                  </p>
                  <button
                    onClick={() => setActiveTab('settings')}
                    className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                  >
                    检查设置
                  </button>
                </div>
              ) : (
                <OutfitPhotoGenerator
                  projectId={projectId || ''}
                  modelId={modelId || ''}
                  modelPhotos={model.photos || []}
                  onGenerationComplete={handleGenerationComplete}
                  disabled={connectionStatus !== 'connected'}
                />
              )}
            </div>
          )}

          {activeTab === 'history' && (
            <OutfitPhotoGenerationHistory
              projectId={projectId}
              modelId={modelId}
              onRetryGeneration={handleRetryGeneration}
            />
          )}

          {activeTab === 'settings' && (
            <ComfyUISettingsPanel
              onSettingsChange={handleSettingsChange}
            />
          )}
        </div>
      </div>
    </div>
  );
};
