"use client";

import { useState } from "react";
import { Button } from "@/components/button";

interface FormState {
  fullName: string;
  email: string;
  organization: string;
  phone: string;
  projectType: string;
  budgetRange: string;
  message: string;
}

const initialState: FormState = {
  fullName: "",
  email: "",
  organization: "",
  phone: "",
  projectType: "",
  budgetRange: "",
  message: "",
};

export function ContactForm() {
  const [form, setForm] = useState<FormState>(initialState);
  const [status, setStatus] =
    useState<"idle" | "submitting" | "success" | "error">("idle");
  const [errorMessage, setErrorMessage] = useState("");

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setStatus("submitting");
    setErrorMessage("");

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });

      if (response.ok) {
        setStatus("success");
        setForm(initialState);
      } else {
        const data = await response.json().catch(() => null);
        setStatus("error");
        setErrorMessage(data?.message ?? "No se pudo enviar el mensaje.");
      }
    } catch (error) {
      console.error(error);
      setStatus("error");
      setErrorMessage("Ocurrió un problema inesperado. Intenta nuevamente.");
    }
  }

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

  return (
    <form
      onSubmit={handleSubmit}
      className="space-y-6 rounded-[28px] border border-slate-100 bg-[#f8fafc] p-8 shadow-sm"
    >
      <div className="grid gap-6 sm:grid-cols-2">
        <label className="space-y-2">
          <span className="text-sm font-medium text-slate-700">Nombre completo *</span>
          <input
            required
            name="fullName"
            value={form.fullName}
            onChange={handleChange}
            placeholder="Ej. Dra. Ana López"
            className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 shadow-sm focus:border-[#1d6fbf] focus:outline-none focus:ring-2 focus:ring-[#1d6fbf]/30"
          />
        </label>
        <label className="space-y-2">
          <span className="text-sm font-medium text-slate-700">Correo electrónico *</span>
          <input
            required
            type="email"
            name="email"
            value={form.email}
            onChange={handleChange}
            placeholder="contacto@tuinstitucion.com"
            className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 shadow-sm focus:border-[#1d6fbf] focus:outline-none focus:ring-2 focus:ring-[#1d6fbf]/30"
          />
        </label>
        <label className="space-y-2">
          <span className="text-sm font-medium text-slate-700">Institución</span>
          <input
            name="organization"
            value={form.organization}
            onChange={handleChange}
            placeholder="Hospital, clínica, prepaga u organismo"
            className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 shadow-sm focus:border-[#1d6fbf] focus:outline-none focus:ring-2 focus:ring-[#1d6fbf]/30"
          />
        </label>
        <label className="space-y-2">
          <span className="text-sm font-medium text-slate-700">Teléfono</span>
          <input
            name="phone"
            value={form.phone}
            onChange={handleChange}
            placeholder="Opcional"
            className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 shadow-sm focus:border-[#1d6fbf] focus:outline-none focus:ring-2 focus:ring-[#1d6fbf]/30"
          />
        </label>
      </div>
      <label className="space-y-2">
        <span className="text-sm font-medium text-slate-700">
          Módulo o proceso que te interesa
        </span>
        <input
          name="projectType"
          value={form.projectType}
          onChange={handleChange}
          placeholder="Ej. Enfermería Mobile, PCI, Guardia Inteligente"
          className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 shadow-sm focus:border-[#1d6fbf] focus:outline-none focus:ring-2 focus:ring-[#1d6fbf]/30"
        />
      </label>
      <label className="space-y-2">
        <span className="text-sm font-medium text-slate-700">Tamaño de la institución</span>
        <input
          name="budgetRange"
          value={form.budgetRange}
          onChange={handleChange}
          placeholder="Ej. 350 camas, 20 quirófanos"
          className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 shadow-sm focus:border-[#1d6fbf] focus:outline-none focus:ring-2 focus:ring-[#1d6fbf]/30"
        />
      </label>
      <label className="space-y-2">
        <span className="text-sm font-medium text-slate-700">Cuéntanos más *</span>
        <textarea
          required
          rows={4}
          name="message"
          value={form.message}
          onChange={handleChange}
          placeholder="Comparte tus procesos actuales y qué te gustaría resolver."
          className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 shadow-sm focus:border-[#1d6fbf] focus:outline-none focus:ring-2 focus:ring-[#1d6fbf]/30"
        />
      </label>
      {status === "error" ? (
        <p className="text-sm text-rose-600" role="alert" aria-live="assertive">
          {errorMessage}
        </p>
      ) : null}
      {status === "success" ? (
        <p
          className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700"
          role="status"
          aria-live="polite"
        >
          Gracias por tu interés. Nuestro equipo responderá muy pronto.
        </p>
      ) : null}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <p className="text-xs text-slate-500">
          Al enviar aceptas el tratamiento seguro de tus datos.
        </p>
        <Button
          type="submit"
          variant="primary"
          className="px-8"
          disabled={status === "submitting"}
        >
          {status === "submitting" ? "Enviando..." : "Enviar mensaje"}
        </Button>
      </div>
    </form>
  );
}
