"use client";

import { useState } from "react";
import { MessageSquare, Send, CheckCircle2, AlertCircle } from "lucide-react";

type FormState = "idle" | "submitting" | "success" | "error";

interface CommentFormProps {
  slug: string;
  locale: string;
}

export function CommentForm({ slug, locale }: CommentFormProps) {
  const isEn = locale === "en";
  const [state, setState] = useState<FormState>("idle");
  const [form, setForm] = useState({ name: "", email: "", content: "" });
  const [errors, setErrors] = useState<Partial<typeof form>>({});

  function validate() {
    const e: Partial<typeof form> = {};
    if (!form.name.trim())
      e.name = isEn ? "Name is required" : "نام الزامی است";
    if (!form.content.trim() || form.content.trim().length < 10)
      e.content = isEn
        ? "Comment must be at least 10 characters"
        : "نظر باید حداقل ۱۰ کاراکتر باشد";
    return e;
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length > 0) {
      setErrors(errs);
      return;
    }
    setErrors({});
    setState("submitting");

    try {
      const res = await fetch(`/api/blog/${slug}/comments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          authorName: form.name.trim(),
          authorEmail: form.email.trim() || undefined,
          content: form.content.trim(),
        }),
      });
      if (!res.ok) throw new Error("Failed");
      setState("success");
      setForm({ name: "", email: "", content: "" });
    } catch {
      setState("error");
    }
  }

  if (state === "success") {
    return (
      <div className="rounded-2xl border border-green-100 bg-green-50 p-6 text-center">
        <CheckCircle2 className="mx-auto mb-3 h-10 w-10 text-green-500" />
        <h3 className="mb-1 text-base font-semibold text-gray-900">
          {isEn ? "Comment submitted!" : "نظر ثبت شد!"}
        </h3>
        <p className="text-sm text-gray-500">
          {isEn
            ? "Your comment is awaiting moderation and will appear shortly."
            : "نظر شما بررسی می‌شود و به‌زودی نمایش داده می‌شود."}
        </p>
        <button
          onClick={() => setState("idle")}
          className="mt-4 text-sm font-medium text-brand-700 hover:underline"
        >
          {isEn ? "Leave another comment" : "ثبت نظر دیگر"}
        </button>
      </div>
    );
  }

  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
      <div className="mb-5 flex items-center gap-2">
        <div className="flex h-8 w-8 items-center justify-center rounded-xl bg-brand-50">
          <MessageSquare className="h-4 w-4 text-brand-700" />
        </div>
        <h3 className="text-base font-semibold text-gray-900">
          {isEn ? "Leave a comment" : "ثبت نظر"}
        </h3>
      </div>

      {state === "error" && (
        <div className="mb-4 flex items-center gap-2 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
          <AlertCircle className="h-4 w-4 shrink-0" />
          {isEn
            ? "Failed to submit. Please try again."
            : "ارسال ناموفق بود. دوباره تلاش کنید."}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4" noValidate>
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="mb-1.5 block text-sm font-medium text-gray-700">
              {isEn ? "Name" : "نام"} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              placeholder={isEn ? "Your name" : "نام شما"}
              className={`w-full rounded-xl border px-3 py-2.5 text-sm outline-none transition focus:ring-2 focus:ring-brand-500/30 ${
                errors.name
                  ? "border-red-300 bg-red-50"
                  : "border-gray-200 bg-gray-50 focus:border-brand-400"
              }`}
            />
            {errors.name && (
              <p className="mt-1 text-xs text-red-600">{errors.name}</p>
            )}
          </div>
          <div>
            <label className="mb-1.5 block text-sm font-medium text-gray-700">
              {isEn ? "Email" : "ایمیل"}{" "}
              <span className="text-xs text-gray-400">
                ({isEn ? "optional" : "اختیاری"})
              </span>
            </label>
            <input
              type="email"
              value={form.email}
              onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
              placeholder={isEn ? "your@email.com" : "ایمیل شما (نمایش داده نمی‌شود)"}
              className="w-full rounded-xl border border-gray-200 bg-gray-50 px-3 py-2.5 text-sm outline-none transition focus:border-brand-400 focus:ring-2 focus:ring-brand-500/30"
            />
          </div>
        </div>

        <div>
          <label className="mb-1.5 block text-sm font-medium text-gray-700">
            {isEn ? "Comment" : "نظر"} <span className="text-red-500">*</span>
          </label>
          <textarea
            rows={4}
            value={form.content}
            onChange={(e) =>
              setForm((f) => ({ ...f, content: e.target.value }))
            }
            placeholder={
              isEn
                ? "Share your thoughts..."
                : "نظر خود را بنویسید..."
            }
            className={`w-full resize-none rounded-xl border px-3 py-2.5 text-sm outline-none transition focus:ring-2 focus:ring-brand-500/30 ${
              errors.content
                ? "border-red-300 bg-red-50"
                : "border-gray-200 bg-gray-50 focus:border-brand-400"
            }`}
          />
          {errors.content && (
            <p className="mt-1 text-xs text-red-600">{errors.content}</p>
          )}
        </div>

        <div className="flex items-center justify-between">
          <p className="text-xs text-gray-400">
            {isEn
              ? "Comments are reviewed before publishing."
              : "نظرات قبل از انتشار بررسی می‌شوند."}
          </p>
          <button
            type="submit"
            disabled={state === "submitting"}
            className="inline-flex items-center gap-2 rounded-xl bg-brand-700 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-brand-800 disabled:opacity-60"
          >
            {state === "submitting" ? (
              <>
                <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                {isEn ? "Submitting..." : "در حال ارسال..."}
              </>
            ) : (
              <>
                <Send className="h-4 w-4" />
                {isEn ? "Submit comment" : "ثبت نظر"}
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
