import { useState, useRef, useEffect } from "preact/hooks";

const STATUS_OPTIONS = [
  { value: "replied", label: "Junwon to reply" },
  { value: "processing", label: "Ace is working" },
  { value: "skipped", label: "Waiting" },
  { value: "no_reply", label: "Chose no reply" },
  { value: "failed", label: "Failed" },
  { value: "archived", label: "Archived" },
];

function statusLabel(status: string): string {
  const opt = STATUS_OPTIONS.find((o) => o.value === status);
  if (opt) return opt.label;
  if (status === "processing") return "Ace is working";
  if (status === "queued") return "In queue";
  if (status === "stalled") return "Stalled";
  if (status === "skipped") return "Waiting";
  return status;
}

interface Props {
  status: string;
  onChangeStatus?: (newStatus: string) => void;
  onDelete?: () => void;
  hasLinear?: boolean;
}

export default function StatusBadge({ status, onChangeStatus, onDelete, hasLinear }: Props) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("click", handler, true);
    return () => document.removeEventListener("click", handler, true);
  }, [open]);

  return (
    <div class="status-badge-wrap" ref={ref}>
      <span
        class={`badge ${status} badge-clickable`}
        onClick={(e) => { e.stopPropagation(); if (onChangeStatus) setOpen(!open); }}
      >
        {statusLabel(status)}
      </span>
      {open && (
        <div class="status-dd">
          {STATUS_OPTIONS.map((opt) => (
            <div
              key={opt.value}
              class={`status-dd-opt${opt.value === status ? " active" : ""}`}
              onClick={(e) => {
                e.stopPropagation();
                if (opt.value !== status && onChangeStatus) onChangeStatus(opt.value);
                setOpen(false);
              }}
            >
              <span class={`badge ${opt.value}`} style="pointer-events:none">{opt.label}</span>
            </div>
          ))}
          {onDelete && (
            <>
              <div style="border-top: 1px solid var(--border); margin: 4px 0" />
              <div
                class="status-dd-opt"
                onClick={(e) => {
                  e.stopPropagation();
                  onDelete();
                  setOpen(false);
                }}
              >
                <span class="badge deleted" style="pointer-events:none">Delete</span>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
}
