import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ExclamationTriangleIcon, UserIcon } from '@heroicons/react/24/outline';
import { Model, ModelPhoto, PhotoType, ModelDynamic } from '../types/model';
import {
  VideoGenerationTask,
  VideoPromptConfig
} from '../types/videoGeneration';
import { videoGenerationService } from '../services/videoGenerationService';

import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { LoadingSpinner } from '../components/LoadingSpinner';
import { DeleteConfirmDialog } from '../components/DeleteConfirmDialog';
import { OutfitImageService } from '../services/outfitImageService';
import { ModelDashboardStats, OutfitImageRecord, OutfitImageGenerationRequest } from '../types/outfitImage';
import { ModelImageGallery } from '../components/ModelImageGallery';
import { OutfitImageGenerationModal } from '../components/OutfitImageGenerationModal';
import { ModelImageUploadModal } from '../components/ModelImageUploadModal';
import { OutfitImageGallery } from '../components/OutfitImageGallery';
import { ModelDetailHeader } from '../components/model-detail/ModelDetailHeader';
import { ModelDetailTabs, TabId } from '../components/model-detail/ModelDetailTabs';
import { ModelOverviewTab } from '../components/model-detail/ModelOverviewTab';
import { ModelDynamicsTab } from '../components/model-detail/ModelDynamicsTab';
import { ModelVideoTab } from '../components/model-detail/ModelVideoTab';
import { ModelStatsTab } from '../components/model-detail/ModelStatsTab';

const ModelDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  // 状态管理
  const [model, setModel] = useState<Model | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedPhotos, setSelectedPhotos] = useState<string[]>([]);
  const [promptConfig, setPromptConfig] = useState<VideoPromptConfig>({
    product: '',
    scene: '',
    model_desc: '',
    template: '抚媚眼神',
    duplicate: 1
  });
  const [videoTasks, setVideoTasks] = useState<VideoGenerationTask[]>([]);
  const [isGenerating, setIsGenerating] = useState(false);
  const [uploadingPhotos, setUploadingPhotos] = useState(false);
  const [dashboardStats, setDashboardStats] = useState<ModelDashboardStats | null>(null);
  const [statsLoading, setStatsLoading] = useState(false);
  const [outfitRecords, setOutfitRecords] = useState<OutfitImageRecord[]>([]);

  // 分页状态
  const [outfitPage, setOutfitPage] = useState(1);
  const [outfitHasMore, setOutfitHasMore] = useState(false);
  const [outfitLoadingMore, setOutfitLoadingMore] = useState(false);
  const [_outfitTotalCount, setOutfitTotalCount] = useState(0);

  const [generatingOutfit, setGeneratingOutfit] = useState(false);
  const [activeTab, setActiveTab] = useState<TabId>('overview');
  const [dynamics] = useState<ModelDynamic[]>([]);

  // 穿搭图片生成Modal状态
  const [showOutfitModal, setShowOutfitModal] = useState(false);
  const [showUploadModal, setShowUploadModal] = useState(false);


  const [deletePhotoConfirm, setDeletePhotoConfirm] = useState<{
    show: boolean;
    photoId: string | null;
    photoName: string | null;
    deleting: boolean;
  }>({
    show: false,
    photoId: null,
    photoName: null,
    deleting: false,
  });


  // 加载模特详情
  const loadModelDetail = async () => {
    if (!id) return;

    try {
      setLoading(true);
      setError(null);

      const modelData = await videoGenerationService.getModelDetailWithPhotos(id);
      if (modelData) {
        setModel(modelData);
        // 设置默认的模特描述
        setPromptConfig(prev => ({
          ...prev,
          model_desc: modelData.description || `${modelData.name}，${modelData.tags.join('、')}`
        }));
      } else {
        setError('模特不存在');
      }
    } catch (err) {
      setError(err as string);
    } finally {
      setLoading(false);
    }
  };

  // 加载视频生成任务
  const loadVideoTasks = async () => {
    if (!id) return;

    try {
      const tasks = await videoGenerationService.getVideoGenerationTasks({
        model_id: id
      });
      setVideoTasks(tasks);
    } catch (err) {
      console.error('加载视频任务失败:', err);
    }
  };

  // 加载个人看板统计信息
  const loadDashboardStats = async () => {
    if (!id) return;

    try {
      setStatsLoading(true);
      const stats = await OutfitImageService.getModelDashboardStats(id);
      setDashboardStats(stats);
    } catch (err) {
      console.error('加载个人看板统计失败:', err);
    } finally {
      setStatsLoading(false);
    }
  };

  // 批量上传照片（新的图片画廊组件使用）
  const handleBatchUploadPhotos = async (imagePaths: string[], photoType: PhotoType) => {
    if (!id) return;

    try {
      setUploadingPhotos(true);
      const photos = await videoGenerationService.batchUploadModelPhotos(
        id,
        imagePaths,
        photoType,
        '批量上传的照片'
      );

      if (photos && photos.length > 0) {
        // 重新加载模特详情以获取最新的照片列表
        await loadModelDetail();
        await loadDashboardStats(); // 更新统计信息
      }
    } catch (err) {
      console.error('批量上传照片失败:', err);
      setError(err as string);
    } finally {
      setUploadingPhotos(false);
    }
  };

  // 删除照片（新的图片画廊组件使用）
  const handleDeletePhoto = async (photo: ModelPhoto) => {
    if (!id) return;

    try {
      await videoGenerationService.deleteModelPhoto(id, photo.id);
      // 重新加载模特详情以获取最新的照片列表
      await loadModelDetail();
      await loadDashboardStats(); // 更新统计信息
    } catch (err) {
      console.error('删除照片失败:', err);
      setError(err as string);
    }
  };



  // 加载穿搭图片生成记录（首次加载）
  const loadOutfitRecords = async () => {
    if (!id) return;

    try {
      const response = await OutfitImageService.getOutfitImageRecordsPaginated(id, 1, 20);
      setOutfitRecords(response.records);
      setOutfitPage(1);
      setOutfitHasMore(response.has_more);
      setOutfitTotalCount(response.total_count);
    } catch (err) {
      console.error('加载穿搭图片记录失败:', err);
    }
  };

  // 加载更多穿搭图片记录
  const loadMoreOutfitRecords = async () => {
    if (!id || outfitLoadingMore || !outfitHasMore) return;

    try {
      setOutfitLoadingMore(true);
      const nextPage = outfitPage + 1;
      const response = await OutfitImageService.getOutfitImageRecordsPaginated(id, nextPage, 20);

      setOutfitRecords(prev => [...prev, ...response.records]);
      setOutfitPage(nextPage);
      setOutfitHasMore(response.has_more);
      setOutfitTotalCount(response.total_count);
    } catch (err) {
      console.error('加载更多穿搭图片记录失败:', err);
    } finally {
      setOutfitLoadingMore(false);
    }
  };

  // 生成穿搭图片（异步模式）
  const handleGenerateOutfitImages = async (request: OutfitImageGenerationRequest) => {
    try {
      setGeneratingOutfit(true);

      // 创建任务记录
      const recordId = await OutfitImageService.createOutfitImageTask(request);
      console.log('✅ 穿搭图片任务已创建:', recordId);

      // 立即执行后台任务（不等待结果）
      await OutfitImageService.executeOutfitImageTask(recordId);
      console.log('✅ 穿搭图片任务已提交到后台');

      // 立即重新加载记录显示新创建的任务
      await loadOutfitRecords();
      await loadDashboardStats();

      // 关闭弹框，让用户在列表中查看进度
      setShowOutfitModal(false);
    } catch (err) {
      console.error('生成穿搭图片失败:', err);
      setError(err as string);
    } finally {
      setGeneratingOutfit(false);
    }
  };











  // 生成视频
  const handleGenerateVideo = async () => {
    if (!id || selectedPhotos.length === 0) {
      setError('请至少选择一张照片');
      return;
    }

    if (!promptConfig.product.trim() || !promptConfig.scene.trim()) {
      setError('请填写产品描述和场景描述');
      return;
    }

    try {
      setIsGenerating(true);
      setError(null);

      const request = {
        model_id: id,
        prompt_config: promptConfig,
        selected_photos: selectedPhotos
      };

      // 创建并执行任务
      const task = await videoGenerationService.createAndExecuteVideoGeneration(request);

      // 重新加载任务列表
      await loadVideoTasks();

      // 开始轮询任务状态
      videoGenerationService.pollTaskUntilComplete(
        task.id,
        (updatedTask) => {
          // 更新任务列表中的任务状态
          setVideoTasks(prev =>
            prev.map(t => t.id === updatedTask.id ? updatedTask : t)
          );
        }
      ).then(() => {
        // 任务完成后重新加载任务列表
        loadVideoTasks();
      }).catch(err => {
        console.error('轮询任务状态失败:', err);
      });

    } catch (err) {
      setError(`生成视频失败: ${err}`);
    } finally {
      setIsGenerating(false);
    }
  };





  // 确认删除照片
  const confirmDeletePhoto = async () => {
    if (!deletePhotoConfirm.photoId || !id) return;

    setDeletePhotoConfirm(prev => ({ ...prev, deleting: true }));

    try {
      await invoke('delete_model_photo', {
        modelId: id,
        photoId: deletePhotoConfirm.photoId
      });

      // 重新加载模特数据
      await loadModelDetail();

      // 如果删除的照片在选中列表中，移除它
      setSelectedPhotos(prev => prev.filter(selectedId => selectedId !== deletePhotoConfirm.photoId));

      console.log('照片删除成功');

      // 关闭确认弹框
      setDeletePhotoConfirm({
        show: false,
        photoId: null,
        photoName: null,
        deleting: false,
      });
    } catch (err) {
      setError(`删除照片失败: ${err}`);
      setDeletePhotoConfirm(prev => ({ ...prev, deleting: false }));
    }
  };

  // 取消删除照片
  const cancelDeletePhoto = () => {
    setDeletePhotoConfirm({
      show: false,
      photoId: null,
      photoName: null,
      deleting: false,
    });
  };

  // 删除视频任务
  const handleDeleteTask = async (taskId: string) => {
    try {
      await videoGenerationService.deleteVideoGenerationTask(taskId);
      await loadVideoTasks(); // 重新加载任务列表
    } catch (err) {
      console.error('删除任务失败:', err);
      setError(`删除任务失败: ${err}`);
    }
  };

  // 删除穿搭图片记录
  const handleDeleteOutfitRecord = async (record: OutfitImageRecord) => {
    try {
      await OutfitImageService.deleteOutfitImageRecord(record.id);
      // 重新加载记录和统计信息
      await loadOutfitRecords();
      await loadDashboardStats();
    } catch (err) {
      console.error('删除穿搭记录失败:', err);
      setError(`删除穿搭记录失败: ${err}`);
    }
  };

  // 重试穿搭图片生成
  const handleRetryOutfitRecord = async (record: OutfitImageRecord) => {
    try {
      await OutfitImageService.retryOutfitImageGeneration(record.id);
      // 重新加载记录和统计信息
      await loadOutfitRecords();
      await loadDashboardStats();
    } catch (err) {
      console.error('重试穿搭生成失败:', err);
      setError(`重试穿搭生成失败: ${err}`);
    }
  };

  // 批量生成穿搭图片（并发模式）
  const handleBatchGenerateOutfitImages = async (requests: OutfitImageGenerationRequest[]) => {
    try {
      setGeneratingOutfit(true);

      console.log('🚀 开始批量生成穿搭图片:', requests.length, '个任务');

      // 使用批量生成方法（并发执行）
      const recordIds = await OutfitImageService.batchGenerateOutfitImages(requests);
      console.log('✅ 批量穿搭图片任务已创建并提交:', recordIds);

      // 立即重新加载记录显示新创建的任务
      await loadOutfitRecords();
      await loadDashboardStats();

      // 关闭弹框，让用户在列表中查看进度
      setShowOutfitModal(false);
    } catch (err) {
      console.error('批量生成穿搭图片失败:', err);
      setError(err as string);
    } finally {
      setGeneratingOutfit(false);
    }
  };

  // 初始化
  useEffect(() => {
    loadModelDetail();
    loadVideoTasks();
    loadDashboardStats();
    loadOutfitRecords();
  }, [id]);

  // 监听穿搭图片生成事件
  useEffect(() => {
    const setupEventListeners = async () => {
      // 监听生成进度事件
      const unlistenProgress = await listen('outfit_generation_progress', (event) => {
        console.log('收到穿搭图片生成进度事件:', event.payload);
        // 实时更新记录列表显示进度
        loadOutfitRecords();
      });

      // 监听生成完成事件
      const unlistenCompleted = await listen('outfit_generation_completed', (event) => {
        console.log('收到穿搭图片生成完成事件:', event.payload);
        // 重新加载记录和统计信息
        loadOutfitRecords();
        loadDashboardStats();
      });

      // 监听生成失败事件
      const unlistenFailed = await listen('outfit_generation_failed', (event) => {
        console.log('收到穿搭图片生成失败事件:', event.payload);
        // 重新加载记录显示失败状态
        loadOutfitRecords();
      });

      return () => {
        unlistenProgress();
        unlistenCompleted();
        unlistenFailed();
      };
    };

    setupEventListeners();
  }, [loadOutfitRecords, loadDashboardStats]);

  if (loading) {
    return (
      <div className="app-layout">
        <div className="app-main bg-gradient-to-br from-gray-50 via-white to-blue-50">
          <div className="content-container">
            <div className="flex flex-col items-center justify-center h-96 animate-fade-in">
              <div className="loading-shimmer w-16 h-16 rounded-full mb-4"></div>
              <LoadingSpinner size="large" />
              <p className="text-body text-medium-emphasis mt-4">加载模特信息中...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="app-layout">
        <div className="app-main bg-gradient-to-br from-gray-50 via-white to-blue-50">
          <div className="content-container">
            <div className="card content-card error-state animate-fade-in max-w-md mx-auto mt-20">
              <div className="card-body text-center">
                <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <ExclamationTriangleIcon className="w-8 h-8 text-red-600" />
                </div>
                <h3 className="text-heading-5 text-high-emphasis mb-2">加载失败</h3>
                <p className="text-body text-medium-emphasis mb-4">{error}</p>
                <button
                  onClick={() => setError(null)}
                  className="btn btn-secondary"
                >
                  重试
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!model) {
    return (
      <div className="app-layout">
        <div className="app-main bg-gradient-to-br from-gray-50 via-white to-blue-50">
          <div className="content-container">
            <div className="card content-card animate-fade-in max-w-md mx-auto mt-20">
              <div className="card-body text-center">
                <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <UserIcon className="w-8 h-8 text-gray-400" />
                </div>
                <h3 className="text-heading-5 text-high-emphasis mb-2">模特不存在</h3>
                <p className="text-body text-medium-emphasis mb-4">未找到指定的模特信息</p>
                <button
                  onClick={() => navigate('/models')}
                  className="btn btn-primary"
                >
                  返回模特列表
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-blue-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* 页面头部 */}
        <ModelDetailHeader
          model={model}
          uploadingPhotos={uploadingPhotos}
          onOpenUploadModal={() => setShowUploadModal(true)}
        />

        {/* Tab导航 */}
        <ModelDetailTabs
          activeTab={activeTab}
          onTabChange={setActiveTab}
          model={model}
          dynamics={dynamics}
          videoTasks={videoTasks}
          outfitRecords={outfitRecords}
          onOpenOutfitModal={() => setShowOutfitModal(false)}
        />

        {/* Tab内容区域 */}
        <div className="min-h-[600px]">
          {/* 概览选项卡 */}
          {activeTab === 'overview' && (
            <ModelOverviewTab
              model={model}
              dashboardStats={dashboardStats}
              statsLoading={statsLoading}
              videoTasks={videoTasks}
              outfitRecords={outfitRecords}
              onTabChange={setActiveTab}
            />
          )}

          {/* 照片管理选项卡 */}
          {activeTab === 'photos' && (
            <div className="animate-fade-in">
              <ModelImageGallery
                photos={model.photos}
                onUpload={handleBatchUploadPhotos}
                onDelete={handleDeletePhoto}
                isUploading={uploadingPhotos}
              />
            </div>
          )}

          {/* 模特动态选项卡 */}
          {activeTab === 'dynamics' && (
            <ModelDynamicsTab model={model} />
          )}

          {/* 视频生成选项卡 */}
          {activeTab === 'videos' && (
            <ModelVideoTab
              model={model}
              videoTasks={videoTasks}
              selectedPhotos={selectedPhotos}
              promptConfig={promptConfig}
              isGenerating={isGenerating}
              onSelectedPhotosChange={setSelectedPhotos}
              onPromptConfigChange={setPromptConfig}
              onGenerateVideo={handleGenerateVideo}
              onDeleteTask={handleDeleteTask}
              onRefreshTasks={loadVideoTasks}
            />
          )}

          {/* 穿搭生成选项卡 */}
          {activeTab === 'outfits' && (
            <div className="animate-fade-in space-y-6">
              {/* 头部操作区域 */}
              <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-xl flex items-center justify-center">
                      <span className="text-xl">👗</span>
                    </div>
                    <div>
                      <h3 className="text-xl font-bold text-gray-900">AI穿搭图片生成</h3>
                      <p className="text-gray-600">
                        为 {model.name} 生成专业的AI穿搭效果图
                      </p>
                    </div>
                  </div>

                  <button
                    onClick={() => setShowOutfitModal(true)}
                    className="inline-flex items-center px-6 py-3 bg-gradient-to-r from-purple-500 to-pink-500 text-white font-semibold rounded-xl hover:from-purple-600 hover:to-pink-600 transition-all duration-200 shadow-lg hover:shadow-xl"
                  >
                    <span className="text-lg mr-2">✨</span>
                    生成穿搭图片
                  </button>

                </div>

                {/* 统计信息 */}
                {dashboardStats && (
                  <div className="flex gap-6 mt-6 pt-6 border-t border-gray-100">
                    <div className="text-center">
                      <div className="text-2xl font-bold text-gray-900">{dashboardStats.outfit_stats.total_records}</div>
                      <div className="text-sm text-gray-600">生成记录</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-green-600">{dashboardStats.outfit_stats.completed_records}</div>
                      <div className="text-sm text-gray-600">成功生成</div>
                    </div>
                    <div className="text-center">
                      <div className="text-2xl font-bold text-orange-600">{dashboardStats.outfit_stats.total_records - dashboardStats.outfit_stats.completed_records}</div>
                      <div className="text-sm text-gray-600">处理中/失败</div>
                    </div>
                  </div>
                )}
              </div>

              {/* 穿搭生成记录列表 */}
              <div className="bg-white rounded-2xl shadow-sm border border-gray-200">
                <div className="p-6 border-b border-gray-200">
                  <h4 className="text-lg font-semibold text-gray-900">生成记录</h4>
                  <p className="text-sm text-gray-600 mt-1">查看所有穿搭图片生成记录和结果</p>
                </div>

                <div className="p-6">
                  <OutfitImageGallery
                    records={outfitRecords}
                    onDelete={handleDeleteOutfitRecord}
                    onRefresh={loadOutfitRecords}
                    onRetry={handleRetryOutfitRecord}
                    onLoadMore={loadMoreOutfitRecords}
                    loading={false}
                    loadingMore={outfitLoadingMore}
                    hasMore={outfitHasMore}
                  />
                </div>
              </div>
            </div>
          )}

          {/* 数据统计选项卡 */}
          {activeTab === 'stats' && (
            <ModelStatsTab
              model={model}
              dashboardStats={dashboardStats}
              videoTasks={videoTasks}
              outfitRecords={outfitRecords}
            />
          )}
        </div>

        {/* 删除确认对话框 */}
        <DeleteConfirmDialog
          isOpen={deletePhotoConfirm.show}
          title="删除照片"
          message="确定要删除这张照片吗？此操作不可撤销。"
          itemName={deletePhotoConfirm.photoName || undefined}
          deleting={deletePhotoConfirm.deleting}
          onConfirm={confirmDeletePhoto}
          onCancel={cancelDeletePhoto}
        />

        {/* 穿搭图片生成Modal */}
        {model && (
          <OutfitImageGenerationModal
            isOpen={showOutfitModal}
            onClose={() => setShowOutfitModal(false)}
            model={model}
            onGenerate={handleGenerateOutfitImages}
            onBatchGenerate={handleBatchGenerateOutfitImages}
            isGenerating={generatingOutfit}
          />
        )}

        {/* 图片上传Modal */}
        <ModelImageUploadModal
          isOpen={showUploadModal}
          onClose={() => setShowUploadModal(false)}
          onUpload={handleBatchUploadPhotos}
          isUploading={uploadingPhotos}
        />
      </div>
    </div>
  );
};

export default ModelDetail;