"use client";

import { useState } from "react";
import { Loader2, Send } from "lucide-react";
import { toast } from "sonner";
import { inquiryApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";

export type InquiryFormType =
  | "CONTACT" | "FEEDBACK" | "SEMINAR" | "WORKSHOP" | "TRAINING"
  | "BOOK_SUGGESTION" | "TOPIC_SUGGESTION" | "ABSTRACT" | "SUBSCRIPTION" | "FORUM";

interface InquiryFormProps {
  type: InquiryFormType;
  /** Heading above the form; defaults to a generic bilingual label. */
  headingHi?: string;
  headingEn?: string;
  /** Show the optional subject field. */
  withSubject?: boolean;
}

/**
 * Guest inquiry form → POST /public/inquiries. Replaces the legacy
 * email-only forms: submissions persist and appear in the admin inbox.
 * The hidden "website" field is a honeypot — humans never see it, so a
 * value there marks bot traffic (the API silently drops it).
 */
export function InquiryForm({ type, headingHi, headingEn, withSubject = true }: InquiryFormProps) {
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";

  const [form, setForm] = useState({ name: "", email: "", subject: "", message: "", website: "" });
  const [submitting, setSubmitting] = useState(false);

  const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (form.message.trim().length < 10) {
      toast.error(hi ? "संदेश कम से कम 10 अक्षरों का हो" : "Message must be at least 10 characters");
      return;
    }
    setSubmitting(true);
    try {
      await inquiryApi.create({
        type,
        name: form.name.trim(),
        email: form.email.trim(),
        subject: form.subject.trim() || undefined,
        message: form.message.trim(),
        website: form.website, // honeypot passthrough
      });
      toast.success(
        hi
          ? "आपका संदेश प्राप्त हो गया है। धन्यवाद!"
          : "Your submission has been received. Thank you!"
      );
      setForm({ name: "", email: "", subject: "", message: "", website: "" });
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
        (hi ? "भेजने में त्रुटि हुई। पुनः प्रयास करें।" : "Something went wrong. Please try again.");
      toast.error(message);
    } finally {
      setSubmitting(false);
    }
  };

  const inputCls =
    "w-full rounded-md border border-gray-300 bg-white px-3 py-2.5 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500";

  return (
    <section className="mt-10 rounded-lg border border-gray-200 bg-white p-6 shadow-sm sm:p-8">
      <h2 className="mb-1 text-lg font-bold text-gray-900">
        {hi ? headingHi ?? "जानकारी भेजें" : headingEn ?? "Send Information"}
      </h2>
      <p className="mb-5 text-xs text-gray-500">
        {hi ? headingEn ?? "Send Information" : headingHi ?? "जानकारी भेजें"}
      </p>

      <form onSubmit={onSubmit} className="space-y-4">
        {/* Honeypot — hidden from humans, tempting for bots */}
        <div className="absolute -left-[9999px] top-auto" aria-hidden="true">
          <label>
            Website
            <input type="text" name="website" tabIndex={-1} autoComplete="off"
              value={form.website} onChange={onChange} />
          </label>
        </div>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label className="mb-1.5 block text-sm font-medium text-gray-700">
              {hi ? "नाम" : "Name"} <span className="text-red-500">*</span>
            </label>
            <input name="name" required maxLength={200} value={form.name} onChange={onChange}
              className={inputCls} placeholder={hi ? "आपका नाम" : "Your name"} />
          </div>
          <div>
            <label className="mb-1.5 block text-sm font-medium text-gray-700">
              {hi ? "ईमेल" : "Email"} <span className="text-red-500">*</span>
            </label>
            <input type="email" name="email" required maxLength={320} value={form.email}
              onChange={onChange} className={inputCls} placeholder="you@example.com" />
          </div>
        </div>

        {withSubject && (
          <div>
            <label className="mb-1.5 block text-sm font-medium text-gray-700">
              {hi ? "विषय" : "Subject"}
            </label>
            <input name="subject" maxLength={300} value={form.subject} onChange={onChange}
              className={inputCls} placeholder={hi ? "विषय (वैकल्पिक)" : "Subject (optional)"} />
          </div>
        )}

        <div>
          <label className="mb-1.5 block text-sm font-medium text-gray-700">
            {hi ? "संदेश / विवरण" : "Message / Details"} <span className="text-red-500">*</span>
          </label>
          <textarea name="message" required rows={5} maxLength={10000} value={form.message}
            onChange={onChange} className={inputCls}
            placeholder={hi ? "पूरा विवरण यहाँ लिखें…" : "Write the full details here…"} />
        </div>

        <button type="submit" disabled={submitting}
          className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-indigo-700 disabled:opacity-50">
          {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
          {submitting ? (hi ? "भेजा जा रहा है…" : "Sending…") : (hi ? "भेजें" : "Submit")}
        </button>
      </form>
    </section>
  );
}
