import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { api } from "../api/client";
import type { Template } from "../types";
import styles from "./NewCreative.module.css";

export default function NewCreative() {
  const navigate = useNavigate();
  const [templates, setTemplates] = useState<Template[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState<string>("coloring");
  const [name, setName] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    api
      .getTemplates()
      .then((res) => {
        setTemplates(res.data);
        if (res.data.length > 0) setSelectedTemplate(res.data[0].id);
      })
      .catch((e) => setError(e.message));
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!name.trim()) return;

    setLoading(true);
    setError("");

    try {
      const res = await api.createCreative({
        name: name.trim(),
        templateId: selectedTemplate,
      });
      navigate(`/creatives/${res.data.id}`);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className={styles.container}>
      <button onClick={() => navigate(-1)} className={styles.back}>
        ← 返回
      </button>

      <h2 className={styles.title}>新建创意</h2>

      <form onSubmit={handleSubmit} className={styles.form}>
        <div className={styles.section}>
          <label className={styles.label}>选择模板</label>
          <div className={styles.templateList}>
            {templates.map((t) => (
              <label
                key={t.id}
                className={`${styles.templateCard} ${
                  selectedTemplate === t.id ? styles.selected : ""
                }`}
              >
                <input
                  type="radio"
                  name="template"
                  value={t.id}
                  checked={selectedTemplate === t.id}
                  onChange={() => setSelectedTemplate(t.id)}
                />
                <div className={styles.templateInfo}>
                  <strong>{t.name}</strong>
                  <span className={styles.templateDesc}>{t.description}</span>
                  <span className={styles.templateMeta}>
                    必填素材 {t.assetCount.required} 项 · 可选 {t.assetCount.optional} 项 ·{" "}
                    支持 {t.platforms.length} 个平台
                  </span>
                </div>
              </label>
            ))}
          </div>
        </div>

        <div className={styles.section}>
          <label className={styles.label} htmlFor="name">
            创意名称
          </label>
          <input
            id="name"
            type="text"
            className={styles.input}
            placeholder="例如：萌宠填色-谷歌渠道"
            value={name}
            onChange={(e) => setName(e.target.value)}
            maxLength={100}
            required
          />
        </div>

        {error && <p className={styles.error}>{error}</p>}

        <div className={styles.actions}>
          <button
            type="button"
            className={styles.cancelBtn}
            onClick={() => navigate(-1)}
          >
            取消
          </button>
          <button
            type="submit"
            className={styles.submitBtn}
            disabled={!name.trim() || loading}
          >
            {loading ? "创建中…" : "创建"}
          </button>
        </div>
      </form>
    </div>
  );
}
