"use client";

import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { Check, Send, X } from "lucide-react";
import type { Job } from "@/lib/types";

/**
 * Applying for a job.
 *
 * A window rather than a panel down the side of the advert. Filling this in
 * is a job of its own — name, contact, last role, whatever they asked, a CV
 * — and doing it in a 300px column beside the text you are still reading is
 * uncomfortable. It opens from the bottom of the advert, where someone is
 * once they have decided.
 */
export function ApplyJobModal({
  job,
  onClose,
  onSent,
}: {
  job: Job;
  onClose: () => void;
  onSent: () => void;
}) {
  const [form, setForm] = useState<Record<string, string>>({});
  const [answers, setAnswers] = useState<string[]>([]);
  const [workNow, setWorkNow] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sending, setSending] = useState(false);
  const [done, setDone] = useState(false);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const set = (k: string, v: string) => setForm((f) => ({ ...f, [k]: v }));
  const answer = (i: number, v: string) =>
    setAnswers((a) => {
      const next = [...a];
      next[i] = v;
      return next;
    });

  async function send() {
    setError(null);
    if (!form.name?.trim()) return setError("Give your name");
    if (!form.email?.trim() || !form.email.includes("@")) {
      return setError("Give an email they can reach you on");
    }

    setSending(true);
    const res = await fetch(`/api/jobs/${job.id}/apply`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...form, workNow, answers }),
    });
    setSending(false);

    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      return setError(body.error || "That didn't send");
    }
    setDone(true);
    onSent();
    // Left up for a moment so the confirmation is actually read.
    setTimeout(onClose, 1600);
  }

  return createPortal(
    <div className="nm-back" onClick={onClose}>
      <div className="jb-modal" onClick={(e) => e.stopPropagation()}>
        <header className="jb-mhead">
          <h2 className="jb-mtitle">Apply — {job.title}</h2>
          <button className="jb-mx" onClick={onClose} aria-label="Close">
            <X size={18} />
          </button>
        </header>

        {done ? (
          <div className="jb-mbody">
            <p className="jb-applied">
              <Check size={18} /> Sent. They can see your application now.
            </p>
          </div>
        ) : (
          <>
            <div className="jb-mbody">
              <section className="jb-sec">
                <label className="jb-label">
                  Your name <span className="jb-req">*</span>
                </label>
                <input className="jb-field" onChange={(e) => set("name", e.target.value)} />

                <div className="jb-row">
                  <div>
                    <label className="jb-label">
                      Email <span className="jb-req">*</span>
                    </label>
                    <input
                      className="jb-field"
                      type="email"
                      onChange={(e) => set("email", e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="jb-label">Phone</label>
                    <input className="jb-field" onChange={(e) => set("phone", e.target.value)} />
                  </div>
                </div>

                <label className="jb-label">Where you are</label>
                <input className="jb-field" onChange={(e) => set("location", e.target.value)} />
              </section>

              <section className="jb-sec">
                <label className="jb-label">
                  Most recent job <span className="jb-opt">optional</span>
                </label>
                <div className="jb-row">
                  <input
                    className="jb-field"
                    placeholder="Job title"
                    onChange={(e) => set("workPosition", e.target.value)}
                  />
                  <input
                    className="jb-field"
                    placeholder="Company"
                    onChange={(e) => set("workPlace", e.target.value)}
                  />
                </div>
                <div className="jb-row" style={{ marginTop: 10 }}>
                  <input
                    className="jb-field"
                    placeholder="From"
                    onChange={(e) => set("workFrom", e.target.value)}
                  />
                  <input
                    className="jb-field"
                    placeholder="To"
                    disabled={workNow}
                    onChange={(e) => set("workTo", e.target.value)}
                  />
                </div>
                <label className="jb-check" style={{ marginTop: 10 }}>
                  <input
                    type="checkbox"
                    checked={workNow}
                    onChange={(e) => setWorkNow(e.target.checked)}
                  />
                  I still work there
                </label>
              </section>

              {(job.questions ?? []).length > 0 && (
                <section className="jb-sec">
                  <label className="jb-label">Their questions</label>
                  {(job.questions ?? []).map((q, i) => (
                    <div key={i} style={{ marginBottom: 14 }}>
                      <label className="jb-label" style={{ fontWeight: 550 }}>
                        {q.title}
                      </label>
                      {q.type === "multiple_choice" ? (
                        <select className="jb-field" onChange={(e) => answer(i, e.target.value)}>
                          <option value="">Choose one</option>
                          {(q.choices ?? []).map((c) => (
                            <option key={c} value={c}>
                              {c}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <textarea
                          className="jb-field"
                          rows={3}
                          onChange={(e) => answer(i, e.target.value)}
                        />
                      )}
                    </div>
                  ))}
                </section>
              )}

              <section className="jb-sec">
                <label className="jb-label">
                  CV <span className="jb-opt">optional</span>
                </label>
                <input
                  type="file"
                  accept=".pdf,.doc,.docx,image/*"
                  className="jb-field"
                  onChange={(e) => {
                    const file = e.target.files?.[0];
                    if (!file) return;
                    const reader = new FileReader();
                    reader.onload = () => set("cvUrl", String(reader.result));
                    reader.readAsDataURL(file);
                  }}
                />
              </section>

              {error && <p className="jb-error">{error}</p>}
            </div>

            <footer className="jb-mfoot">
              <button className="jb-btn primary wide big" onClick={send} disabled={sending}>
                <Send size={16} /> {sending ? "Sending…" : "Send application"}
              </button>
            </footer>
          </>
        )}
      </div>
    </div>,
    document.body
  );
}
