/**
 * 右栏设置面板 — V8 原型 1:1 还原
 * 标题设置(AI toggle) + 字幕设置 + BGM设置 + 片段详情
 */
import React, { useRef, useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import type { TemplateMode } from "@/api/editingPlanner";
import type { ClipData, ClipType } from "../types";
import type { AssetItem } from "@/api/assets";

interface TitleSettings {
  aiAutoSelect: boolean;
  title: string;
  position: string;
  font: string;
  size: number;
  bold: boolean;
  italic: boolean;
  stroke: boolean;
  shadow: boolean;
  color: string;
}

interface SubtitleSettings {
  enabled: boolean;
  position: string;
  font: string;
  size: number;
  animation: string;
}

interface BgmSettings {
  music: string;
}

interface ClipPropertiesPanelProps {
  selectedClip: ClipData | null;
  titleSettings: TitleSettings;
  subtitleSettings: SubtitleSettings;
  bgmSettings: BgmSettings;
  clipsCount: number;
  totalDuration: number;
  currentMode: TemplateMode;
  onTitleSettingsChange: (partial: Partial<TitleSettings>) => void;
  onSubtitleSettingsChange: (partial: Partial<SubtitleSettings>) => void;
  onBgmSettingsChange: (partial: Partial<BgmSettings>) => void;
  onClipUpdate: (clipId: string, data: Partial<ClipData>) => void;
  /** 配音素材列表（从配音素材库 API 获取） */
  voiceMaterials?: AssetItem[];
  /** 配音素材加载中 */
  voiceMaterialsLoading?: boolean;
  /** 刷新配音素材列表 */
  onRefreshVoiceMaterials?: () => void;
  /** 为片段选择配音素材 */
  onClipVoiceSelect?: (clipId: string, asset: AssetItem | null) => void;
}

const POSITION_OPTIONS = [
  { value: "top", label: "顶部" },
  { value: "center", label: "居中" },
  { value: "bottom", label: "底部" },
];

const FONT_OPTIONS = [
  "思源黑体",
  "思源宋体",
  "苹方",
  "PingFang",
  "微软雅黑",
  "楷体",
  "华康俪金黑",
];

const ANIMATION_OPTIONS = [
  { value: "none", label: "无" },
  { value: "fade", label: "淡入淡出" },
  { value: "slide", label: "滑动" },
  { value: "typewriter", label: "打字机" },
];

const BGM_OPTIONS = [
  { value: "none", label: "无背景音乐" },
  { value: "bgm_01", label: "🎵 轻快节奏" },
  { value: "bgm_02", label: "🎵 温馨舒缓" },
  { value: "bgm_03", label: "🎵 动感活力" },
  { value: "bgm_04", label: "🎵 科技感" },
];

/**
 * 标题样式预设 — 纯样式组合（颜色+描边+阴影+字重+字号）
 * 不绑定字体，用户可自由搭配任意字体
 * 预览统一用系统字体展示效果
 */
const TITLE_PRESETS = [
  {
    key: "classic_white",
    label: "经典白字",
    style: {
      size: 28,
      color: "#ffffff",
      bold: true,
      italic: false,
      stroke: true,
      shadow: false,
    },
    previewStyle: {
      fontWeight: 700,
      color: "#ffffff",
      WebkitTextStroke: "1px #000000",
      fontSize: "20px",
    },
  },
  {
    key: "black_gold",
    label: "黑金质感",
    style: {
      size: 32,
      color: "#d4a843",
      bold: true,
      italic: false,
      stroke: false,
      shadow: true,
    },
    previewStyle: {
      fontWeight: 700,
      color: "#d4a843",
      textShadow: "1px 1px 3px rgba(0,0,0,0.8)",
      fontSize: "20px",
    },
  },
  {
    key: "fresh_minimal",
    label: "清新简约",
    style: {
      size: 24,
      color: "#333333",
      bold: false,
      italic: false,
      stroke: false,
      shadow: false,
    },
    previewStyle: {
      fontWeight: 400,
      color: "#333333",
      fontSize: "18px",
    },
  },
  {
    key: "variety_show",
    label: "综艺花字",
    style: {
      size: 36,
      color: "#ff4081",
      bold: true,
      italic: false,
      stroke: true,
      shadow: true,
    },
    previewStyle: {
      fontWeight: 900,
      color: "#ff4081",
      WebkitTextStroke: "1.5px #ffffff",
      textShadow: "2px 2px 4px rgba(0,0,0,0.5)",
      fontSize: "22px",
    },
  },
  {
    key: "business",
    label: "商务极简",
    style: {
      size: 24,
      color: "#1a1a1a",
      bold: false,
      italic: false,
      stroke: false,
      shadow: false,
    },
    previewStyle: {
      fontWeight: 400,
      color: "#1a1a1a",
      fontSize: "17px",
    },
  },
  {
    key: "retro_film",
    label: "复古胶片",
    style: {
      size: 28,
      color: "#e8d5b7",
      bold: false,
      italic: false,
      stroke: false,
      shadow: true,
    },
    previewStyle: {
      fontWeight: 400,
      color: "#e8d5b7",
      textShadow: "2px 2px 6px rgba(0,0,0,0.7)",
      fontSize: "18px",
    },
  },
  {
    key: "neon_glow",
    label: "霓虹发光",
    style: {
      size: 32,
      color: "#00e5ff",
      bold: true,
      italic: false,
      stroke: false,
      shadow: true,
    },
    previewStyle: {
      fontWeight: 700,
      color: "#00e5ff",
      textShadow:
        "0 0 4px #00e5ff, 0 0 8px #00e5ff, 0 0 16px rgba(0,229,255,0.5)",
      fontSize: "20px",
    },
  },
  {
    key: "handwriting",
    label: "手写字",
    style: {
      size: 28,
      color: "#333333",
      bold: false,
      italic: false,
      stroke: false,
      shadow: true,
    },
    previewStyle: {
      fontWeight: 400,
      color: "#333333",
      textShadow: "1px 1px 2px rgba(0,0,0,0.3)",
      fontSize: "20px",
    },
  },
];

/** 判断当前设置匹配哪个预设（比较 size + color + bold/italic/stroke/shadow，不比较字体） */
function getActivePreset(settings: TitleSettings): string | null {
  for (const p of TITLE_PRESETS) {
    if (
      settings.size === p.style.size &&
      settings.color === p.style.color &&
      settings.bold === p.style.bold &&
      settings.italic === p.style.italic &&
      settings.stroke === p.style.stroke &&
      settings.shadow === p.style.shadow
    ) {
      return p.key;
    }
  }
  return null;
}

/** 片段类型图标/标签 */
const CLIP_TYPE_ICONS: Record<ClipType, string> = { voice: "🎙️", pip: "🖼️" };
const CLIP_TYPE_LABELS: Record<ClipType, string> = {
  voice: "口播",
  pip: "画中画",
};

const ClipPropertiesPanel: React.FC<ClipPropertiesPanelProps> = ({
  selectedClip,
  titleSettings,
  subtitleSettings,
  bgmSettings,
  clipsCount,
  totalDuration,
  currentMode,
  onTitleSettingsChange,
  onSubtitleSettingsChange,
  onBgmSettingsChange,
  onClipUpdate,
  voiceMaterials = [],
  voiceMaterialsLoading = false,
  onRefreshVoiceMaterials,
  onClipVoiceSelect,
}) => {
  const navigate = useNavigate();

  /* ── 配音试听 ── */
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const [previewingId, setPreviewingId] = useState<string | null>(null);

  /** 试听配音素材 */
  const handlePreviewVoice = useCallback(
    (asset: AssetItem) => {
      // 点击同一个 → 暂停
      if (previewingId === asset.id) {
        audioRef.current?.pause();
        setPreviewingId(null);
        return;
      }
      // 停止上一个
      audioRef.current?.pause();
      const url = asset.file_url || (asset.metadata?.preview_url as string);
      if (!url) return;
      const audio = new Audio(url);
      audioRef.current = audio;
      audio.play().catch(() => {});
      audio.onended = () => setPreviewingId(null);
      setPreviewingId(asset.id);
    },
    [previewingId],
  );

  /** 从 metadata 取性别标签 */
  const getGenderLabel = (m: AssetItem): string => {
    const g = (m.metadata?.gender as string) || "";
    if (g === "male") return "男";
    if (g === "female") return "女";
    return "";
  };
  return (
    <div className="ep-right-panel">
      {/* ═══ 标题设置 ═══ */}
      <div className="ep-settings-section">
        <div className="ep-section-title">
          <span className="ep-section-icon">📝</span>
          标题设置
        </div>

        <div className="ep-toggle-row">
          <span className="ep-toggle-label">AI 自动选择</span>
          <div
            className={`ep-toggle ${titleSettings.aiAutoSelect ? "active" : ""}`}
            onClick={() =>
              onTitleSettingsChange({
                aiAutoSelect: !titleSettings.aiAutoSelect,
              })
            }
          >
            <div className="ep-toggle-knob" />
          </div>
        </div>

        {!titleSettings.aiAutoSelect && (
          <>
            <div className="ep-field">
              <label className="ep-field-label">位置</label>
              <select
                className="ep-form-select"
                value={titleSettings.position}
                onChange={(e) =>
                  onTitleSettingsChange({ position: e.target.value })
                }
              >
                {POSITION_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="ep-field">
              <label className="ep-field-label">字体</label>
              <select
                className="ep-form-select"
                value={titleSettings.font}
                onChange={(e) =>
                  onTitleSettingsChange({ font: e.target.value })
                }
              >
                {FONT_OPTIONS.map((f) => (
                  <option key={f} value={f}>
                    {f}
                  </option>
                ))}
              </select>
            </div>

            <div className="ep-field">
              <label className="ep-field-label">大小</label>
              <div className="ep-slider-row">
                <input
                  className="ep-slider"
                  type="range"
                  min={12}
                  max={48}
                  value={titleSettings.size}
                  onChange={(e) =>
                    onTitleSettingsChange({ size: Number(e.target.value) })
                  }
                />
                <span className="ep-slider-value">{titleSettings.size}px</span>
              </div>
            </div>

            <div className="ep-field">
              <label className="ep-field-label">预设样式</label>
              <div className="ep-title-presets-grid">
                {TITLE_PRESETS.map((p) => {
                  const isActive = getActivePreset(titleSettings) === p.key;
                  return (
                    <button
                      key={p.key}
                      className={`ep-title-preset-card${isActive ? " active" : ""}`}
                      onClick={() =>
                        onTitleSettingsChange({
                          size: p.style.size,
                          color: p.style.color,
                          bold: p.style.bold,
                          italic: p.style.italic,
                          stroke: p.style.stroke,
                          shadow: p.style.shadow,
                        })
                      }
                      title={p.label}
                    >
                      <span
                        className="ep-title-preset-preview-text"
                        style={p.previewStyle}
                      >
                        标题
                      </span>
                      <span className="ep-title-preset-card-label">
                        {p.label}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>

            <div className="ep-field">
              <label className="ep-field-label">样式</label>
              <div className="ep-style-btns">
                <button
                  className={`ep-style-btn ${titleSettings.bold ? "active" : ""}`}
                  onClick={() =>
                    onTitleSettingsChange({ bold: !titleSettings.bold })
                  }
                  title="粗体"
                >
                  <b>B</b>
                </button>
                <button
                  className={`ep-style-btn ${titleSettings.italic ? "active" : ""}`}
                  onClick={() =>
                    onTitleSettingsChange({ italic: !titleSettings.italic })
                  }
                  title="斜体"
                >
                  <i>I</i>
                </button>
                <button
                  className={`ep-style-btn ${titleSettings.stroke ? "active" : ""}`}
                  onClick={() =>
                    onTitleSettingsChange({ stroke: !titleSettings.stroke })
                  }
                  title="描边"
                >
                  S
                </button>
                <button
                  className={`ep-style-btn ${titleSettings.shadow ? "active" : ""}`}
                  onClick={() =>
                    onTitleSettingsChange({ shadow: !titleSettings.shadow })
                  }
                  title="阴影"
                >
                  ☁
                </button>
              </div>
            </div>
          </>
        )}
      </div>

      {/* ═══ 字幕设置 ═══ */}
      <div className="ep-settings-section">
        <div className="ep-section-title">
          <span className="ep-section-icon">💬</span>
          字幕设置
        </div>

        <div className="ep-toggle-row">
          <span className="ep-toggle-label">启用字幕</span>
          <div
            className={`ep-toggle ${subtitleSettings.enabled ? "active" : ""}`}
            onClick={() =>
              onSubtitleSettingsChange({
                enabled: !subtitleSettings.enabled,
              })
            }
          >
            <div className="ep-toggle-knob" />
          </div>
        </div>

        {subtitleSettings.enabled && (
          <>
            <div className="ep-field">
              <label className="ep-field-label">位置</label>
              <select
                className="ep-form-select"
                value={subtitleSettings.position}
                onChange={(e) =>
                  onSubtitleSettingsChange({ position: e.target.value })
                }
              >
                {POSITION_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="ep-field">
              <label className="ep-field-label">字体</label>
              <select
                className="ep-form-select"
                value={subtitleSettings.font}
                onChange={(e) =>
                  onSubtitleSettingsChange({ font: e.target.value })
                }
              >
                {FONT_OPTIONS.map((f) => (
                  <option key={f} value={f}>
                    {f}
                  </option>
                ))}
              </select>
            </div>

            <div className="ep-field">
              <label className="ep-field-label">大小</label>
              <div className="ep-slider-row">
                <input
                  className="ep-slider"
                  type="range"
                  min={10}
                  max={32}
                  value={subtitleSettings.size}
                  onChange={(e) =>
                    onSubtitleSettingsChange({ size: Number(e.target.value) })
                  }
                />
                <span className="ep-slider-value">
                  {subtitleSettings.size}px
                </span>
              </div>
            </div>

            <div className="ep-field">
              <label className="ep-field-label">动画</label>
              <select
                className="ep-form-select"
                value={subtitleSettings.animation}
                onChange={(e) =>
                  onSubtitleSettingsChange({ animation: e.target.value })
                }
              >
                {ANIMATION_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
          </>
        )}
      </div>

      {/* ═══ BGM 设置 ═══ */}
      <div className="ep-settings-section">
        <div className="ep-section-title">
          <span className="ep-section-icon">🎵</span>
          BGM 设置
        </div>

        <div className="ep-field">
          <label className="ep-field-label">背景音乐</label>
          <select
            className="ep-form-select"
            value={bgmSettings.music}
            onChange={(e) => onBgmSettingsChange({ music: e.target.value })}
          >
            {BGM_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* ═══ 片段详情（选中时显示） ═══ */}
      {selectedClip && (
        <div className="ep-settings-section">
          <div className="ep-section-title">
            <span className="ep-section-icon">🎞️</span>
            片段详情
          </div>

          <div className="ep-clip-detail">
            {/* 类型选择器 */}
            <div className="ep-clip-detail-field">
              <div className="ep-clip-detail-label">类型</div>
              <div className="ep-clip-type-selector">
                {(["voice", "pip"] as ClipType[]).map((t) => {
                  const disabled =
                    currentMode === "pip"
                      ? t !== "pip"
                      : currentMode === "voice_over"
                        ? t !== "voice"
                        : false; // voice_pip 可切换
                  return (
                    <button
                      key={t}
                      className={`ep-clip-type-btn${selectedClip.type === t ? " active" : ""}${disabled ? " disabled" : ""}`}
                      disabled={disabled}
                      onClick={() =>
                        !disabled && onClipUpdate(selectedClip.id, { type: t })
                      }
                    >
                      {CLIP_TYPE_ICONS[t]} {CLIP_TYPE_LABELS[t]}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* 时长 */}
            <div className="ep-clip-detail-field">
              <div className="ep-clip-detail-label">时长</div>
              <div className="ep-clip-detail-row">
                <input
                  className="ep-duration-input"
                  type="number"
                  min={1}
                  max={120}
                  value={selectedClip.duration}
                  onChange={(e) =>
                    onClipUpdate(selectedClip.id, {
                      duration: Math.max(
                        1,
                        Math.min(120, Number(e.target.value) || 1),
                      ),
                    })
                  }
                />
                <span className="ep-clip-detail-unit">秒</span>
              </div>
            </div>

            {/* 素材起始时间 — 仅 voice 类型显示 */}
            {selectedClip.type === "voice" && (
              <div className="ep-clip-detail-field">
                <div className="ep-clip-detail-label">素材起始时间</div>
                <div className="ep-clip-detail-row">
                  <input
                    className="ep-duration-input"
                    type="number"
                    min={0}
                    max={9999}
                    step={0.1}
                    value={selectedClip.startOffset}
                    onChange={(e) =>
                      onClipUpdate(selectedClip.id, {
                        startOffset: Math.max(
                          0,
                          Math.min(9999, Number(e.target.value) || 0),
                        ),
                      })
                    }
                  />
                  <span className="ep-clip-detail-unit">秒</span>
                </div>
              </div>
            )}

            {/* 配音素材选择 — 仅 voice 类型显示 */}
            {selectedClip.type === "voice" && (
              <div className="ep-clip-detail-field">
                <div className="ep-clip-detail-label">
                  配音素材
                  {onRefreshVoiceMaterials && (
                    <button
                      type="button"
                      className="ep-voice-refresh-btn"
                      title="刷新配音列表"
                      onClick={() => onRefreshVoiceMaterials()}
                      disabled={voiceMaterialsLoading}
                    >
                      {voiceMaterialsLoading ? "⏳" : "🔄"}
                    </button>
                  )}
                </div>

                {voiceMaterialsLoading && voiceMaterials.length === 0 ? (
                  <div className="ep-voice-loading">加载中...</div>
                ) : (
                  <>
                    <div className="ep-voice-select-row">
                      <select
                        className="ep-clip-detail-select"
                        value={selectedClip.voice_asset_id ?? ""}
                        onChange={(e) => {
                          const assetId = e.target.value;
                          if (!onClipVoiceSelect) return;
                          if (!assetId) {
                            onClipVoiceSelect(selectedClip.id, null);
                          } else {
                            const asset = voiceMaterials.find(
                              (m) => m.id === assetId,
                            );
                            if (asset)
                              onClipVoiceSelect(selectedClip.id, asset);
                          }
                          // 切换选择时停止试听
                          audioRef.current?.pause();
                          setPreviewingId(null);
                        }}
                      >
                        <option value="">未选择</option>
                        {voiceMaterials.map((m) => {
                          const gender = getGenderLabel(m);
                          const label = gender
                            ? `${m.name}（${gender}）`
                            : m.name;
                          return (
                            <option key={m.id} value={m.id}>
                              {label}
                            </option>
                          );
                        })}
                      </select>
                      {/* 试听按钮 */}
                      {selectedClip.voice_asset_id && (
                        <button
                          type="button"
                          className="ep-voice-preview-btn"
                          title={
                            previewingId === selectedClip.voice_asset_id
                              ? "暂停"
                              : "试听"
                          }
                          onClick={() => {
                            const asset = voiceMaterials.find(
                              (m) => m.id === selectedClip.voice_asset_id,
                            );
                            if (asset) handlePreviewVoice(asset);
                          }}
                        >
                          {previewingId === selectedClip.voice_asset_id
                            ? "⏸"
                            : "▶️"}
                        </button>
                      )}
                    </div>
                    {voiceMaterials.length === 0 && (
                      <div className="ep-voice-empty">
                        暂无配音素材，请先上传
                      </div>
                    )}
                  </>
                )}

                <button
                  className="ep-voice-upload-btn"
                  onClick={() => navigate("/app/voice-materials")}
                >
                  + 上传新配音
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ═══ 统计信息（始终显示） ═══ */}
      {!selectedClip && (
        <div className="ep-settings-section">
          <div className="ep-section-title">
            <span className="ep-section-icon">📊</span>
            编辑统计
          </div>
          <div className="ep-clip-detail">
            <div className="ep-clip-detail-field">
              <div className="ep-clip-detail-label">片段数</div>
              <div className="ep-clip-detail-value">{clipsCount}</div>
            </div>
            <div className="ep-clip-detail-field">
              <div className="ep-clip-detail-label">总时长</div>
              <div className="ep-clip-detail-value">
                {totalDuration.toFixed(1)}s
              </div>
            </div>
            <div className="ep-clip-detail-field">
              <div className="ep-clip-detail-label">当前模式</div>
              <div className="ep-clip-detail-value">
                {currentMode === "pip"
                  ? "画中画"
                  : currentMode === "voice_over"
                    ? "人物口播"
                    : currentMode === "one_take"
                      ? "一镜到底"
                      : "口播+画中画"}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ClipPropertiesPanel;
