// ============================================================
// CreateScenarioModal — 创建自建情景对话框
// 职责：提供表单让用户创建新的自定义情景
// ============================================================

import { useCallback, useEffect, useRef, useState } from "react";
import { useI18n } from "../../lib/i18n";
import type { CreateScenarioRequest } from "../../lib/api/scenarios";
import { SCENARIO_ICON_SET, DEFAULT_SCENARIO_ICON_ID } from "../../lib/scenarioIcons";

interface CreateScenarioModalProps {
  onClose: () => void;
  onSubmit: (data: CreateScenarioRequest) => Promise<void>;
}

export function CreateScenarioModal({ onClose, onSubmit }: CreateScenarioModalProps) {
  const { t } = useI18n();
  const [name, setName] = useState("");
  const [icon, setIcon] = useState(DEFAULT_SCENARIO_ICON_ID);
  const [description, setDescription] = useState("");
  const [prompt, setPrompt] = useState("");
  const [greeting, setGreeting] = useState("");
  const [language, setLanguage] = useState("zh-CN");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showGuide, setShowGuide] = useState(false);
  const overlayRef = useRef<HTMLDivElement>(null);

  // 点击遮罩关闭
  const handleOverlayClick = useCallback(
    (e: React.MouseEvent) => {
      if (e.target === overlayRef.current) onClose();
    },
    [onClose]
  );

  // ESC 关闭
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [onClose]);

  // 阻止 body 滚动
  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, []);

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setError("");

      // 表单验证
      if (name.length < 2 || name.length > 50) {
        setError(t("scenario.error.nameLength"));
        return;
      }
      if (prompt.length < 10 || prompt.length > 2000) {
        setError(t("scenario.error.promptLength"));
        return;
      }
      if (greeting && greeting.length > 500) {
        setError(t("scenario.error.greetingLength"));
        return;
      }

      setIsSubmitting(true);
      try {
        await onSubmit({
          name,
          icon,
          description: description || undefined,
          prompt,
          greeting: greeting || undefined,
          language,
        });
        onClose();
      } catch (err) {
        setError(err instanceof Error ? err.message : "Unknown error");
      } finally {
        setIsSubmitting(false);
      }
    },
    [name, icon, description, prompt, greeting, language, onSubmit, onClose, t]
  );

  return (
    <div
      ref={overlayRef}
      className="modal-overlay"
      onClick={handleOverlayClick}
    >
      <div className="modal modal--large" onClick={(e) => e.stopPropagation()}>
        <div className="modal__header">
          <span className="modal__title">{t("scenario.create.title")}</span>
          <button className="modal__close" onClick={onClose}>
            ✕
          </button>
        </div>

        <form className="modal__body" onSubmit={handleSubmit}>
          {/* 名称 */}
          <div className="form-group">
            <label className="form-label">
              {t("scenario.create.name")} <span className="form-required">*</span>
            </label>
            <input
              type="text"
              className="form-input"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t("scenario.create.namePlaceholder")}
              maxLength={50}
              required
            />
            <span className="form-hint">{name.length}/50</span>
          </div>

          {/* 图标选择 */}
          <div className="form-group">
            <label className="form-label">{t("scenario.create.icon")}</label>
            <div className="icon-picker">
              {SCENARIO_ICON_SET.map((ic) => (
                <button
                  key={ic.id}
                  type="button"
                  className={`icon-picker__item ${icon === ic.id ? "icon-picker__item--active" : ""}`}
                  onClick={() => setIcon(ic.id)}
                  title={ic.label}
                >
                  {ic.render(22)}
                </button>
              ))}
            </div>
          </div>

          {/* 描述 */}
          <div className="form-group">
            <label className="form-label">{t("scenario.create.description")}</label>
            <input
              type="text"
              className="form-input"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder={t("scenario.create.descriptionPlaceholder")}
              maxLength={100}
            />
            <span className="form-hint">{description.length}/100</span>
          </div>

          {/* Prompt */}
          <div className="form-group">
            <label className="form-label">
              {t("scenario.create.prompt")} <span className="form-required">*</span>
              <button
                type="button"
                className="form-guide-btn"
                onClick={() => setShowGuide(!showGuide)}
              >
                {showGuide ? "▼" : "▶"} {t("scenario.create.promptGuide")}
              </button>
            </label>
            {showGuide && (
              <div className="form-guide">
                <p><strong>{t("scenario.create.promptGuide.tips")}</strong></p>
                <ul>
                  <li>{t("scenario.create.promptGuide.tip1")}</li>
                  <li>{t("scenario.create.promptGuide.tip2")}</li>
                  <li>{t("scenario.create.promptGuide.tip3")}</li>
                </ul>
                <p><strong>{t("scenario.create.promptGuide.example")}</strong></p>
                <pre className="form-guide__code">
{`你是一位创意写作导师。
帮助用户构思故事情节、人物设定和写作技巧。

【角色定位】
- 你是导师，不是代笔人
- 激发用户创意，不直接给答案

【交互规则】
1. 提出启发性问题
2. 给出具体、可操作的建议
3. 回答控制在3-5句话`}
                </pre>
              </div>
            )}
            <textarea
              className="form-textarea"
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder={t("scenario.create.promptPlaceholder")}
              rows={8}
              maxLength={2000}
              required
            />
            <span className="form-hint">{prompt.length}/2000</span>
          </div>

          {/* 首句引导 */}
          <div className="form-group">
            <label className="form-label">{t("scenario.create.greeting")}</label>
            <textarea
              className="form-textarea"
              value={greeting}
              onChange={(e) => setGreeting(e.target.value)}
              placeholder={t("scenario.create.greetingPlaceholder")}
              rows={3}
              maxLength={500}
            />
            <span className="form-hint">{greeting.length}/500</span>
          </div>

          {/* 语言 */}
          <div className="form-group">
            <label className="form-label">{t("scenario.create.language")}</label>
            <select
              className="form-select"
              value={language}
              onChange={(e) => setLanguage(e.target.value)}
            >
              <option value="zh-CN">中文</option>
              <option value="en-US">English</option>
              <option value="ja-JP">日本語</option>
            </select>
          </div>

          {error && <div className="form-error">{error}</div>}

          <div className="modal__footer">
            <button
              type="button"
              className="btn btn--secondary"
              onClick={onClose}
              disabled={isSubmitting}
            >
              {t("common.cancel")}
            </button>
            <button
              type="submit"
              className="btn btn--primary"
              disabled={isSubmitting}
            >
              {isSubmitting ? t("common.creating") : t("common.create")}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
