"use client";
import { useActionState, useRef, useState, type ChangeEvent } from "react";
import { Camera, ChevronDown, User as UserIcon } from "lucide-react";
import { submitApplication, type JoinFormState } from "./actions";
import { COUNTRIES } from "@/lib/membership/countries";
import { PROFESSIONAL_ROLES } from "@/lib/membership/application-schema";
import { Button } from "@/components/Button";

const initial: JoinFormState = { ok: false };

export function JoinForm() {
  const [state, formAction, pending] = useActionState(submitApplication, initial);
  const [showOptional, setShowOptional] = useState(false);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const avatarInputRef = useRef<HTMLInputElement>(null);

  function handleAvatarChange(e: ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) {
      setAvatarPreview(null);
      return;
    }
    if (file.size > 6 * 1024 * 1024) {
      window.alert("Image must be under 6 MB.");
      if (avatarInputRef.current) avatarInputRef.current.value = "";
      setAvatarPreview(null);
      return;
    }
    const reader = new FileReader();
    reader.onload = () => setAvatarPreview(reader.result as string);
    reader.readAsDataURL(file);
  }

  return (
    <form action={formAction} className="space-y-6">
      {state.message && (
        <div className="rounded-md border border-[var(--color-line)] bg-[var(--color-mist)] p-3 text-sm text-[var(--color-ink)]">
          {state.message}
        </div>
      )}

      <div aria-hidden="true" className="absolute left-[-9999px] top-[-9999px] h-0 w-0 overflow-hidden">
        <label>
          Website (leave blank)
          <input type="text" name="website" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      <Field label="Full name" name="name" error={state.fieldErrors?.name} required />
      <Field
        label="Email"
        name="email"
        type="email"
        error={state.fieldErrors?.email}
        required
      />
      <Field
        label="Password (min 12 characters)"
        name="password"
        type="password"
        error={state.fieldErrors?.password}
        required
      />

      <SelectField
        label="Country"
        name="country"
        error={state.fieldErrors?.country}
        required
        options={COUNTRIES}
      />
      <Field
        label="Institution / hospital"
        name="institution"
        error={state.fieldErrors?.institution}
        required
      />
      <SelectField
        label="Role"
        name="professionalRole"
        error={state.fieldErrors?.professionalRole}
        required
        options={PROFESSIONAL_ROLES}
      />

      <TextAreaField
        label="Why do you want to join? (max 200 characters)"
        name="motivationText"
        error={state.fieldErrors?.motivationText}
        required
        maxLength={200}
      />

      {/* Optional expandable section */}
      <div className="overflow-hidden rounded-xl border border-[var(--color-line)] bg-[var(--color-mist)]/30">
        <button
          type="button"
          onClick={() => setShowOptional((v) => !v)}
          aria-expanded={showOptional}
          className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left transition-colors hover:bg-[var(--color-mist)]/60"
        >
          <div>
            <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              Optional — About you
            </div>
            <div className="mt-0.5 text-[14px] font-semibold text-[var(--color-ink)]">
              Profile photo, specialty, ORCID, LinkedIn, website
            </div>
            <div className="mt-0.5 text-[12px] text-[var(--color-slate)]">
              Skip for now — you can add these later from your account page.
            </div>
          </div>
          <ChevronDown
            className={`h-5 w-5 shrink-0 text-[var(--color-slate)] transition-transform ${showOptional ? "rotate-180" : ""}`}
            aria-hidden
          />
        </button>
        {showOptional && (
          <div className="space-y-5 border-t border-[var(--color-line)] bg-white p-5">
            <div>
              <span className="mb-2 block text-sm font-semibold text-[var(--color-ink)]">
                Profile photo
              </span>
              <div className="flex items-center gap-4">
                <div className="relative h-20 w-20 overflow-hidden rounded-full border border-[var(--color-line)] bg-[var(--color-mist)]">
                  {avatarPreview ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={avatarPreview}
                      alt="Preview"
                      className="h-full w-full object-cover"
                    />
                  ) : (
                    <div className="flex h-full w-full items-center justify-center text-[var(--color-slate)]">
                      <UserIcon className="h-8 w-8" aria-hidden />
                    </div>
                  )}
                </div>
                <div className="flex flex-col gap-1.5">
                  <input
                    ref={avatarInputRef}
                    type="file"
                    name="avatar"
                    accept="image/jpeg,image/png,image/webp,image/gif"
                    onChange={handleAvatarChange}
                    className="hidden"
                    id="avatar-input"
                  />
                  <label
                    htmlFor="avatar-input"
                    className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg border border-[var(--color-line)] bg-white px-3 py-1.5 text-[13px] font-semibold text-[var(--color-ink)] transition-colors hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                  >
                    <Camera className="h-3.5 w-3.5" aria-hidden />
                    {avatarPreview ? "Change photo" : "Upload photo"}
                  </label>
                  <span className="text-[11px] text-[var(--color-slate)]">
                    JPG/PNG/WEBP · max 6 MB. Square works best.
                  </span>
                </div>
              </div>
            </div>

            <TextAreaField
              label="Short bio (max 600 characters)"
              name="bio"
              maxLength={600}
              placeholder="A sentence or two — your focus areas, training, and what you're working on."
            />

            <div className="grid gap-4 md:grid-cols-2">
              <Field
                label="Subspecialty"
                name="specialty"
                placeholder="e.g. Shoulder & elbow"
              />
              <Field
                label="Years qualified"
                name="yearsExperience"
                type="number"
                placeholder="0–80"
                error={state.fieldErrors?.yearsExperience}
              />
            </div>

            <Field
              label="ORCID URL"
              name="orcidUrl"
              placeholder="https://orcid.org/0000-0000-0000-0000"
              error={state.fieldErrors?.orcidUrl}
            />
            <Field
              label="LinkedIn URL"
              name="linkedinUrl"
              placeholder="https://linkedin.com/in/..."
              error={state.fieldErrors?.linkedinUrl}
            />
            <Field
              label="Website"
              name="websiteUrl"
              type="url"
              placeholder="https://yourclinic.example"
              error={state.fieldErrors?.websiteUrl}
            />
            <Field
              label="X / Twitter"
              name="twitterUrl"
              type="url"
              placeholder="https://x.com/handle"
              error={state.fieldErrors?.twitterUrl}
            />
          </div>
        )}
      </div>

      <Button type="submit" disabled={pending}>
        {pending ? "Submitting..." : "Submit application"}
      </Button>

      <p className="text-sm text-[var(--color-slate)]">
        Applications are usually reviewed within 3 days.
      </p>
    </form>
  );
}

