"use client";

import { useActionState } from "react";
import { AlertCircle, Loader2, Send } from "lucide-react";
import { submitStudyApplication, type ApplyState } from "../../../actions";
import { Button } from "@/components/Button";

const initial: ApplyState = { ok: false };

type Props = {
  studySlug: string;
  studyTitle: string;
  openRoles: Array<{ title: string; description: string; commitment: string; compensation: string }>;
};

export function ApplyForm({ studySlug, studyTitle, openRoles }: Props) {
  const [state, action, pending] = useActionState(submitStudyApplication, initial);

  return (
    <form action={action} className="flex flex-col gap-5">
      <input type="hidden" name="studySlug" value={studySlug} />
      {/* Honeypot — bots tend to fill every field. */}
      <div className="hidden" aria-hidden>
        <label>
          Website
          <input type="text" name="website" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      {state.message && !state.ok && (
        <div
          role="alert"
          className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800"
        >
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
          <span>{state.message}</span>
        </div>
      )}

      <div className="grid gap-4 md:grid-cols-2">
        <Field
          name="name"
          label="Full name"
          required
          autoComplete="name"
          error={state.fieldErrors?.name}
        />
        <Field
          name="email"
          label="Email"
          type="email"
          required
          autoComplete="email"
          error={state.fieldErrors?.email}
        />
        <Field name="institution" label="Institution" autoComplete="organization" />
        <Field name="country" label="Country" autoComplete="country-name" />
        <Field
          name="professionalRole"
          label="Your role"
          placeholder="e.g. Consultant shoulder surgeon"
        />
        <div>
          <label className="mb-1.5 block text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
            Preferred role on this study
          </label>
          <select
            name="rolePreference"
            defaultValue=""
            className="w-full rounded-md border border-[var(--color-line)] bg-white px-3 py-2.5 text-[14px] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
          >
            <option value="">Open to discuss</option>
            <option value="Site investigator">Site investigator</option>
            <option value="Site coordinator">Site coordinator</option>
            <option value="Research fellow">Research fellow</option>
            <option value="Data analyst">Data analyst</option>
            <option value="Manuscript writer">Manuscript writer</option>
            {openRoles.map((r) =>
              r.title ? (
                <option key={r.title} value={r.title}>
                  {r.title}
                </option>
              ) : null,
            )}
          </select>
        </div>
        <Field name="orcidUrl" label="ORCID URL (optional)" type="url" placeholder="https://orcid.org/0000-0000-0000-0000" />
        <Field name="linkedinUrl" label="LinkedIn (optional)" type="url" placeholder="https://www.linkedin.com/in/…" />
      </div>

      <label className="block">
        <span className="mb-1.5 block text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
          Relevant experience (optional)
        </span>
        <textarea
          name="experience"
          rows={4}
          maxLength={4000}
          placeholder="Prior studies, site setup experience, relevant fellowships…"
          className="w-full rounded-md border border-[var(--color-line)] bg-white px-3 py-2.5 text-[14px] leading-relaxed focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
        />
      </label>

      <label className="block">
        <span className="mb-1.5 block text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
          Why do you want to join {studyTitle || "this study"}?
          <span className="ml-1 text-red-600">*</span>
        </span>
        <textarea
          name="motivation"
          rows={5}
          required
          minLength={10}
          maxLength={4000}
          className="w-full rounded-md border border-[var(--color-line)] bg-white px-3 py-2.5 text-[14px] leading-relaxed focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
        />
        {state.fieldErrors?.motivation && (
          <span className="mt-1 block text-[12px] text-red-600">
            {state.fieldErrors.motivation}
          </span>
        )}
      </label>

      <Button type="submit" disabled={pending} variant="primary">
        {pending ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
            Sending…
          </>
        ) : (
          <>
            <Send className="h-4 w-4" aria-hidden />
            Submit application
          </>
        )}
      </Button>
      <p className="text-[12px] text-[var(--color-slate)]">
        A coordinator will reply within 14 days. You&rsquo;ll receive a confirmation email straight away.
      </p>
    </form>
  );
}

function Field({
  name,
  label,
  type = "text",
  required,
  placeholder,
  autoComplete,
  error,
}: {
  name: string;
  label: string;
  type?: string;
  required?: boolean;
  placeholder?: string;
  autoComplete?: string;
  error?: string;
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {label}
        {required && <span className="ml-1 text-red-600">*</span>}
      </span>
      <input
        name={name}
        type={type}
        required={required}
        placeholder={placeholder}
        autoComplete={autoComplete}
        className="w-full rounded-md border border-[var(--color-line)] bg-white px-3 py-2.5 text-[14px] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
      />
      {error && (
        <span className="mt-1 block text-[12px] text-red-600">{error}</span>
      )}
    </label>
  );
}
