"use client";

import { useActionState, useState } from "react";
import { flagLabel } from "@/lib/actions/flags";
import { FLAG_REASONS, FLAG_REASON_LABELS } from "@/lib/flag-reasons";

function FlagModalBody({
  labelId,
  onClose,
}: {
  labelId: string;
  onClose: () => void;
}) {
  const [state, formAction, isPending] = useActionState(flagLabel, undefined);

  if (state?.success) {
    return (
      <>
        <h2 className="font-heading text-xl font-semibold text-charcoal">
          Thanks for the report
        </h2>
        <p className="mt-2 text-sm text-charcoal/60">
          A moderator will take a look.
        </p>
        <button
          type="button"
          onClick={onClose}
          className="mt-6 rounded-full border border-charcoal/20 px-5 py-2 text-sm font-medium text-charcoal hover:bg-charcoal/5"
        >
          Close
        </button>
      </>
    );
  }

  return (
    <form action={formAction} className="flex flex-col gap-4">
      <h2 className="font-heading text-xl font-semibold text-charcoal">
        Report this label
      </h2>
      <input type="hidden" name="labelId" value={labelId} />
      <label className="flex flex-col gap-1 text-sm">
        <span className="text-charcoal/70">Reason</span>
        <select
          name="reason"
          required
          className="rounded border border-charcoal/20 bg-cream px-3 py-1.5 text-charcoal"
        >
          {FLAG_REASONS.map((reason) => (
            <option key={reason} value={reason}>
              {FLAG_REASON_LABELS[reason]}
            </option>
          ))}
        </select>
      </label>
      <label className="flex flex-col gap-1 text-sm">
        <span className="text-charcoal/70">Details (optional)</span>
        <textarea
          name="note"
          rows={3}
          className="rounded border border-charcoal/20 bg-cream px-3 py-1.5 text-charcoal"
        />
      </label>
      {state?.error && <p className="text-sm text-terracotta">{state.error}</p>}
      <div className="flex justify-end gap-3">
        <button
          type="button"
          onClick={onClose}
          className="rounded-full border border-charcoal/20 px-5 py-2 text-sm font-medium text-charcoal hover:bg-charcoal/5"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={isPending}
          className="rounded-full bg-terracotta px-5 py-2 text-sm font-medium text-white hover:bg-terracotta/90 disabled:opacity-60"
        >
          {isPending ? "Sending..." : "Submit report"}
        </button>
      </div>
    </form>
  );
}

export function FlagButton({
  labelId,
  isLoggedIn,
}: {
  labelId: string;
  isLoggedIn: boolean;
}) {
  const [open, setOpen] = useState(false);
  // Incremented on every open so FlagModalBody remounts with a fresh
  // useActionState -- otherwise reopening after a successful report shows
  // the stale "Thanks for the report" screen instead of a new form.
  const [openKey, setOpenKey] = useState(0);

  if (!isLoggedIn) return null;

  return (
    <>
      <button
        type="button"
        onClick={() => {
          setOpenKey((k) => k + 1);
          setOpen(true);
        }}
        className="text-sm text-charcoal/60 hover:text-terracotta hover:underline"
      >
        Report this label
      </button>

      {open && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 px-6"
          onClick={() => setOpen(false)}
        >
          <div
            className="w-full max-w-sm rounded-lg bg-warm-white p-6 shadow-xl"
            onClick={(e) => e.stopPropagation()}
          >
            <FlagModalBody
              key={openKey}
              labelId={labelId}
              onClose={() => setOpen(false)}
            />
          </div>
        </div>
      )}
    </>
  );
}
