'use client';

import React, { useState } from 'react';
import { X, Sparkles, Image as ImageIcon, Video, CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { Asset, Storyboard } from '@/types';

interface BatchGenerateDialogProps {
  items: (Asset | Storyboard)[];
  type: 'image' | 'video';
  onGenerate: (items: (Asset | Storyboard)[]) => Promise<void>;
  onClose: () => void;
}

interface GenerationStatus {
  id: string;
  name: string;
  status: 'pending' | 'processing' | 'success' | 'failed';
  error?: string;
}

export default function BatchGenerateDialog({
  items,
  type,
  onGenerate,
  onClose,
}: BatchGenerateDialogProps) {
  const [selectedItems, setSelectedItems] = useState<Set<string>>(
    new Set(items.map(item => item.id))
  );
  const [generating, setGenerating] = useState(false);
  const [statuses, setStatuses] = useState<Map<string, GenerationStatus>>(new Map());

  const handleToggleItem = (id: string) => {
    const newSelected = new Set(selectedItems);
    if (newSelected.has(id)) {
      newSelected.delete(id);
    } else {
      newSelected.add(id);
    }
    setSelectedItems(newSelected);
  };

  const handleSelectAll = () => {
    if (selectedItems.size === items.length) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(items.map(item => item.id)));
    }
  };

  const handleGenerate = async () => {
    const itemsToGenerate = items.filter(item => selectedItems.has(item.id));
    
    if (itemsToGenerate.length === 0) return;

    setGenerating(true);
    
    // Initialize statuses
    const initialStatuses = new Map<string, GenerationStatus>();
    itemsToGenerate.forEach(item => {
      initialStatuses.set(item.id, {
        id: item.id,
        name: 'name' in item ? item.name : item.shot,
        status: 'pending',
      });
    });
    setStatuses(initialStatuses);

    try {
      await onGenerate(itemsToGenerate);
    } catch (error) {
      console.error('Batch generation failed:', error);
    } finally {
      setGenerating(false);
    }
  };

  const getItemName = (item: Asset | Storyboard) => {
    if ('name' in item) {
      return item.name;
    }
    return `分镜 ${item.order}: ${item.shot}`;
  };

  const hasPrompt = (item: Asset | Storyboard) => {
    if (type === 'image') {
      if ('imagePrompt' in item) {
        return !!item.imagePrompt;
      }
      if ('mergeImagePrompt' in item) {
        return !!item.mergeImagePrompt;
      }
    } else {
      if ('videoPrompt' in item) {
        return !!item.videoPrompt;
      }
    }
    return false;
  };

  const validItems = items.filter(hasPrompt);
  const selectedCount = Array.from(selectedItems).filter(id => 
    validItems.some(item => item.id === id)
  ).length;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <div className="flex items-center gap-3">
            {type === 'image' ? (
              <ImageIcon className="w-5 h-5 text-blue-600" />
            ) : (
              <Video className="w-5 h-5 text-purple-600" />
            )}
            <h2 className="text-lg font-semibold text-gray-900">
              批量生成{type === 'image' ? '图像' : '视频'}
            </h2>
          </div>
          <button
            onClick={onClose}
            disabled={generating}
            className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors disabled:opacity-50"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {/* Summary */}
          <div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-blue-900">
                  已选择 {selectedCount} / {validItems.length} 项
                </p>
                <p className="text-xs text-blue-700 mt-1">
                  {validItems.length < items.length && 
                    `${items.length - validItems.length} 项没有提示词，已自动过滤`
                  }
                </p>
              </div>
              <button
                onClick={handleSelectAll}
                disabled={generating}
                className="text-sm text-blue-600 hover:text-blue-700 font-medium disabled:opacity-50"
              >
                {selectedItems.size === validItems.length ? '取消全选' : '全选'}
              </button>
            </div>
          </div>

          {/* Items List */}
          <div className="space-y-2">
            {validItems.map((item) => {
              const isSelected = selectedItems.has(item.id);
              const status = statuses.get(item.id);

              return (
                <div
                  key={item.id}
                  className={`flex items-center gap-3 p-3 border rounded-lg transition-colors ${
                    isSelected
                      ? 'border-blue-300 bg-blue-50'
                      : 'border-gray-200 bg-white'
                  } ${generating ? 'opacity-75' : 'cursor-pointer hover:border-blue-200'}`}
                  onClick={() => !generating && handleToggleItem(item.id)}
                >
                  {/* Checkbox */}
                  <input
                    type="checkbox"
                    checked={isSelected}
                    onChange={() => handleToggleItem(item.id)}
                    disabled={generating}
                    className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                    onClick={(e) => e.stopPropagation()}
                  />

                  {/* Item Info */}
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 truncate">
                      {getItemName(item)}
                    </p>
                    {'desc' in item && (
                      <p className="text-xs text-gray-500 truncate mt-0.5">
                        {item.desc}
                      </p>
                    )}
                  </div>

                  {/* Status */}
                  {status && (
                    <div className="flex items-center gap-2">
                      {status.status === 'pending' && (
                        <span className="text-xs text-gray-500">等待中</span>
                      )}
                      {status.status === 'processing' && (
                        <>
                          <Loader2 className="w-4 h-4 text-blue-600 animate-spin" />
                          <span className="text-xs text-blue-600">生成中</span>
                        </>
                      )}
                      {status.status === 'success' && (
                        <>
                          <CheckCircle className="w-4 h-4 text-green-600" />
                          <span className="text-xs text-green-600">成功</span>
                        </>
                      )}
                      {status.status === 'failed' && (
                        <>
                          <XCircle className="w-4 h-4 text-red-600" />
                          <span className="text-xs text-red-600">失败</span>
                        </>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {validItems.length === 0 && (
            <div className="text-center py-12">
              <Sparkles className="w-12 h-12 text-gray-300 mx-auto mb-3" />
              <p className="text-sm text-gray-500">
                没有可用的项目（需要包含提示词）
              </p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-6 py-4 border-t border-gray-200 bg-gray-50">
          <div className="text-sm text-gray-600">
            {generating ? (
              <span className="flex items-center gap-2">
                <Loader2 className="w-4 h-4 animate-spin" />
                正在生成...
              </span>
            ) : (
              <span>
                预计消耗 {selectedCount} 次生成配额
              </span>
            )}
          </div>

          <div className="flex items-center gap-2">
            <button
              onClick={onClose}
              disabled={generating}
              className="px-4 py-2 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors disabled:opacity-50"
            >
              {generating ? '生成中...' : '取消'}
            </button>
            <button
              onClick={handleGenerate}
              disabled={generating || selectedCount === 0}
              className="flex items-center gap-2 px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Sparkles className="w-4 h-4" />
              开始生成
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
