"use client";

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

const initial: ProposeState = { ok: false };

export function ProposalForm() {
  const [state, action, pending] = useActionState(submitStudyProposal, initial);

  return (
    <form action={action} className="flex flex-col gap-5">
      <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>
      )}

      <Field
        name="title"
        label="Proposal title"
        required
        minLength={8}
        error={state.fieldErrors?.title}
      />

      <div className="grid gap-4 md:grid-cols-2">
        <Field name="proposerName" label="Your name" required autoComplete="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="specialty" label="Specialty" placeholder="e.g. Shoulder, Hip, Trauma" />
        <Field
          name="orcidUrl"
          label="ORCID URL (optional)"
          type="url"
          placeholder="https://orcid.org/0000-0000-0000-0000"
        />
      </div>

      <TextField
        name="background"
        label="Background / rationale"
        required
        rows={5}
        minLength={30}
        hint="Why does this question need answering? What evidence gap does it address?"
        error={state.fieldErrors?.background}
      />
      <TextField
        name="hypothesis"
        label="Primary hypothesis or aim"
        required
        rows={3}
        minLength={10}
        error={state.fieldErrors?.hypothesis}
      />
      <TextField
        name="design"
        label="Proposed design (optional)"
        rows={4}
        hint="RCT, prospective cohort, registry, etc."
      />
      <TextField
        name="resourcesNeeded"
        label="Resources needed (optional)"
        rows={3}
        hint="Participating sites, sample size, funding, ethics support."
      />
      <Field
        name="fundingStatus"
        label="Funding status (optional)"
        placeholder="e.g. Unfunded, NIHR submitted, Wellcome"
      />

      <Button type="submit" disabled={pending} variant="primary">
        {pending ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
            Submitting…
          </>
        ) : (
          <>
            <Send className="h-4 w-4" aria-hidden />
            Submit proposal
          </>
        )}
      </Button>
      <p className="text-[12px] text-[var(--color-slate)]">
        The steering committee reviews proposals monthly. You&rsquo;ll hear back within 30 days.
      </p>
    </form>
  );
}

function Field({
  name,
  label,
  type = "text",
  required,
  placeholder,
  autoComplete,
  minLength,
  error,
}: {
  name: string;
  label: string;
  type?: string;
  required?: boolean;
  placeholder?: string;
  autoComplete?: string;
  minLength?: number;
  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}
        minLength={minLength}
        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>
  );
}

function TextField({
  name,
  label,
  required,
  rows,
  minLength,
  hint,
  error,
}: {
  name: string;
  label: string;
  required?: boolean;
  rows: number;
  minLength?: number;
  hint?: 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>
      <textarea
        name={name}
        rows={rows}
        required={required}
        minLength={minLength}
        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)]"
      />
      {hint && (
        <span className="mt-1 block text-[12px] text-[var(--color-slate)]">{hint}</span>
      )}
      {error && (
        <span className="mt-1 block text-[12px] text-red-600">{error}</span>
      )}
    </label>
  );
}
