import { useState, useEffect } from "react";
import { api } from "../api/client";
import type { ThemeProp } from "../types";
import GradientEditor from "./GradientEditor";
import styles from "./ThemeEditor.module.css";

interface Props {
  creativeId: string;
  theme: Record<string, string>;
  themeProps: ThemeProp[];
  onUpdated: () => void;
}

export default function ThemeEditor({ creativeId, theme, themeProps, onUpdated }: Props) {
  const [values, setValues] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  // 初始化：用当前 theme 或 default 填充
  useEffect(() => {
    const init: Record<string, string> = {};
    for (const prop of themeProps) {
      init[prop.key] = theme[prop.key] ?? prop.default;
    }
    setValues(init);
  }, [theme, themeProps]);

  if (themeProps.length === 0) {
    return <p className={styles.empty}>此模板无可配置的主题参数。</p>;
  }

  const changed =
    JSON.stringify(values) !==
    JSON.stringify(
      Object.fromEntries(themeProps.map((p) => [p.key, theme[p.key] ?? p.default]))
    );

  async function handleSave() {
    setSaving(true);
    try {
      await api.updateCreative(creativeId, { theme: values });
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
      onUpdated();
    } catch {
      // error handling via BuildPanel
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className={styles.wrapper}>
      {themeProps.map((prop) => (
        <div key={prop.key} className={styles.field}>
          <label className={styles.label}>{prop.label}</label>
          {prop.type === "color" ? (
            <div className={styles.colorRow}>
              <input
                type="color"
                value={values[prop.key] || prop.default}
                onChange={(e) =>
                  setValues((v) => ({ ...v, [prop.key]: e.target.value }))
                }
                className={styles.colorInput}
              />
              <span className={styles.colorValue}>
                {values[prop.key] || prop.default}
              </span>
            </div>
          ) : prop.type === "text" ? (
            <input
              type="text"
              value={values[prop.key] || ""}
              maxLength={prop.maxLength}
              onChange={(e) =>
                setValues((v) => ({ ...v, [prop.key]: e.target.value }))
              }
              className={styles.textInput}
            />
          ) : prop.type === "css-gradient" ? (
            <GradientEditor
              value={values[prop.key] || prop.default}
              onChange={(newVal) =>
                setValues((v) => ({ ...v, [prop.key]: newVal }))
              }
            />
          ) : (
            <input
              type="text"
              value={values[prop.key] || prop.default}
              onChange={(e) =>
                setValues((v) => ({ ...v, [prop.key]: e.target.value }))
              }
              className={styles.textInput}
              placeholder={prop.default}
            />
          )}
        </div>
      ))}

      <button
        onClick={handleSave}
        disabled={!changed || saving}
        className={styles.saveBtn}
      >
        {saving ? "保存中…" : saved ? "已保存 ✓" : "保存主题"}
      </button>
    </div>
  );
}
