"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Select } from "@/components/ui/input";
import { useConfirmDialog } from "@/components/ui/confirm-dialog";
import { useToast } from "@/components/ui/toast";
import { clientFetch } from "@/lib/api/client";

const OPTIONS = [
  { value: "published", label: "Coming Soon" },
  { value: "ongoing", label: "Ongoing" },
  { value: "finished", label: "Finished" },
] as const;

/**
 * Manual Coming Soon/Ongoing/Finished override for an already-published
 * event — only shown when status is one of those three (see
 * EventLifecycleService::overrideStatus() on the backend for the guard and
 * why this locks the event out of the date-driven cron).
 */
export function EventStatusSelect({ eventId, status }: { eventId: number; status: string }) {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { confirm, dialog } = useConfirmDialog();
  const { toast } = useToast();

  async function handleChange(event: React.ChangeEvent<HTMLSelectElement>) {
    const next = event.target.value;
    if (next === status) return;

    const label = OPTIONS.find((o) => o.value === next)?.label ?? next;
    if (
      !(await confirm(
        `Change status to "${label}"? This locks the event out of automatic status updates going forward.`,
        "Change Status",
        "primary",
      ))
    ) {
      return;
    }

    setError(null);
    setIsSubmitting(true);
    const res = await clientFetch(`/api/admin/events/${eventId}/status`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: next }),
    });
    setIsSubmitting(false);

    const body = await res.json().catch(() => null);
    if (!res.ok) {
      const message = body?.message ?? "Failed to update status.";
      setError(message);
      toast(message, "error");
      return;
    }
    toast("Status updated successfully.", "success");
    router.refresh();
  }

  return (
    <div className="flex flex-col items-start gap-1">
      {dialog}
      <Select size="sm" value={status} onChange={handleChange} disabled={isSubmitting} aria-label="Event status">
        {OPTIONS.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </Select>
      {error && <p className="text-xs text-red-600">{error}</p>}
    </div>
  );
}
