import React, { useState, useCallback, useEffect } from 'react';
import {
  Image,
  Upload,
  Wand2,
  CheckCircle,
  XCircle,
  Loader2,
  RefreshCw,
  AlertTriangle,
  X,
  FileImage,
  Clock,
  Send,
  Trash2,
  Copy,
  ExternalLink
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { open } from '@tauri-apps/plugin-dialog';
import { useNotifications } from '../../components/NotificationSystem';
import { ImageGalleryModal } from '../../components/ImageGalleryModal';
import { DeleteConfirmDialog } from '../../components/DeleteConfirmDialog';
import {
  PromptCheckResponse,
  ImageGenerationRequest,
  ImageGenerationResponse,
  ImageGenerationRecord,
  ImageGenerationRecordStatus
} from '../../types/imageGeneration';

/**
 * AI图片生成工具 - 对话框形式
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const ImageGenerationTool: React.FC = () => {
  // 输入状态
  const [prompt, setPrompt] = useState('');
  const [referenceImagePath, setReferenceImagePath] = useState<string | null>(null);
  
  // 提示词预审状态
  const [promptCheckResult, setPromptCheckResult] = useState<PromptCheckResponse | null>(null);
  const [isCheckingPrompt, setIsCheckingPrompt] = useState(false);
  
  // 生成记录列表
  const [records, setRecords] = useState<ImageGenerationRecord[]>([]);
  const [isLoadingRecords, setIsLoadingRecords] = useState(false);

  // 图片预览模态框
  const [previewModal, setPreviewModal] = useState<{
    isOpen: boolean;
    images: string[];
    initialIndex: number;
    title: string;
  }>({
    isOpen: false,
    images: [],
    initialIndex: 0,
    title: ''
  });

  // 确认对话框状态
  const [confirmDialog, setConfirmDialog] = useState<{
    isOpen: boolean;
    title: string;
    message: string;
    onConfirm: () => void;
  }>({
    isOpen: false,
    title: '',
    message: '',
    onConfirm: () => {}
  });

  // 通知系统
  const { addNotification } = useNotifications();

  // 加载生成记录列表
  const loadRecords = useCallback(async () => {
    setIsLoadingRecords(true);
    try {
      const allRecords = await invoke<ImageGenerationRecord[]>('get_all_image_generation_records', {
        limit: 50
      });
      setRecords(allRecords);
    } catch (error) {
      console.error('加载生成记录失败:', error);
      addNotification({
        type: 'error',
        title: '加载失败',
        message: `无法加载生成记录: ${error}`
      });
    } finally {
      setIsLoadingRecords(false);
    }
  }, [addNotification]);

  // 初始化加载记录
  useEffect(() => {
    loadRecords();
  }, [loadRecords]);

  // 检查提示词合规性
  const checkPrompt = useCallback(async () => {
    if (!prompt.trim()) {
      addNotification({
        type: 'warning',
        title: '提示词为空',
        message: '请输入图片生成提示词'
      });
      return;
    }

    setIsCheckingPrompt(true);
    setPromptCheckResult(null);
    
    try {
      const result = await invoke<PromptCheckResponse>('check_image_prompt', {
        prompt: prompt.trim()
      });
      
      setPromptCheckResult(result);
      
      if (result.is_valid) {
        addNotification({
          type: 'success',
          title: '提示词检查通过',
          message: result.message
        });
      } else {
        addNotification({
          type: 'warning',
          title: '提示词需要优化',
          message: result.message
        });
      }
    } catch (error) {
      console.error('提示词检查失败:', error);
      addNotification({
        type: 'error',
        title: '提示词检查失败',
        message: `检查过程中出现错误: ${error}`
      });
    } finally {
      setIsCheckingPrompt(false);
    }
  }, [prompt, addNotification]);

  // 选择参考图片
  const selectReferenceImage = useCallback(async () => {
    try {
      const selected = await open({
        multiple: false,
        filters: [{
          name: 'Images',
          extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
        }]
      });
      
      if (selected && typeof selected === 'string') {
        setReferenceImagePath(selected);
        addNotification({
          type: 'success',
          title: '参考图片已选择',
          message: '图片将用作生成参考'
        });
      }
    } catch (error) {
      console.error('选择参考图片失败:', error);
      addNotification({
        type: 'error',
        title: '选择图片失败',
        message: `无法选择图片: ${error}`
      });
    }
  }, [addNotification]);

  // 移除参考图片
  const removeReferenceImage = useCallback(() => {
    setReferenceImagePath(null);
    addNotification({
      type: 'info',
      title: '参考图片已移除',
      message: '将使用纯文本提示词生成图片'
    });
  }, [addNotification]);

  // 设置事件监听
  useEffect(() => {
    const setupEventListeners = async () => {
      // 监听进度更新事件
      const progressUnlisten = await listen('image-generation-progress', (event: any) => {
        const { record_id, progress, status } = event.payload;
        console.log(`进度更新: ${record_id} -> ${Math.round(progress * 100)}%`);

        // 更新本地记录状态
        setRecords(prev => prev.map(record =>
          record.id === record_id
            ? { ...record, progress, status: status as ImageGenerationRecordStatus }
            : record
        ));
      });

      // 监听任务完成事件
      const completedUnlisten = await listen('image-generation-completed', (event: any) => {
        const { record_id, result_urls } = event.payload;
        console.log(`任务完成: ${record_id} -> ${result_urls.length} 张图片`);

        // 更新本地记录状态
        setRecords(prev => prev.map(record =>
          record.id === record_id
            ? {
                ...record,
                status: ImageGenerationRecordStatus.COMPLETED,
                progress: 1.0,
                result_urls,
                completed_at: new Date().toISOString()
              }
            : record
        ));

        addNotification({
          type: 'success',
          title: '图片生成完成',
          message: `成功生成 ${result_urls.length} 张图片`
        });
      });

      // 监听任务失败事件
      const failedUnlisten = await listen('image-generation-failed', (event: any) => {
        const { record_id, error } = event.payload;
        console.log(`任务失败: ${record_id} -> ${error}`);

        // 更新本地记录状态
        setRecords(prev => prev.map(record =>
          record.id === record_id
            ? {
                ...record,
                status: ImageGenerationRecordStatus.FAILED,
                error_message: error,
                completed_at: new Date().toISOString()
              }
            : record
        ));

        addNotification({
          type: 'error',
          title: '图片生成失败',
          message: error
        });
      });

      // 返回清理函数
      return () => {
        progressUnlisten();
        completedUnlisten();
        failedUnlisten();
      };
    };

    setupEventListeners();
  }, [addNotification]);

  // 开始图片生成
  const generateImage = useCallback(async () => {
    if (!prompt.trim()) {
      addNotification({
        type: 'warning',
        title: '提示词为空',
        message: '请输入图片生成提示词'
      });
      return;
    }

    // 如果提示词未通过检查，询问用户是否继续
    if (promptCheckResult && !promptCheckResult.is_valid) {
      setConfirmDialog({
        isOpen: true,
        title: '提示词检查未通过',
        message: `${promptCheckResult.message}\n\n是否仍要继续生成？`,
        onConfirm: () => {
          setConfirmDialog(prev => ({ ...prev, isOpen: false }));
          proceedWithGeneration();
        }
      });
      return;
    }

    await proceedWithGeneration();
  }, [prompt, referenceImagePath, promptCheckResult, addNotification]);

  // 实际执行生成的函数
  const proceedWithGeneration = useCallback(async () => {

    try {
      // 1. 创建数据库记录
      const record = await invoke<ImageGenerationRecord>('create_image_generation_record', {
        prompt: prompt.trim(),
        referenceImagePath: referenceImagePath
      });

      // 2. 更新记录列表
      setRecords(prev => [record, ...prev]);

      // 3. 提交生成任务
      const request: ImageGenerationRequest = {
        prompt: prompt.trim(),
        reference_image_path: referenceImagePath || undefined
      };

      const response = await invoke<ImageGenerationResponse>('submit_image_generation_task', {
        request
      });
      
      if (response.status === 'success') {
        // 4. 更新记录的任务ID并启动后台监控
        await invoke('start_image_generation_task', {
          recordId: record.id,
          taskId: response.task_id
        });

        // 5. 启动后台任务监控
        await invoke('start_background_task_monitoring', {
          taskId: response.task_id,
          recordId: record.id
        });

        addNotification({
          type: 'success',
          title: '任务提交成功',
          message: response.message
        });
      } else {
        // 更新记录为失败状态
        await invoke('fail_image_generation_task', {
          recordId: record.id,
          errorMessage: response.message
        });
        throw new Error(response.message);
      }
    } catch (error) {
      console.error('图片生成失败:', error);
      
      addNotification({
        type: 'error',
        title: '生成失败',
        message: `图片生成过程中出现错误: ${error}`
      });
    }
  }, [prompt, referenceImagePath, addNotification]);

  // 重置输入
  const resetInput = useCallback(() => {
    setPrompt('');
    setReferenceImagePath(null);
    setPromptCheckResult(null);
    
    addNotification({
      type: 'info',
      title: '已重置',
      message: '输入内容已重置'
    });
  }, [addNotification]);

  // 删除记录
  const deleteRecord = useCallback(async (recordId: string) => {
    try {
      await invoke('delete_image_generation_record', {
        recordId
      });

      // 删除记录时，后台监控会自动停止

      // 重新加载记录列表
      loadRecords();

      addNotification({
        type: 'success',
        title: '记录已删除',
        message: '图片生成记录已删除'
      });
    } catch (error) {
      console.error('删除记录失败:', error);
      addNotification({
        type: 'error',
        title: '删除失败',
        message: `无法删除记录: ${error}`
      });
    }
  }, [loadRecords, addNotification]);

  // 打开图片预览
  const openImagePreview = useCallback((images: string[], initialIndex: number, title: string) => {
    setPreviewModal({
      isOpen: true,
      images,
      initialIndex,
      title
    });
  }, []);

  // 关闭图片预览
  const closeImagePreview = useCallback(() => {
    setPreviewModal(prev => ({ ...prev, isOpen: false }));
  }, []);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-50">
      <div className="container mx-auto px-4 py-8 max-w-7xl">
        {/* 页面标题 */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <div className="p-3 bg-gradient-to-r from-purple-500 to-pink-500 rounded-xl">
              <Wand2 className="w-8 h-8 text-white" />
            </div>
            <div>
              <h1 className="text-3xl font-bold text-gray-900">AI图片生成工具</h1>
              <p className="text-gray-600 mt-1">对话框形式生成图片，支持提示词预审、参考图片和历史记录管理</p>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 左侧：输入区域 */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-xl shadow-lg p-6 sticky top-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-6 flex items-center gap-2">
                <Image className="w-5 h-5" />
                图片生成
              </h2>
              
              {/* 参考图片 */}
              {referenceImagePath && (
                <div className="mb-4 p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <FileImage className="w-4 h-4 text-gray-500" />
                      <span className="text-sm text-gray-600 truncate">
                        {referenceImagePath.split('/').pop()}
                      </span>
                    </div>
                    <button
                      onClick={removeReferenceImage}
                      className="p-1 text-red-500 hover:bg-red-50 rounded"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              )}
              
              {/* 输入框 */}
              <div className="mb-4">
                <textarea
                  value={prompt}
                  onChange={(e) => setPrompt(e.target.value)}
                  placeholder="请输入详细的图片描述..."
                  className="w-full h-32 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
                />
              </div>
              
              {/* 提示词检查结果 */}
              {promptCheckResult && (
                <div className={`mb-4 p-3 rounded-lg ${
                  promptCheckResult.is_valid 
                    ? 'bg-green-50 border border-green-200' 
                    : 'bg-yellow-50 border border-yellow-200'
                }`}>
                  <div className="flex items-center gap-2">
                    {promptCheckResult.is_valid ? (
                      <CheckCircle className="w-4 h-4 text-green-500" />
                    ) : (
                      <AlertTriangle className="w-4 h-4 text-yellow-500" />
                    )}
                    <span className={`text-sm ${
                      promptCheckResult.is_valid ? 'text-green-700' : 'text-yellow-700'
                    }`}>
                      {promptCheckResult.message}
                    </span>
                  </div>
                </div>
              )}
              
              {/* 操作按钮 */}
              <div className="space-y-3">
                <div className="flex gap-2">
                  <button
                    onClick={selectReferenceImage}
                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <Upload className="w-4 h-4" />
                    参考图片
                  </button>
                  <button
                    onClick={checkPrompt}
                    disabled={isCheckingPrompt || !prompt.trim()}
                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    {isCheckingPrompt ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <CheckCircle className="w-4 h-4" />
                    )}
                    检查提示词
                  </button>
                </div>
                
                <div className="flex gap-2">
                  <button
                    onClick={generateImage}
                    disabled={!prompt.trim()}
                    className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-lg hover:from-purple-600 hover:to-pink-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                  >
                    <Send className="w-4 h-4" />
                    开始生成
                  </button>
                  <button
                    onClick={resetInput}
                    className="px-4 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <RefreshCw className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* 右侧：记录列表 */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-xl shadow-lg p-6">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-semibold text-gray-900 flex items-center gap-2">
                  <Clock className="w-5 h-5" />
                  生成记录
                </h2>
                <button
                  onClick={loadRecords}
                  disabled={isLoadingRecords}
                  className="flex items-center gap-2 px-3 py-1 text-sm text-gray-600 hover:text-gray-900 transition-colors"
                >
                  <RefreshCw className={`w-4 h-4 ${isLoadingRecords ? 'animate-spin' : ''}`} />
                  刷新
                </button>
              </div>
              
              {/* 记录列表 */}
              <div className="space-y-4 max-h-[600px] overflow-y-auto">
                {records.length === 0 ? (
                  <div className="text-center py-12 text-gray-500">
                    <Image className="w-12 h-12 mx-auto mb-4 opacity-50" />
                    <p>暂无生成记录</p>
                    <p className="text-sm">开始生成您的第一张AI图片吧！</p>
                  </div>
                ) : (
                  records.map((record) => (
                    <RecordCard
                      key={record.id}
                      record={record}
                      onDelete={() => deleteRecord(record.id)}
                      onImagePreview={openImagePreview}
                    />
                  ))
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 图片预览模态框 */}
      <ImageGalleryModal
        images={previewModal.images}
        initialIndex={previewModal.initialIndex}
        isOpen={previewModal.isOpen}
        onClose={closeImagePreview}
        title={previewModal.title}
      />

      {/* 确认对话框 */}
      <DeleteConfirmDialog
        isOpen={confirmDialog.isOpen}
        title={confirmDialog.title}
        message={confirmDialog.message}
        onConfirm={confirmDialog.onConfirm}
        onCancel={() => setConfirmDialog(prev => ({ ...prev, isOpen: false }))}
      />
    </div>
  );
};

