"use client";

import { Check, Lightbulb, LoaderCircle, X } from "lucide-react";
import { FormEvent, useEffect, useState } from "react";

type AccessState =
  | { status: "checking" }
  | { status: "allowed" }
  | { status: "unauthenticated" }
  | { status: "profile_missing" }
  | { status: "error"; message: string };

export default function SuggestWidget() {
  const [open, setOpen] = useState(false);
  const [access, setAccess] = useState<AccessState>({ status: "checking" });
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!open) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape" && !submitting) setOpen(false);
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [open, submitting]);

  async function showForm() {
    setOpen(true);
    setSubmitted(false);
    setError("");
    setAccess({ status: "checking" });
    try {
      const response = await fetch("/api/sys/suggest", { cache: "no-store" });
      const result = await response.json();
      if (response.ok) setAccess({ status: "allowed" });
      else if (result.code === "profile_missing") setAccess({ status: "profile_missing" });
      else if (response.status === 401) setAccess({ status: "unauthenticated" });
      else setAccess({ status: "error", message: result.error || "Could not verify your account." });
    } catch {
      setAccess({ status: "error", message: "Could not verify your account. Please try again." });
    }
  }

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError("");
    const form = new FormData(event.currentTarget);
    try {
      const response = await fetch("/api/sys/suggest", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ suggestion: form.get("suggestion"), context: form.get("context") }),
      });
      const result = await response.json();
      if (!response.ok) {
        if (response.status === 401) setAccess({ status: "unauthenticated" });
        else if (result.code === "profile_missing") setAccess({ status: "profile_missing" });
        else setError(result.error || "Could not submit your suggestion. Please try again.");
        return;
      }
      setSubmitted(true);
    } catch {
      setError("Could not submit your suggestion. Please check your connection and try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <>
      <button type="button" className="bugReportTrigger suggestTrigger" onClick={() => void showForm()} aria-label="Share a suggestion" title="Share a suggestion">
        <Lightbulb size={20} aria-hidden="true" />
      </button>

      {open && (
        <div className="bugReportBackdrop" onMouseDown={(event) => {
          if (event.target === event.currentTarget && !submitting) setOpen(false);
        }}>
          <section className="bugReportDialog" role="dialog" aria-modal="true" aria-labelledby="suggestTitle">
            <header className="bugReportHeader">
              <div>
                <span className="bugReportEyebrow">Help us improve</span>
                <h2 id="suggestTitle">Suggest a feature</h2>
              </div>
              <button type="button" className="bugReportClose" onClick={() => setOpen(false)} disabled={submitting} aria-label="Close suggestions">
                <X size={19} />
              </button>
            </header>

            {access.status === "checking" ? (
              <div className="bugReportNotice"><LoaderCircle className="bugReportSpinner" size={20} /> Checking your account…</div>
            ) : access.status === "unauthenticated" ? (
              <div className="bugReportNotice">
                <p>Log in before submitting a suggestion.</p>
                <a className="bugReportSubmit" href="/login">Log in</a>
              </div>
            ) : access.status === "profile_missing" ? (
              <div className="bugReportNotice">
                <p>Claim your profile before submitting a suggestion.</p>
                <a className="bugReportSubmit" href="/claim">Claim your profile</a>
              </div>
            ) : access.status === "error" ? (
              <div className="bugReportNotice">
                <p>{access.message}</p>
                <button type="button" className="bugReportSubmit" onClick={() => void showForm()}>Try again</button>
              </div>
            ) : submitted ? (
              <div className="bugReportSuccess">
                <span><Check size={20} /></span>
                <strong>Suggestion sent</strong>
                <p>Thanks for helping us make the site better.</p>
                <button type="button" className="bugReportSubmit" onClick={() => setOpen(false)}>Done</button>
              </div>
            ) : (
              <form className="bugReportForm" onSubmit={submit}>
                <label>
                  Your suggestion
                  <textarea name="suggestion" maxLength={1500} required rows={5} placeholder="What should we add or improve?" />
                </label>
                <label>
                  Context (optional)
                  <textarea name="context" maxLength={800} rows={2} placeholder="Where would this help, and why?" />
                </label>
                {error && <p className="bugReportError" role="alert">{error}</p>}
                <button className="bugReportSubmit" type="submit" disabled={submitting}>
                  {submitting ? <><LoaderCircle className="bugReportSpinner" size={17} /> Sending…</> : "Submit suggestion"}
                </button>
              </form>
            )}
          </section>
        </div>
      )}
    </>
  );
}
