// ============================================================
// ConfigPanel — 右侧抽屉式配置面板
// 职责：主题切换、TTS 开关、detail level 切换、语言选择、情景选择（含自建）
// ============================================================

import { useState } from "react";
import { useI18n } from "../../lib/i18n";
import type { SessionConfig, Theme } from "../../types";
import type { ExtendedScenario } from "../../hooks/useScenarios";
import type { UserScenario } from "../../lib/api/scenarios";

interface ConfigPanelProps {
  config: SessionConfig;
  theme: Theme;
  username?: string;
  allScenarios: ExtendedScenario[];
  open: boolean;
  onUpdate: (partial: Partial<SessionConfig>) => void;
  onThemeChange: (theme: Theme) => void;
  onLogout?: () => void;
  onClose: () => void;
  onCreateScenario: () => void;
  onEditScenario: (scenario: UserScenario) => void;
  onDeleteScenario: (id: string) => void;
}

export function ConfigPanel({
  config,
  theme,
  username,
  allScenarios,
  open,
  onUpdate,
  onThemeChange,
  onLogout,
  onClose,
  onCreateScenario,
  onEditScenario,
  onDeleteScenario,
}: ConfigPanelProps) {
  const { t } = useI18n();
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  // 分组：系统预置 vs 自建
  const systemScenarios = allScenarios.filter((s) => !s.isCustom);
  const customScenarios = allScenarios.filter((s) => s.isCustom);

  const handleDelete = (id: string) => {
    if (deleteConfirm === id) {
      onDeleteScenario(id);
      setDeleteConfirm(null);
      // 如果当前选中的情景被删除，切换回自由对话
      if (config.scenario === id) {
        onUpdate({ scenario: "free_chat" });
      }
    } else {
      setDeleteConfirm(id);
      // 3秒后自动取消确认
      setTimeout(() => setDeleteConfirm(null), 3000);
    }
  };

  return (
    <div
      className={`drawer-overlay ${open ? 'drawer-overlay--visible' : ''}`}
      onClick={onClose}
    >
      <div
        className={`drawer ${open ? 'drawer--open' : 'drawer--collapsed'}`}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="drawer__header">
          <span className="drawer__title">{t("settings.title")}</span>
          <button className="drawer__close" onClick={onClose}>
            ✕
          </button>
        </div>

        <div className="drawer__body">
          <div className="config-group">
            <div className="config-group__title">{t("settings.appearance")}</div>

            <label className="config-row">
              <div className="config-row__info">
                <span className="config-row__label">{t("settings.theme")}</span>
                <span className="config-row__desc">{t("settings.theme.desc")}</span>
              </div>
              <select
                value={theme}
                onChange={(e) => onThemeChange(e.target.value as Theme)}
              >
                <option value="dark">{t("settings.theme.dark")}</option>
                <option value="light">{t("settings.theme.light")}</option>
              </select>
            </label>
          </div>

          <div className="config-group">
            <div className="config-group__title">{t("settings.session")}</div>

            <label className="config-row">
              <div className="config-row__info">
                <span className="config-row__label">{t("settings.tts")}</span>
                <span className="config-row__desc">{t("settings.tts.desc")}</span>
              </div>
              <input
                type="checkbox"
                checked={config.ttsEnabled}
                onChange={(e) => onUpdate({ ttsEnabled: e.target.checked })}
              />
            </label>

            <label className="config-row">
              <div className="config-row__info">
                <span className="config-row__label">{t("settings.detail")}</span>
                <span className="config-row__desc">{t("settings.detail.desc")}</span>
              </div>
              <select
                value={config.detailLevel}
                onChange={(e) => onUpdate({ detailLevel: e.target.value as "low" | "high" })}
              >
                <option value="low">{t("settings.detail.low")}</option>
                <option value="high">{t("settings.detail.high")}</option>
              </select>
            </label>

            <label className="config-row">
              <div className="config-row__info">
                <span className="config-row__label">{t("settings.language")}</span>
                <span className="config-row__desc">{t("settings.language.desc")}</span>
              </div>
              <select
                value={config.language}
                onChange={(e) => onUpdate({ language: e.target.value })}
              >
                <option value="zh-CN">中文</option>
                <option value="en-US">English</option>
                <option value="ja-JP">日本語</option>
              </select>
            </label>
          </div>

          {/* 系统预置情景 */}
          <div className="config-group">
            <div className="config-group__title">{t("settings.scenario.system")}</div>
            <div className="scenario-list">
              {systemScenarios.map((sc) => (
                <label key={sc.id} className="scenario-item">
                  <input
                    type="radio"
                    name="scenario"
                    value={sc.id}
                    checked={config.scenario === sc.id}
                    onChange={(e) => onUpdate({ scenario: e.target.value })}
                  />
                  <span className="scenario-item__icon">{sc.icon}</span>
                  <span className="scenario-item__name">
                    {sc.nameKey ? t(sc.nameKey) : sc.name}
                  </span>
                </label>
              ))}
            </div>
          </div>

          {/* 自建情景 */}
          <div className="config-group">
            <div className="config-group__title">
              {t("settings.scenario.custom")}
              <button
                className="config-create-btn"
                onClick={onCreateScenario}
                title={t("scenario.create.button")}
              >
                + {t("scenario.create.button")}
              </button>
            </div>

            {customScenarios.length === 0 ? (
              <div className="scenario-empty">
                {t("settings.scenario.empty")}
              </div>
            ) : (
              <div className="scenario-list">
                {customScenarios.map((sc) => (
                  <div key={sc.id} className="scenario-item scenario-item--custom">
                    <label className="scenario-item__radio">
                      <input
                        type="radio"
                        name="scenario"
                        value={sc.id}
                        checked={config.scenario === sc.id}
                        onChange={(e) => onUpdate({ scenario: e.target.value })}
                      />
                      <span className="scenario-item__icon">{sc.icon}</span>
                      <div className="scenario-item__info">
                        <span className="scenario-item__name">{sc.name}</span>
                        {sc.description && (
                          <span className="scenario-item__desc">{sc.description}</span>
                        )}
                      </div>
                    </label>
                    <div className="scenario-item__actions">
                      <button
                        className="scenario-action-btn scenario-action-btn--edit"
                        onClick={() => onEditScenario(sc as unknown as UserScenario)}
                        title={t("common.edit")}
                      >
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                      </button>
                      <button
                        className={`scenario-action-btn scenario-action-btn--delete ${
                          deleteConfirm === sc.id ? "scenario-action-btn--confirm" : ""
                        }`}
                        onClick={() => handleDelete(sc.id)}
                        title={deleteConfirm === sc.id ? t("common.confirmDelete") : t("common.delete")}
                      >
                        {deleteConfirm === sc.id ? "✓" : <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {username && onLogout && (
            <div className="config-group">
              <div className="config-group__title">{t("settings.account")}</div>
              <div className="config-row" style={{ cursor: "default" }}>
                <div className="config-row__info">
                  <span className="config-row__label">{t("settings.account.user")}</span>
                  <span className="config-row__desc">{username}</span>
                </div>
              </div>
              <button className="config-logout-btn" onClick={onLogout}>
                {t("auth.logout")}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
