"use client";

import { useState, type FormEvent } from "react";
import {
  volunteerActivities,
  volunteerDivisions,
  type VolunteerActivity,
  type VolunteerDivision,
} from "@/lib/volunteer-applications";
import { usePublicCopy } from "@/lib/cms/use-public-copy";
import { InlineText } from "@/components/cms/LandingInlineEditor";

type FormState = {
  fullName: string;
  nickname: string;
  email: string;
  phone: string;
  primaryActivity: VolunteerActivity | "";
  motivation: string;
  contactConsent: boolean;
};

const initialForm: FormState = {
  fullName: "",
  nickname: "",
  email: "",
  phone: "",
  primaryActivity: "",
  motivation: "",
  contactConsent: false,
};

type Props = {
  initialDivision?: VolunteerDivision | null;
  onDivisionChange?: (division: VolunteerDivision | null) => void;
};

export default function VolunteerApplicationForm({
  initialDivision,
  onDivisionChange,
}: Props) {
  const copy = usePublicCopy();
  const [form, setForm] = useState(initialForm);
  const [localDivision, setLocalDivision] = useState<VolunteerDivision | "">("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const preferredDivision = initialDivision === undefined
    ? localDivision
    : initialDivision ?? "";

  function updateDivision(value: string) {
    const division = volunteerDivisions.find((item) => item.value === value)?.value ?? "";
    if (initialDivision === undefined) setLocalDivision(division);
    onDivisionChange?.(division || null);
  }

  function updateActivity(value: string) {
    const activity = volunteerActivities.find((item) => item.value === value)?.value ?? "";
    setForm((current) => ({ ...current, primaryActivity: activity }));
  }

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    setSuccess("");
    setSubmitting(true);

    try {
      const response = await fetch("/api/volunteer-applications", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, preferredDivision }),
      });
      const result = await response.json() as {
        success?: boolean;
        error?: string;
        message?: string;
      };
      if (!response.ok || !result.success) {
        throw new Error(result.error || copy.volunteerSubmitError);
      }
      setSuccess(result.message || copy.volunteerSuccessFallback);
      setForm(initialForm);
      if (initialDivision === undefined) setLocalDivision("");
      onDivisionChange?.(null);
    } catch (submitError) {
      setError(
        submitError instanceof Error
          ? submitError.message
          : copy.volunteerConnectionError,
      );
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <form className={"vol-form"} onSubmit={submit}>
      {error && <p className={"vol-formError"} role="alert">{error}</p>}
      {success && (
        <div className={"vol-toast"} role="status" aria-live="polite">
          <p>{success}</p>
          <button
            className={"vol-toastClose"}
            type="button"
            aria-label={copy.volunteerCloseNotification}
            onClick={() => setSuccess("")}
          >
            ×
          </button>
        </div>
      )}

      <div className={"vol-formGrid"}>
        <div className={"vol-field"}>
          <label htmlFor="volunteer-full-name">
            <InlineText path="publicCopy.volunteerFullName" value={copy.volunteerFullName} /> <span className={"vol-required"}>*</span>
          </label>
          <input
            id="volunteer-full-name"
            className={"vol-control"}
            autoComplete="name"
            maxLength={150}
            required
            value={form.fullName}
            onChange={(event) => setForm({ ...form, fullName: event.target.value })}
          />
        </div>
        <div className={"vol-field"}>
          <label htmlFor="volunteer-nickname">
            <InlineText path="publicCopy.volunteerNickname" value={copy.volunteerNickname} /> <span className={"vol-required"}>*</span>
          </label>
          <input
            id="volunteer-nickname"
            className={"vol-control"}
            autoComplete="nickname"
            maxLength={80}
            required
            placeholder={copy.volunteerNicknamePlaceholder}
            onChange={(event) => setForm({ ...form, nickname: event.target.value })}
          />
        </div>
        <div className={"vol-field"}>
          <label htmlFor="volunteer-email">
            <InlineText path="publicCopy.volunteerEmail" value={copy.volunteerEmail} /> <span className={"vol-required"}>*</span>
          </label>
          <input
            id="volunteer-email"
            className={"vol-control"}
            autoComplete="email"
            maxLength={190}
            required
            type="email"
            value={form.email}
            onChange={(event) => setForm({ ...form, email: event.target.value })}
          />
          <span className={"vol-fieldHint"}><InlineText path="publicCopy.volunteerEmailHint" value={copy.volunteerEmailHint} /></span>
        </div>
        <div className={"vol-field"}>
          <label htmlFor="volunteer-phone">
            <InlineText path="publicCopy.volunteerPhone" value={copy.volunteerPhone} /> <span className={"vol-required"}>*</span>
          </label>
          <input
            id="volunteer-phone"
            className={"vol-control"}
            autoComplete="tel"
            maxLength={30}
            minLength={8}
            required
            type="tel"
            placeholder={copy.volunteerPhonePlaceholder}
            value={form.phone}
            onChange={(event) => setForm({ ...form, phone: event.target.value })}
          />
        </div>
      </div>

      <div className={"vol-field"}>
        <label htmlFor="volunteer-division"><InlineText path="publicCopy.volunteerDivision" value={copy.volunteerDivision} /> <span className={"vol-fieldHint"}>(<InlineText path="publicCopy.volunteerOptional" value={copy.volunteerOptional} />)</span></label>
        <select
          id="volunteer-division"
          className={"vol-control"}
          value={preferredDivision}
          onChange={(event) => updateDivision(event.target.value)}
        >
          <option value="">{copy.volunteerChooseDivision}</option>
          {volunteerDivisions.map((division) => (
            <option key={division.value} value={division.value}>{division.label}</option>
          ))}
        </select>
        <span className={"vol-fieldHint"}><InlineText path="publicCopy.volunteerDivisionHint" value={copy.volunteerDivisionHint} /></span>
      </div>

      <div className={"vol-field"}>
        <label htmlFor="volunteer-activity"><InlineText path="publicCopy.volunteerActivity" value={copy.volunteerActivity} /> <span className={"vol-fieldHint"}>(<InlineText path="publicCopy.volunteerOptional" value={copy.volunteerOptional} />)</span></label>
        <select
          id="volunteer-activity"
          className={"vol-control"}
          value={form.primaryActivity}
          onChange={(event) => updateActivity(event.target.value)}
        >
          <option value="">{copy.volunteerChooseActivity}</option>
          {volunteerActivities.map((activity) => (
            <option key={activity.value} value={activity.value}>{activity.label}</option>
          ))}
        </select>
      </div>

      <div className={"vol-field"}>
        <label htmlFor="volunteer-motivation"><InlineText path="publicCopy.volunteerMotivation" value={copy.volunteerMotivation} /> <span className={"vol-fieldHint"}>(<InlineText path="publicCopy.volunteerOptional" value={copy.volunteerOptional} />)</span></label>
        <textarea
          id="volunteer-motivation"
          className={`${"vol-control"} ${"vol-textarea"}`}
          maxLength={3000}
          placeholder={copy.volunteerMotivationPlaceholder}
          value={form.motivation}
          onChange={(event) => setForm({ ...form, motivation: event.target.value })}
        />
      </div>

      <label className={"vol-consent"} htmlFor="volunteer-contact-consent">
        <input
          id="volunteer-contact-consent"
          required
          type="checkbox"
          checked={form.contactConsent}
          onChange={(event) => setForm({ ...form, contactConsent: event.target.checked })}
        />
        <span>
          <InlineText path="publicCopy.volunteerConsent" value={copy.volunteerConsent} /> <strong><InlineText path="publicCopy.volunteerConsentEmphasis" value={copy.volunteerConsentEmphasis} /></strong>
        </span>
      </label>

      <button className={`${"vol-button"} ${"vol-submitButton"}`} disabled={submitting} type="submit">
        {submitting ? copy.volunteerSubmitting : <InlineText path="publicCopy.volunteerSubmit" value={copy.volunteerSubmit} />}
        <span aria-hidden="true">→</span>
      </button>
      <p className={"vol-formNote"}>
        {copy.volunteerFormNote}
      </p>
    </form>
  );
}