function Field(props: {
  label: string;
  name: string;
  type?: string;
  required?: boolean;
  error?: string;
  placeholder?: string;
}) {
  return (
    <label className="block">
      <span className="mb-1 block text-sm font-semibold text-[var(--color-ink)]">
        {props.label}
      </span>
      <input
        name={props.name}
        type={props.type ?? "text"}
        required={props.required}
        placeholder={props.placeholder}
        className="w-full rounded-md border border-[var(--color-line)] px-3 py-2 text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none"
      />
      {props.error && <span className="mt-1 block text-xs text-red-600">{props.error}</span>}
    </label>
  );
}

function SelectField(props: {
  label: string;
  name: string;
  required?: boolean;
  error?: string;
  options: readonly string[];
}) {
  return (
    <label className="block">
      <span className="mb-1 block text-sm font-semibold text-[var(--color-ink)]">
        {props.label}
      </span>
      <select
        name={props.name}
        required={props.required}
        defaultValue=""
        className="w-full rounded-md border border-[var(--color-line)] px-3 py-2 text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none"
      >
        <option value="" disabled>
          Select…
        </option>
        {props.options.map((o) => (
          <option key={o} value={o}>
            {o}
          </option>
        ))}
      </select>
      {props.error && <span className="mt-1 block text-xs text-red-600">{props.error}</span>}
    </label>
  );
}

function TextAreaField(props: {
  label: string;
  name: string;
  required?: boolean;
  error?: string;
  maxLength?: number;
  placeholder?: string;
}) {
  return (
    <label className="block">
      <span className="mb-1 block text-sm font-semibold text-[var(--color-ink)]">
        {props.label}
      </span>
      <textarea
        name={props.name}
        required={props.required}
        maxLength={props.maxLength}
        placeholder={props.placeholder}
        rows={4}
        className="w-full rounded-md border border-[var(--color-line)] px-3 py-2 text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none"
      />
      {props.error && <span className="mt-1 block text-xs text-red-600">{props.error}</span>}
    </label>
  );
}
