"use client";

import { useActionState, useState } from "react";
import { submitContact } from "@/app/actions/forms";
import type { ActionState } from "@/app/lib/definitions";

const subjects = [
  "General enquiry",
  "Admissions",
  "Programs & curriculum",
  "Fees & payments",
  "Partnerships",
  "Other",
];

const initialState: ActionState = {};

export default function ContactForm() {
  const [formKey, setFormKey] = useState(0);

  return (
    <ContactFormInner key={formKey} onReset={() => setFormKey((k) => k + 1)} />
  );
}

function ContactFormInner({ onReset }: { onReset: () => void }) {
  const [state, action, pending] = useActionState(submitContact, initialState);

  if (state?.success) {
    return (
      <div className="rounded-2xl border border-[#e9eefc] bg-white p-6 sm:p-10 md:p-14 text-center">
        <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-[#1f3fb8]/10">
          <svg
            className="h-7 w-7 text-[#1f3fb8]"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2.5}
            aria-hidden="true"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M5 13l4 4L19 7"
            />
          </svg>
        </div>
        <h3 className="mt-5 text-2xl font-bold tracking-tight text-[#132b87]">
          Message sent
        </h3>
        <p className="mt-3 text-[#5a688d] leading-relaxed max-w-md mx-auto">
          Thanks for reaching out. Our team will get back to you within 1 - 2
          working days.
        </p>
        <button
          type="button"
          onClick={onReset}
          className="mt-7 text-sm font-semibold text-[#1f3fb8] hover:text-[#18339a] transition"
        >
          Send another message →
        </button>
      </div>
    );
  }

  return (
    <form
      action={action}
      className="rounded-2xl border border-[#e9eefc] bg-white p-5 sm:p-6 md:p-10 relative"
    >
      <div
        aria-hidden="true"
        className="absolute -left-[9999px] h-0 w-0 overflow-hidden"
      >
        <label>
          Website
          <input type="text" name="website" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-5 gap-y-5">
        <Field label="Full name" required error={state?.errors?.name?.[0]}>
          <input
            type="text"
            name="name"
            required
            className={inputCls}
            placeholder="Your name"
          />
        </Field>
        <Field label="Email" required error={state?.errors?.email?.[0]}>
          <input
            type="email"
            name="email"
            required
            className={inputCls}
            placeholder="you@example.com"
          />
        </Field>
        <Field label="Phone" error={state?.errors?.phone?.[0]}>
          <input
            type="tel"
            name="phone"
            className={inputCls}
            placeholder="+254 7XX XXX XXX"
          />
        </Field>
        <Field label="Subject" required error={state?.errors?.subject?.[0]}>
          <select name="subject" required className={inputCls} defaultValue="">
            <option value="">Select a topic</option>
            {subjects.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
          </select>
        </Field>
        <div className="sm:col-span-2">
          <Field label="Message" required error={state?.errors?.message?.[0]}>
            <textarea
              name="message"
              required
              rows={4}
              className={`${inputCls} resize-y min-h-28`}
              placeholder="How can we help?"
            />
          </Field>
        </div>
      </div>

      {state?.message && !state.success && (
        <p className="mt-4 text-sm text-red-600" role="alert">
          {state.message}
        </p>
      )}

      <div className="mt-8 flex flex-col-reverse sm:flex-row sm:items-center sm:justify-between gap-4">
        <button
          type="submit"
          disabled={pending}
          className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3 bg-[#1f3fb8] text-white text-sm font-semibold rounded-full hover:bg-[#18339a] transition disabled:opacity-60"
        >
          {pending ? "Sending..." : "Send message"}
          <span aria-hidden="true">→</span>
        </button>
      </div>
    </form>
  );
}

const inputCls =
  "w-full rounded-lg border border-[#e3e8f5] bg-white px-3.5 py-2.5 text-sm text-[#132b87] placeholder:text-[#a5b0cc] focus:outline-none focus:border-[#1f3fb8] focus:ring-2 focus:ring-[#1f3fb8]/15 transition";

function Field({
  label,
  required,
  error,
  children,
}: {
  label: string;
  required?: boolean;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <label className="block">
      <span className="block text-xs font-medium text-[#5a688d] mb-1.5">
        {label}
        {required && <span className="text-[#1f3fb8]"> *</span>}
      </span>
      {children}
      {error && (
        <span className="mt-1 block text-xs text-red-600" role="alert">
          {error}
        </span>
      )}
    </label>
  );
}
