"use client";

import { useState } from "react";
import { apiFetch } from "@/app/lib/api-client";

interface NewsletterSubscribeProps {
  locale: string;
  citySlug?: string;
  list?: "city" | "meetup" | "general";
  className?: string;
}

const copy = {
  zh: {
    title: "订阅城市与活动通讯",
    hint: "通过 Listmonk 接收新活动、城市更新（可随时退订）",
    email: "邮箱地址",
    name: "称呼（可选）",
    submit: "订阅",
    success: "订阅成功，请查收确认邮件",
    error: "订阅失败，请稍后再试",
  },
  en: {
    title: "Subscribe to city & event updates",
    hint: "Get meetup and city news via Listmonk (unsubscribe anytime)",
    email: "Email",
    name: "Name (optional)",
    submit: "Subscribe",
    success: "Subscribed — check your inbox to confirm",
    error: "Subscription failed, please try again",
  },
};

export default function NewsletterSubscribe({
  locale,
  citySlug = "",
  list = "general",
  className = "",
}: NewsletterSubscribeProps) {
  const c = locale === "zh" ? copy.zh : copy.en;
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">("idle");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!email.trim()) return;
    setStatus("loading");
    try {
      await apiFetch("/api/newsletter/subscribe", {
        method: "POST",
        body: JSON.stringify({ email, name, citySlug, list }),
      });
      setStatus("success");
      setEmail("");
      setName("");
    } catch {
      setStatus("error");
    }
  }

  return (
    <form
      onSubmit={handleSubmit}
      className={`rounded-2xl border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-800 dark:bg-gray-900 ${className}`}
    >
      <p className="text-sm font-semibold text-gray-900 dark:text-gray-100">{c.title}</p>
      <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">{c.hint}</p>
      <div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
        <input
          type="email"
          required
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder={c.email}
          className="rounded-xl border border-gray-200 px-4 py-2.5 text-sm dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
        />
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder={c.name}
          className="rounded-xl border border-gray-200 px-4 py-2.5 text-sm dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
        />
        <button
          type="submit"
          disabled={status === "loading"}
          className="rounded-xl bg-[#ff4d4f] px-5 py-2.5 text-sm font-semibold text-white hover:bg-[#ff7a45] disabled:opacity-60"
        >
          {c.submit}
        </button>
      </div>
      {status === "success" ? <p className="mt-3 text-sm text-emerald-600 dark:text-emerald-400">{c.success}</p> : null}
      {status === "error" ? <p className="mt-3 text-sm text-red-600 dark:text-red-400">{c.error}</p> : null}
    </form>
  );
}
