"use client";

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

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

const initialAccess: AccessState = { status: "checking" };

export default function BugReportWidget() {
  const [open, setOpen] = useState(false);
  const [access, setAccess] = useState<AccessState>(initialAccess);
  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/bug", { cache: "no-store" });
      const result = await response.json();
      if (response.ok) {
        setAccess({ status: "allowed" });
      } else if (result.code === "profile_missing" || result.code === "discord_unlinked") {
        setAccess({ status: result.code });
      } 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 submitReport(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError("");
    const form = new FormData(event.currentTarget);
    const payload = {
      title: form.get("title"),
      description: form.get("description"),
      steps: form.get("steps"),
      expected: form.get("expected"),
      actual: form.get("actual"),
      browser: navigator.userAgent,
      device: navigator.platform,
    };

    try {
      const response = await fetch("/api/sys/bug", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const result = await response.json();
      if (!response.ok) {
        if (response.status === 401) setAccess({ status: "unauthenticated" });
        else if (result.code === "profile_missing" || result.code === "discord_unlinked") {
          setAccess({ status: result.code });
        } else setError(result.error || "Could not submit your report. Please try again.");
        return;
      }
      setSubmitted(true);
    } catch {
      setError("Could not submit your report. Please check your connection and try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <>
      <button
        type="button"
        className="bugReportTrigger"
        onClick={() => void showForm()}
        aria-label="Report a bug"
        title="Report a bug"
      >
        <Bug 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="bugReportTitle"
          >
            <header className="bugReportHeader">
              <div>
                <span className="bugReportEyebrow">Help us improve</span>
                <h2 id="bugReportTitle">Report a bug</h2>
              </div>
              <button
                type="button"
                className="bugReportClose"
                onClick={() => setOpen(false)}
                disabled={submitting}
                aria-label="Close bug report"
              >
                <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 and link your Discord account before submitting a bug report.</p>
                <a className="bugReportSubmit" href="/login">Log in</a>
              </div>
            ) : access.status === "profile_missing" ? (
              <div className="bugReportNotice">
                <p>Claim your profile before submitting a bug report.</p>
                <a className="bugReportSubmit" href="/claim">Claim your profile</a>
              </div>
            ) : access.status === "discord_unlinked" ? (
              <div className="bugReportNotice">
                <p>Your Discord account must be linked to submit a bug report.</p>
                <a className="bugReportSubmit" href="/dashboard/discord-presence">Link Discord</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>Report submitted</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={submitReport}>
                <p className="bugReportIntro">Your linked Discord account will be included with this report.</p>
                <label>
                  Bug title
                  <input name="title" maxLength={120} required placeholder="A short summary of the issue" />
                </label>
                <label>
                  What happened?
                  <textarea name="description" maxLength={1500} required rows={3} placeholder="Describe the bug and what you were doing." />
                </label>
                <label>
                  Steps to reproduce
                  <textarea name="steps" maxLength={1024} required rows={3} placeholder={"1. Go to…\n2. Click…\n3. See the issue"} />
                </label>
                <div className="bugReportSplit">
                  <label>
                    What did you expect?
                    <textarea name="expected" maxLength={800} required rows={2} />
                  </label>
                  <label>
                    What happened instead?
                    <textarea name="actual" maxLength={800} required rows={2} />
                  </label>
                </div>
                <p className="bugReportContext">Your browser and device details are included automatically.</p>
                {error && <p className="bugReportError" role="alert">{error}</p>}
                <button className="bugReportSubmit" type="submit" disabled={submitting}>
                  {submitting ? <><LoaderCircle className="bugReportSpinner" size={17} /> Sending…</> : "Submit bug report"}
                </button>
              </form>
            )}
          </section>
        </div>
      )}
    </>
  );
}
