import { useState, useRef, useCallback, useEffect, useMemo } from "react";
import { Play, Pause, Pencil, Trash2, Check, X, RefreshCw, Mic, ChevronDown, Search } from "lucide-react";
import type { GeneratedAudio } from "@/features/home/model/useGeneratedAudios";
import { SelectPopover } from "@/shared/ui/SelectPopover";

interface AudioTask {
  status: string;
  progress?: number;
  message?: string;
}

interface GeneratedAudiosPanelProps {
  generatedAudios: GeneratedAudio[];
  selectedAudioId: string | null;
  isGeneratingAudio: boolean;
  audioTask: AudioTask | null;
  onGenerateAudio: () => void;
  onRefresh: () => void;
  onSelectAudio: (audio: GeneratedAudio) => void;
  onDeleteAudio: (id: string) => void;
  onRenameAudio: (id: string, newName: string) => void;
  hasText: boolean;
  missingRefAudio?: boolean;
  speed: number;
  onSpeedChange: (speed: number) => void;
  ttsMode: string;
  emotion: string;
  onEmotionChange: (e: string) => void;
  embedded?: boolean;
}

export function GeneratedAudiosPanel({
  generatedAudios,
  selectedAudioId,
  isGeneratingAudio,
  audioTask,
  onGenerateAudio,
  onRefresh,
  onSelectAudio,
  onDeleteAudio,
  onRenameAudio,
  hasText,
  missingRefAudio = false,
  speed,
  onSpeedChange,
  ttsMode,
  emotion,
  onEmotionChange,
  embedded = false,
}: GeneratedAudiosPanelProps) {
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState("");
  const [playingId, setPlayingId] = useState<string | null>(null);
  const [audioFilter, setAudioFilter] = useState("");
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const audioListContainerRef = useRef<HTMLDivElement | null>(null);

  const stopPlaying = useCallback(() => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
      audioRef.current = null;
    }
    setPlayingId(null);
  }, []);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current = null;
      }
    };
  }, []);

  const togglePlay = (audio: GeneratedAudio, e: React.MouseEvent) => {
    e.stopPropagation();
    if (playingId === audio.id) {
      stopPlaying();
      return;
    }
    stopPlaying();
    const player = new Audio(audio.path);
    player.onended = () => setPlayingId(null);
    player.play().catch(() => {});
    audioRef.current = player;
    setPlayingId(audio.id);
  };

  const startEditing = (audio: GeneratedAudio, e: React.MouseEvent) => {
    e.stopPropagation();
    setEditingId(audio.id);
    setEditName(audio.name);
  };

  const saveEditing = (audioId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    if (!editName.trim()) return;
    onRenameAudio(audioId, editName.trim());
    setEditingId(null);
    setEditName("");
  };

  const cancelEditing = (e: React.MouseEvent) => {
    e.stopPropagation();
    setEditingId(null);
    setEditName("");
  };

  const canGenerate = hasText && !missingRefAudio;

  const speedOptions = [
    { value: 0.8, label: "较慢" },
    { value: 0.9, label: "稍慢" },
    { value: 1.0, label: "正常" },
    { value: 1.1, label: "稍快" },
    { value: 1.2, label: "较快" },
  ] as const;
  const currentSpeedLabel = speedOptions.find((o) => o.value === speed)?.label ?? "正常";

  const emotionOptions = [
    { value: "normal", label: "正常" },
    { value: "happy", label: "欢快" },
    { value: "sad", label: "低沉" },
    { value: "angry", label: "严肃" },
  ] as const;
  const currentEmotionLabel = emotionOptions.find((o) => o.value === emotion)?.label ?? "正常";
  const selectedAudio = generatedAudios.find((audio) => audio.id === selectedAudioId) || null;
  const filteredAudios = useMemo(() => {
    const query = audioFilter.trim().toLowerCase();
    if (!query) return generatedAudios;
    return generatedAudios.filter((audio) => audio.name.toLowerCase().includes(query));
  }, [audioFilter, generatedAudios]);

  const handleOpenAudioPopover = useCallback(() => {
    setAudioFilter("");

    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        const container = audioListContainerRef.current;
        if (!container) return;
        const selectedRow = container.querySelector<HTMLElement>("[data-audio-selected='true']");
        selectedRow?.scrollIntoView({ block: "nearest", behavior: "auto" });
      });
    });
  }, []);

  const content = (
    <>
      {embedded ? (
        <>
          {/* Row 1: 语气 + 语速 + 生成配音 (right-aligned) */}
          <div className="flex justify-end items-center gap-1.5 mb-3">
            {ttsMode === "voiceclone" && (
              <SelectPopover
                sheetTitle="选择语气"
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="rounded-lg border border-white/10 bg-black/25 px-2.5 py-1.5 text-xs text-gray-200 whitespace-nowrap flex items-center gap-1 transition-colors hover:border-white/30"
                  >
                    语气: {currentEmotionLabel}
                    <ChevronDown className={`h-3 w-3 transition-transform ${open ? "rotate-180" : ""}`} />
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-1">
                    {emotionOptions.map((opt) => {
                      const isSelected = emotion === opt.value;
                      return (
                        <button
                          key={opt.value}
                          type="button"
                          data-popover-selected={isSelected ? "true" : undefined}
                          onClick={() => {
                            onEmotionChange(opt.value);
                            close();
                          }}
                          className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left text-xs transition-colors ${isSelected
                            ? "border-purple-500 bg-purple-500/20 text-purple-200"
                            : "border-white/10 bg-white/5 text-gray-300 hover:border-white/30"
                            }`}
                        >
                          {opt.label}
                          {isSelected && <Check className="h-3.5 w-3.5 text-purple-300" />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </SelectPopover>
            )}
            {ttsMode === "voiceclone" && (
              <SelectPopover
                sheetTitle="选择语速"
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="rounded-lg border border-white/10 bg-black/25 px-2.5 py-1.5 text-xs text-gray-200 whitespace-nowrap flex items-center gap-1 transition-colors hover:border-white/30"
                  >
                    语速: {currentSpeedLabel}
                    <ChevronDown className={`h-3 w-3 transition-transform ${open ? "rotate-180" : ""}`} />
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-1">
                    {speedOptions.map((opt) => {
                      const isSelected = speed === opt.value;
                      return (
                        <button
                          key={opt.value}
                          type="button"
                          data-popover-selected={isSelected ? "true" : undefined}
                          onClick={() => {
                            onSpeedChange(opt.value);
                            close();
                          }}
                          className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left text-xs transition-colors ${isSelected
                            ? "border-purple-500 bg-purple-500/20 text-purple-200"
                            : "border-white/10 bg-white/5 text-gray-300 hover:border-white/30"
                            }`}
                        >
                          {opt.label}
                          {isSelected && <Check className="h-3.5 w-3.5 text-purple-300" />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </SelectPopover>
            )}
            <button
              onClick={onGenerateAudio}
              disabled={isGeneratingAudio || !canGenerate}
              title={missingRefAudio ? "请先选择参考音频" : !hasText ? "请先输入文案" : ""}
              className={`px-4 py-2 text-sm font-medium rounded-lg transition-all whitespace-nowrap flex items-center gap-1.5 shadow-sm ${
                isGeneratingAudio || !canGenerate
                  ? "bg-gray-600 cursor-not-allowed text-gray-400"
                  : "bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white hover:shadow-md"
              }`}
            >
              <Mic className="h-4 w-4" />
              生成配音
            </button>
          </div>
          {/* Row 2: 配音列表 + 刷新 */}
          <div className="flex justify-between items-center mb-3">
            <h3 className="text-sm font-medium text-gray-400">配音列表</h3>
            <button
              onClick={onRefresh}
              className="px-2 py-1 text-xs bg-white/10 hover:bg-white/20 rounded text-gray-300 whitespace-nowrap flex items-center gap-1"
            >
              <RefreshCw className="h-3.5 w-3.5" />
              刷新
            </button>
          </div>
        </>
      ) : (
        <div className="flex justify-between items-center gap-2 mb-4">
          <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2 whitespace-nowrap">
            <Mic className="h-4 w-4 text-purple-400" />
            配音列表
          </h2>
          <div className="flex gap-1.5">
            {ttsMode === "voiceclone" && (
              <SelectPopover
                sheetTitle="选择语气"
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="rounded-lg border border-white/10 bg-black/25 px-2.5 py-1.5 text-xs text-gray-200 whitespace-nowrap flex items-center gap-1 transition-colors hover:border-white/30"
                  >
                    语气: {currentEmotionLabel}
                    <ChevronDown className={`h-3 w-3 transition-transform ${open ? "rotate-180" : ""}`} />
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-1">
                    {emotionOptions.map((opt) => {
                      const isSelected = emotion === opt.value;
                      return (
                        <button
                          key={opt.value}
                          type="button"
                          data-popover-selected={isSelected ? "true" : undefined}
                          onClick={() => {
                            onEmotionChange(opt.value);
                            close();
                          }}
                          className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left text-xs transition-colors ${isSelected
                            ? "border-purple-500 bg-purple-500/20 text-purple-200"
                            : "border-white/10 bg-white/5 text-gray-300 hover:border-white/30"
                            }`}
                        >
                          {opt.label}
                          {isSelected && <Check className="h-3.5 w-3.5 text-purple-300" />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </SelectPopover>
            )}
            {ttsMode === "voiceclone" && (
              <SelectPopover
                sheetTitle="选择语速"
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="rounded-lg border border-white/10 bg-black/25 px-2.5 py-1.5 text-xs text-gray-200 whitespace-nowrap flex items-center gap-1 transition-colors hover:border-white/30"
                  >
                    语速: {currentSpeedLabel}
                    <ChevronDown className={`h-3 w-3 transition-transform ${open ? "rotate-180" : ""}`} />
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-1">
                    {speedOptions.map((opt) => {
                      const isSelected = speed === opt.value;
                      return (
                        <button
                          key={opt.value}
                          type="button"
                          data-popover-selected={isSelected ? "true" : undefined}
                          onClick={() => {
                            onSpeedChange(opt.value);
                            close();
                          }}
                          className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left text-xs transition-colors ${isSelected
                            ? "border-purple-500 bg-purple-500/20 text-purple-200"
                            : "border-white/10 bg-white/5 text-gray-300 hover:border-white/30"
                            }`}
                        >
                          {opt.label}
                          {isSelected && <Check className="h-3.5 w-3.5 text-purple-300" />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </SelectPopover>
            )}
            <button
              onClick={onGenerateAudio}
              disabled={isGeneratingAudio || !canGenerate}
              title={missingRefAudio ? "请先选择参考音频" : !hasText ? "请先输入文案" : ""}
              className={`px-4 py-2 text-sm font-medium rounded-lg transition-all whitespace-nowrap flex items-center gap-1.5 shadow-sm ${
                isGeneratingAudio || !canGenerate
                  ? "bg-gray-600 cursor-not-allowed text-gray-400"
                  : "bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white hover:shadow-md"
              }`}
            >
              <Mic className="h-4 w-4" />
              生成配音
            </button>
            <button
              onClick={onRefresh}
              className="px-2 py-1 text-xs bg-white/10 hover:bg-white/20 rounded text-gray-300 whitespace-nowrap flex items-center gap-1"
            >
              <RefreshCw className="h-3.5 w-3.5" />
              刷新
            </button>
          </div>
        </div>
      )}

      {/* 缺少参考音频提示 */}
      {missingRefAudio && (
        <div className="mb-3 px-3 py-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg text-yellow-300 text-xs">
          声音克隆模式需要先选择参考音频
        </div>
      )}

      {/* 生成进度 */}
      {isGeneratingAudio && audioTask && (
        <div className="mb-4 p-3 bg-purple-500/10 rounded-xl border border-purple-500/30">
          <div className="flex justify-between text-sm text-purple-300 mb-2">
            <span>{audioTask.message || "生成中..."}</span>
            <span>{audioTask.progress || 0}%</span>
          </div>
          <div className="h-2 bg-black/30 rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-purple-500 to-pink-500 transition-all duration-300"
              style={{ width: `${audioTask.progress || 0}%` }}
            />
          </div>
        </div>
      )}

      {/* 配音列表 */}
      {generatedAudios.length === 0 ? (
        <div className="text-center py-6 text-gray-400">
          <p className="text-sm">暂无配音</p>
          <p className="text-xs mt-1 text-gray-500">点击「生成配音」创建</p>
        </div>
      ) : (
        <SelectPopover
          sheetTitle="选择配音"
          onOpen={handleOpenAudioPopover}
          trigger={({ open, toggle }) => (
            <button
              type="button"
              onClick={toggle}
              className="w-full rounded-xl border border-white/10 bg-black/25 px-3 py-2.5 text-left transition-colors hover:border-white/30"
            >
              <span className="flex items-center justify-between gap-3">
                <span className="min-w-0">
                  <span className="block text-xs text-gray-400">当前配音</span>
                  <span className="mt-0.5 block truncate text-sm text-white">
                    {selectedAudio ? selectedAudio.name : "请选择配音"}
                  </span>
                </span>
                <ChevronDown className={`h-4 w-4 text-gray-300 transition-transform ${open ? "rotate-180" : ""}`} />
              </span>
            </button>
          )}
        >
          {({ close }) => (
            <div className="space-y-2">
              <div className="rounded-lg border border-white/10 bg-black/30 px-3 py-2">
                <div className="flex items-center gap-2">
                  <Search className="h-4 w-4 text-gray-400" />
                  <input
                    type="text"
                    value={audioFilter}
                    onChange={(e) => setAudioFilter(e.target.value)}
                    placeholder="搜索配音..."
                    className="w-full bg-transparent text-sm text-white placeholder-gray-500 outline-none"
                  />
                </div>
              </div>

              {filteredAudios.length === 0 ? (
                <div className="py-6 text-center text-sm text-gray-400">没有匹配的配音</div>
              ) : (
                <div ref={audioListContainerRef} className="space-y-1" style={{ contentVisibility: "auto" }}>
                  {filteredAudios.map((audio) => {
                    const isSelected = selectedAudioId === audio.id;
                    return (
                      <div
                        key={audio.id}
                        data-popover-selected={isSelected ? "true" : undefined}
                        data-audio-selected={isSelected ? "true" : "false"}
                        className={`flex items-center justify-between gap-2 rounded-lg border px-3 py-2 transition-colors ${isSelected
                          ? "border-purple-500 bg-purple-500/20"
                          : "border-white/10 bg-white/5 hover:border-white/30"
                          }`}
                      >
                        {editingId === audio.id ? (
                          <div className="flex-1 flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
                            <input
                              value={editName}
                              onChange={(e) => setEditName(e.target.value)}
                              className="flex-1 bg-black/40 border border-white/20 rounded-md px-2 py-1 text-xs text-white"
                              autoFocus
                              onKeyDown={(e) => {
                                if (e.key === "Enter") saveEditing(audio.id, e as unknown as React.MouseEvent);
                                if (e.key === "Escape") cancelEditing(e as unknown as React.MouseEvent);
                              }}
                            />
                            <button type="button" onClick={(e) => saveEditing(audio.id, e)} className="p-1 text-green-400 hover:text-green-300" title="保存">
                              <Check className="h-4 w-4" />
                            </button>
                            <button type="button" onClick={cancelEditing} className="p-1 text-gray-400 hover:text-white" title="取消">
                              <X className="h-4 w-4" />
                            </button>
                          </div>
                        ) : (
                          <button
                            type="button"
                            onClick={() => {
                              onSelectAudio(audio);
                              close();
                            }}
                            className="min-w-0 flex-1 text-left"
                          >
                            <span className="block truncate text-sm text-white">{audio.name}</span>
                            <span className="mt-0.5 block text-xs text-gray-400">{audio.duration_sec.toFixed(1)}s</span>
                          </button>
                        )}

                        {editingId !== audio.id && (
                          <div className="flex items-center gap-1 pl-2">
                            <button
                              type="button"
                              onClick={(e) => togglePlay(audio, e)}
                              className="p-1 text-gray-400 hover:text-purple-300 transition-colors"
                              title={playingId === audio.id ? "暂停" : "播放"}
                            >
                              {playingId === audio.id ? (
                                <Pause className="h-3.5 w-3.5" />
                              ) : (
                                <Play className="h-3.5 w-3.5" />
                              )}
                            </button>
                            <button
                              type="button"
                              onClick={(e) => startEditing(audio, e)}
                              className="p-1 text-gray-400 hover:text-white transition-colors"
                              title="重命名"
                            >
                              <Pencil className="h-3.5 w-3.5" />
                            </button>
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation();
                                onDeleteAudio(audio.id);
                              }}
                              className="p-1 text-gray-400 hover:text-red-400 transition-colors"
                              title="删除"
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </button>
                            {isSelected && <Check className="h-3.5 w-3.5 text-purple-300" />}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </SelectPopover>
      )}
    </>
  );

  if (embedded) return content;

  return (
    <div className="bg-white/5 rounded-2xl p-4 sm:p-6 border border-white/10 backdrop-blur-sm relative z-10">
      {content}
    </div>
  );
}