// 记录卡片组件
interface RecordCardProps {
  record: ImageGenerationRecord;
  onDelete: () => void;
  onImagePreview: (images: string[], initialIndex: number, title: string) => void;
}

const RecordCard: React.FC<RecordCardProps> = ({ record, onDelete, onImagePreview }) => {
  const getStatusIcon = () => {
    switch (record.status) {
      case ImageGenerationRecordStatus.PENDING:
        return <Clock className="w-4 h-4 text-yellow-500" />;
      case ImageGenerationRecordStatus.PROCESSING:
        return <Loader2 className="w-4 h-4 text-blue-500 animate-spin" />;
      case ImageGenerationRecordStatus.COMPLETED:
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case ImageGenerationRecordStatus.FAILED:
        return <XCircle className="w-4 h-4 text-red-500" />;
      case ImageGenerationRecordStatus.CANCELLED:
        return <X className="w-4 h-4 text-gray-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-500" />;
    }
  };

  const getStatusText = () => {
    switch (record.status) {
      case ImageGenerationRecordStatus.PENDING:
        return '等待中';
      case ImageGenerationRecordStatus.PROCESSING:
        return '生成中';
      case ImageGenerationRecordStatus.COMPLETED:
        return '已完成';
      case ImageGenerationRecordStatus.FAILED:
        return '失败';
      case ImageGenerationRecordStatus.CANCELLED:
        return '已取消';
      default:
        return '未知';
    }
  };

  const formatDuration = (ms?: number) => {
    if (!ms) return '-';
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${(ms / 60000).toFixed(1)}min`;
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  return (
    <div className="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
      {/* 头部信息 */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center gap-2">
          {getStatusIcon()}
          <span className="text-sm font-medium text-gray-900">{getStatusText()}</span>
          {record.status === ImageGenerationRecordStatus.PROCESSING && (
            <div className="flex-1 max-w-32">
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${record.progress * 100}%` }}
                />
              </div>
              <span className="text-xs text-gray-500 mt-1">
                {Math.round(record.progress * 100)}%
              </span>
            </div>
          )}
        </div>
        <div className="flex items-center gap-2">
          <span className="text-xs text-gray-500">
            {new Date(record.created_at).toLocaleString()}
          </span>
          <button
            onClick={onDelete}
            className="p-1 text-gray-400 hover:text-red-500 transition-colors"
          >
            <Trash2 className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* 提示词 */}
      <div className="mb-3">
        <div className="flex items-center gap-2 mb-1">
          <Wand2 className="w-3 h-3 text-gray-400" />
          <span className="text-xs font-medium text-gray-600">提示词</span>
          <button
            onClick={() => copyToClipboard(record.prompt)}
            className="p-0.5 text-gray-400 hover:text-gray-600 transition-colors"
          >
            <Copy className="w-3 h-3" />
          </button>
        </div>
        <p className="text-sm text-gray-700 line-clamp-2">{record.prompt}</p>
      </div>

      {/* 参考图片 */}
      {record.reference_image_path && (
        <div className="mb-3">
          <div className="flex items-center gap-2 mb-1">
            <FileImage className="w-3 h-3 text-gray-400" />
            <span className="text-xs font-medium text-gray-600">参考图片</span>
          </div>
          <p className="text-xs text-gray-500 truncate">
            {record.reference_image_path.split('/').pop()}
          </p>
        </div>
      )}

      {/* 生成结果 */}
      {record.result_urls.length > 0 && (
        <div className="mb-3">
          <div className="flex items-center gap-2 mb-2">
            <Image className="w-3 h-3 text-gray-400" />
            <span className="text-xs font-medium text-gray-600">
              生成结果 ({record.result_urls.length}张)
            </span>
          </div>
          <div className="grid grid-cols-4 gap-2">
            {record.result_urls.map((url, index) => (
              <div key={index} className="relative group cursor-pointer">
                <img
                  src={url}
                  alt={`Generated ${index + 1}`}
                  className="w-full h-16 object-cover rounded border border-gray-200 transition-transform group-hover:scale-105"
                  onClick={() => onImagePreview(
                    record.result_urls,
                    index,
                    `生成结果 - ${record.prompt.slice(0, 30)}${record.prompt.length > 30 ? '...' : ''}`
                  )}
                />
                <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 rounded flex items-center justify-center opacity-0 group-hover:opacity-100">
                  <div className="flex space-x-1">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        onImagePreview(
                          record.result_urls,
                          index,
                          `生成结果 - ${record.prompt.slice(0, 30)}${record.prompt.length > 30 ? '...' : ''}`
                        );
                      }}
                      className="p-1 bg-white bg-opacity-90 text-gray-800 rounded hover:bg-opacity-100 transition-all"
                      title="预览图片"
                    >
                      <ExternalLink className="w-3 h-3" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 任务信息 */}
      <div className="flex items-center justify-between text-xs text-gray-500">
        <div className="flex items-center gap-4">
          {record.task_id && (
            <span>任务ID: {record.task_id.slice(0, 8)}...</span>
          )}
          <span>耗时: {formatDuration(record.duration_ms)}</span>
        </div>
        {record.error_message && (
          <span className="text-red-500 truncate max-w-32" title={record.error_message}>
            {record.error_message}
          </span>
        )}
      </div>
    </div>
  );
};

export default ImageGenerationTool;
