"use client";

import { useState } from "react";
import { useTranslation } from "next-i18next";
import { ArrowRight } from "lucide-react";

type FormValues = {
  name: string;
  nationality: string;
  email: string;
  topic: string;
  story: string;
};

type Errors = Partial<Record<keyof FormValues, string>>;

export default function ShareStoryForm() {
  const { t } = useTranslation("expat");

  const [values, setValues] = useState<FormValues>({
    name: "",
    nationality: "",
    email: "",
    topic: "",
    story: "",
  });
  const [errors, setErrors] = useState<Errors>({});
  const [loading, setLoading] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);

  function handleChange(
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) {
    const { name, value } = e.target;
    setValues((prev) => ({ ...prev, [name]: value }));
    setErrors((prev) => ({ ...prev, [name]: undefined }));
  }

  function validate(): Errors {
    const next: Errors = {};
    if (!values.name.trim()) next.name = t("stories.shareForm.required");
    if (!values.email || !/\S+@\S+\.\S+/.test(values.email))
      next.email = t("stories.shareForm.emailInvalid");
    if (!values.story.trim()) next.story = t("stories.shareForm.required");
    return next;
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitted(false);
    setServerError(null);

    const validationErrors = validate();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      return;
    }

    setLoading(true);
    try {
      const res = await fetch("/api/sendEmail", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          firstName: values.name,
          lastName: values.nationality || "-",
          phone: "-",
          email: values.email,
          message: `[${t("stories.shareForm.topic")}: ${
            values.topic || "-"
          }]\n\n${values.story}`,
        }),
      });
      if (!res.ok) throw new Error(t("stories.shareForm.serverError"));

      setSubmitted(true);
      setValues({ name: "", nationality: "", email: "", topic: "", story: "" });
    } catch {
      setServerError(t("stories.shareForm.serverError"));
    } finally {
      setLoading(false);
    }
  }

  return (
    <form
      onSubmit={onSubmit}
      className="rounded-2xl border border-border bg-white p-6 shadow-xl sm:p-8"
    >
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <div>
          <label className="block text-sm font-medium text-gray-700">
            {t("stories.shareForm.name")}*
          </label>
          <input
            name="name"
            value={values.name}
            onChange={handleChange}
            placeholder={t("stories.shareForm.namePh")}
            className={`mt-1 h-10 w-full rounded-xl border px-3 text-sm outline-none focus:border-sky-400 ${
              errors.name ? "border-red-500" : "border-gray-300"
            }`}
          />
          {errors.name && (
            <p className="mt-1 text-xs text-red-600">{errors.name}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700">
            {t("stories.shareForm.nationality")}
          </label>
          <input
            name="nationality"
            value={values.nationality}
            onChange={handleChange}
            placeholder={t("stories.shareForm.nationalityPh")}
            className="mt-1 h-10 w-full rounded-xl border border-gray-300 px-3 text-sm outline-none focus:border-sky-400"
          />
        </div>
      </div>

      <div className="mt-4">
        <label className="block text-sm font-medium text-gray-700">
          {t("stories.shareForm.email")}*
        </label>
        <input
          type="email"
          name="email"
          value={values.email}
          onChange={handleChange}
          placeholder={t("stories.shareForm.emailPh")}
          className={`mt-1 h-10 w-full rounded-xl border px-3 text-sm outline-none focus:border-sky-400 ${
            errors.email ? "border-red-500" : "border-gray-300"
          }`}
        />
        {errors.email && (
          <p className="mt-1 text-xs text-red-600">{errors.email}</p>
        )}
      </div>

      <div className="mt-4">
        <label className="block text-sm font-medium text-gray-700">
          {t("stories.shareForm.topic")}
        </label>
        <input
          name="topic"
          value={values.topic}
          onChange={handleChange}
          // placeholder={t("stories.shareForm.topicPh")}
          className="mt-1 h-10 w-full rounded-xl border border-gray-300 px-3 text-sm outline-none focus:border-sky-400"
        />
      </div>

      <div className="mt-4">
        <label className="block text-sm font-medium text-gray-700">
          {t("stories.shareForm.story")}*
        </label>
        <textarea
          name="story"
          rows={4}
          value={values.story}
          onChange={handleChange}
          placeholder={t("stories.shareForm.storyPh")}
          className={`mt-1 w-full rounded-xl border px-3 py-2 text-sm outline-none focus:border-sky-400 ${
            errors.story ? "border-red-500" : "border-gray-300"
          }`}
        />
        {errors.story && (
          <p className="mt-1 text-xs text-red-600">{errors.story}</p>
        )}
      </div>

      {submitted && (
        <div
          className="mt-4 rounded-lg border border-green-300 bg-green-50 px-4 py-2 text-sm text-green-700"
          role="alert"
        >
          {t("stories.shareForm.ok")}
        </div>
      )}
      {serverError && (
        <div
          className="mt-4 rounded-lg border border-red-300 bg-red-50 px-4 py-2 text-sm text-red-700"
          role="alert"
        >
          {serverError}
        </div>
      )}

      <button
        type="submit"
        disabled={loading}
        className="mt-6 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-[#051973] px-5 py-2.5 text-sm font-semibold text-white transition hover:brightness-110 disabled:opacity-60"
      >
        {loading
          ? t("stories.shareForm.sending")
          : t("stories.shareForm.submit")}
        {!loading && <ArrowRight className="h-4 w-4" />}
      </button>
    </form>
  );
}
