import React, { useState, useCallback, useEffect } from 'react';
import {
  Search,
  Play,
  Pause,
  Star,
  StarOff,
  Volume2,
  Users,
  Settings,
  CheckCircle,
  Loader2,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { Modal } from './Modal';
import { useNotifications } from './NotificationSystem';
import { SystemVoiceService } from '../services/systemVoiceService';
import {
  VoiceInfo,
  GetVoicesResponse
} from '../types/voiceClone';
import { SystemVoice, SystemVoiceType, VoiceGender } from '../types/systemVoice';

interface VoiceSelectorProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (voiceId: string, voiceInfo: VoiceInfo | SystemVoice, source: 'system' | 'custom') => void;
  selectedVoiceId?: string;
}

interface CombinedVoice {
  id: string;
  name: string;
  description?: string;
  type: 'system' | 'custom';
  gender?: string;
  language?: string;
  tags?: string[];
  isFavorite?: boolean;
  data: VoiceInfo | SystemVoice;
}

/**
 * 统一的音色选择器弹框
 * 整合系统音色和自定义音色，提供搜索、筛选、预览等功能
 */
export const VoiceSelector: React.FC<VoiceSelectorProps> = ({
  isOpen,
  onClose,
  onSelect,
  selectedVoiceId
}) => {
  const { addNotification } = useNotifications();

  // ============= 状态管理 =============
  
  const [voices, setVoices] = useState<CombinedVoice[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [typeFilter, setTypeFilter] = useState<'all' | 'system' | 'custom'>('all');
  const [genderFilter, setGenderFilter] = useState<'all' | 'male' | 'female'>('all');
  const [playingVoiceId, setPlayingVoiceId] = useState<string | null>(null);
  const [favorites, setFavorites] = useState<Set<string>>(new Set());

  // ============= 数据加载 =============

  const loadVoices = useCallback(async () => {
    setLoading(true);
    try {
      // 并行加载系统音色和自定义音色
      const [systemVoicesData, customVoicesResponse] = await Promise.all([
        SystemVoiceService.getAllSystemVoices(),
        invoke<GetVoicesResponse>('get_voices')
      ]);

      // 转换系统音色数据
      const systemVoices: CombinedVoice[] = systemVoicesData.map(voice => {
        const tags = [];

        // 根据音色类型添加标签
        switch (voice.voice_type) {
          case SystemVoiceType.SYSTEM:
            tags.push('系统');
            break;
          case SystemVoiceType.PREMIUM:
            tags.push('精品');
            break;
          case SystemVoiceType.CHILD:
            tags.push('童声');
            break;
          case SystemVoiceType.CHARACTER:
            tags.push('角色');
            break;
          case SystemVoiceType.HOLIDAY:
            tags.push('节日');
            break;
          case SystemVoiceType.ENGLISH:
            tags.push('英文');
            break;
        }

        // 根据性别添加标签
        switch (voice.gender) {
          case VoiceGender.MALE:
            tags.push('男声');
            break;
          case VoiceGender.FEMALE:
            tags.push('女声');
            break;
          case VoiceGender.CHILD:
            tags.push('童声');
            break;
        }

        return {
          id: voice.voice_id,
          name: voice.voice_name,
          description: voice.description,
          type: 'system' as const,
          gender: voice.gender === VoiceGender.MALE ? 'male' : voice.gender === VoiceGender.FEMALE ? 'female' : undefined,
          language: voice.language,
          tags,
          data: voice
        };
      });

      // 转换自定义音色数据
      const customVoices: CombinedVoice[] = customVoicesResponse.data?.map(voice => ({
        id: voice.voice_id,
        name: voice.voice_name || voice.voice_id,
        description: Array.isArray(voice.description) ? voice.description.join(', ') : voice.description,
        type: 'custom' as const,
        tags: ['自定义'],
        data: voice
      })) || [];

      const allVoices = [...systemVoices, ...customVoices];
      setVoices(allVoices);

      console.log('🎵 成功加载音色:', {
        系统音色: systemVoices.length,
        自定义音色: customVoices.length,
        总计: allVoices.length
      });
    } catch (error) {
      console.error('加载音色列表失败:', error);
      addNotification({
        type: 'error',
        title: '加载失败',
        message: '加载音色列表失败'
      });
    } finally {
      setLoading(false);
    }
  }, [addNotification]);

  // ============= 筛选逻辑 =============

  const filteredVoices = voices.filter(voice => {
    // 搜索筛选
    if (searchText.trim()) {
      const searchLower = searchText.toLowerCase();
      const matchesName = voice.name.toLowerCase().includes(searchLower);
      const matchesDescription = voice.description?.toLowerCase().includes(searchLower);
      const matchesTags = voice.tags?.some(tag => tag.toLowerCase().includes(searchLower));
      
      if (!matchesName && !matchesDescription && !matchesTags) {
        return false;
      }
    }

    // 类型筛选
    if (typeFilter !== 'all' && voice.type !== typeFilter) {
      return false;
    }

    // 性别筛选
    if (genderFilter !== 'all' && voice.gender !== genderFilter) {
      return false;
    }

    return true;
  });

  // ============= 事件处理 =============

  const handleVoiceSelect = useCallback((voice: CombinedVoice) => {
    onSelect(voice.id, voice.data, voice.type);
    onClose();
  }, [onSelect, onClose]);

  const handlePlayPreview = useCallback((voiceId: string) => {
    if (playingVoiceId === voiceId) {
      setPlayingVoiceId(null);
      // 停止播放逻辑
    } else {
      setPlayingVoiceId(voiceId);
      // 开始播放预览逻辑
      // TODO: 实现音色预览功能
      addNotification({
        type: 'info',
        title: '预览功能',
        message: '音色预览功能开发中...'
      });
      
      // 模拟播放结束
      setTimeout(() => {
        setPlayingVoiceId(null);
      }, 3000);
    }
  }, [playingVoiceId, addNotification]);

  const toggleFavorite = useCallback((voiceId: string) => {
    setFavorites(prev => {
      const newFavorites = new Set(prev);
      if (newFavorites.has(voiceId)) {
        newFavorites.delete(voiceId);
      } else {
        newFavorites.add(voiceId);
      }
      return newFavorites;
    });
  }, []);

  // ============= 生命周期 =============

  useEffect(() => {
    if (isOpen) {
      loadVoices();
    }
  }, [isOpen, loadVoices]);

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="选择音色"
      subtitle="从系统音色和自定义音色中选择"
      icon={<Volume2 className="w-6 h-6 text-white" />}
      size="xl"
      variant="default"
    >
      <div className="p-6">
        {/* 搜索和筛选栏 */}
        <div className="flex flex-col sm:flex-row gap-4 mb-6">
          {/* 搜索框 */}
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="搜索音色名称、描述或标签..."
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          
          {/* 类型筛选 */}
          <select
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value as 'all' | 'system' | 'custom')}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="all">全部类型</option>
            <option value="system">系统音色</option>
            <option value="custom">自定义音色</option>
          </select>
          
          {/* 性别筛选 */}
          <select
            value={genderFilter}
            onChange={(e) => setGenderFilter(e.target.value as 'all' | 'male' | 'female')}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="all">全部性别</option>
            <option value="male">男声</option>
            <option value="female">女声</option>
          </select>
        </div>

        {/* 音色网格 */}
        <div className="max-h-96 overflow-y-auto">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
              <span className="ml-2 text-gray-500">加载中...</span>
            </div>
          ) : filteredVoices.length === 0 ? (
            <div className="text-center py-12">
              <Volume2 className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">未找到匹配的音色</h3>
              <p className="text-gray-500">请尝试调整搜索条件或筛选器</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {filteredVoices.map((voice) => (
                <div
                  key={voice.id}
                  className={`p-4 border rounded-lg cursor-pointer transition-all hover:shadow-md ${
                    selectedVoiceId === voice.id
                      ? 'border-blue-500 bg-blue-50 shadow-md'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                  onClick={() => handleVoiceSelect(voice)}
                >
                  {/* 音色头部 */}
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-2">
                      {voice.type === 'system' ? (
                        <Settings className="w-4 h-4 text-blue-600" />
                      ) : (
                        <Users className="w-4 h-4 text-orange-600" />
                      )}
                      <span className="font-medium text-gray-900">{voice.name}</span>
                    </div>
                    
                    <div className="flex items-center gap-1">
                      {/* 收藏按钮 */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          toggleFavorite(voice.id);
                        }}
                        className="p-1 text-gray-400 hover:text-yellow-500 transition-colors"
                      >
                        {favorites.has(voice.id) ? (
                          <Star className="w-4 h-4 fill-current text-yellow-500" />
                        ) : (
                          <StarOff className="w-4 h-4" />
                        )}
                      </button>
                      
                      {/* 预览按钮 */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handlePlayPreview(voice.id);
                        }}
                        className="p-1 text-gray-400 hover:text-green-600 transition-colors"
                      >
                        {playingVoiceId === voice.id ? (
                          <Pause className="w-4 h-4" />
                        ) : (
                          <Play className="w-4 h-4" />
                        )}
                      </button>
                      
                      {/* 选中状态 */}
                      {selectedVoiceId === voice.id && (
                        <CheckCircle className="w-4 h-4 text-blue-600" />
                      )}
                    </div>
                  </div>

                  {/* 音色描述 */}
                  {voice.description && (
                    <p className="text-sm text-gray-600 mb-3">{voice.description}</p>
                  )}

                  {/* 音色标签 */}
                  {voice.tags && voice.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1">
                      {voice.tags.map((tag, index) => (
                        <span
                          key={index}
                          className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded-full"
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 底部操作栏 */}
        <div className="flex justify-between items-center pt-6 border-t mt-6">
          <div className="text-sm text-gray-500">
            共找到 {filteredVoices.length} 个音色
          </div>
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
          >
            取消
          </button>
        </div>
      </div>
    </Modal>
  );
};
