"use client";

import type { FormEvent } from "react";

import type { PublishPlatform } from "../lib/domain/types";

export interface ArticleInputPayload {
  title: string;
  body: string;
  image_lines: string;
  platform: PublishPlatform;
  user_instructions: string;
}

interface ArticleInputFormProps {
  value: ArticleInputPayload;
  isSubmitting: boolean;
  onChange: (value: ArticleInputPayload) => void;
  onSubmit: () => void;
}

const platforms: { value: PublishPlatform; label: string }[] = [
  { value: "official_site", label: "官网文章" },
  { value: "media_article", label: "媒体稿" },
  { value: "comparison_review", label: "对比评测" },
  { value: "recommendation_list", label: "推荐榜单" },
];

export function ArticleInputForm({
  value,
  isSubmitting,
  onChange,
  onSubmit,
}: ArticleInputFormProps) {
  function update<K extends keyof ArticleInputPayload>(
    key: K,
    nextValue: ArticleInputPayload[K],
  ) {
    onChange({ ...value, [key]: nextValue });
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    onSubmit();
  }

  return (
    <form className="panel stack" onSubmit={handleSubmit}>
      <div className="panel-heading">
        <span>文章输入</span>
        <button disabled={isSubmitting} type="submit">
          {isSubmitting ? "分析中..." : "分析文章"}
        </button>
      </div>
      <label>
        <span>标题</span>
        <input
          required
          value={value.title}
          onChange={(event) => update("title", event.target.value)}
        />
      </label>
      <label>
        <span>正文</span>
        <textarea
          required
          className="body-input"
          value={value.body}
          onChange={(event) => update("body", event.target.value)}
        />
      </label>
      <label>
        <span>图片描述或图片链接</span>
        <textarea
          value={value.image_lines}
          onChange={(event) => update("image_lines", event.target.value)}
        />
      </label>
      <label>
        <span>目标平台</span>
        <select
          value={value.platform}
          onChange={(event) =>
            update("platform", event.target.value as PublishPlatform)
          }
        >
          {platforms.map((platform) => (
            <option key={platform.value} value={platform.value}>
              {platform.label}
            </option>
          ))}
        </select>
      </label>
      <label>
        <span>用户要求</span>
        <textarea
          value={value.user_instructions}
          onChange={(event) => update("user_instructions", event.target.value)}
        />
      </label>
    </form>
  );
}
