"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { fromEatInputValue, toEatInputValue } from "@/lib/format";

const whenFmt = new Intl.DateTimeFormat("en-GB", {
  timeZone: "Africa/Nairobi",
  weekday: "short",
  day: "numeric",
  month: "short",
  hour: "numeric",
  minute: "2-digit",
  hour12: true,
});

// Per-ticket-type sales controls on the organizer's event page: shows whether
// the tier is on sale, closes/reopens it on the spot, and edits how many are
// available plus an optional automatic stop-selling time (Kenya time).
export default function TicketTypeControls({
  id,
  quantityTotal,
  quantitySold,
  salesClosed,
  salesEndAt,
  nowMs,
}: {
  id: string;
  quantityTotal: number;
  quantitySold: number;
  salesClosed: boolean;
  salesEndAt: string | null;
  nowMs: number;
}) {
  const router = useRouter();
  const [editing, setEditing] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(String(quantityTotal));
  const [endAt, setEndAt] = useState(toEatInputValue(salesEndAt));

  const ended = salesEndAt !== null && new Date(salesEndAt).getTime() <= nowMs;
  const soldOut = quantitySold >= quantityTotal;
  const status = salesClosed
    ? { text: "Closed", tone: "text-red-500" }
    : ended
      ? { text: `Closed ${whenFmt.format(new Date(salesEndAt!))}`, tone: "text-red-500" }
      : soldOut
        ? { text: "Sold out", tone: "text-be-muted" }
        : salesEndAt
          ? { text: `On sale · closes ${whenFmt.format(new Date(salesEndAt))}`, tone: "text-emerald-500" }
          : { text: "On sale", tone: "text-emerald-500" };
  const open = !salesClosed && !ended;

  async function patch(body: Record<string, unknown>, confirmMsg?: string) {
    if (confirmMsg && !confirm(confirmMsg)) return false;
    setBusy(true);
    setError(null);
    const res = await fetch(`/api/dashboard/ticket-types/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    }).catch(() => null);
    const data = res ? await res.json().catch(() => ({})) : {};
    setBusy(false);
    if (!res || !res.ok) {
      setError(data.error ?? "Could not save");
      return false;
    }
    router.refresh();
    return true;
  }

  async function saveEdit(e: React.FormEvent) {
    e.preventDefault();
    const n = Number(total);
    if (!Number.isInteger(n) || n < 0) return setError("Enter a whole number.");
    if (n < quantitySold) return setError(`${quantitySold} are already sold, so the total can't be lower.`);
    const iso = endAt ? fromEatInputValue(endAt) : null;
    if (endAt && !iso) return setError("That stop-selling time isn't valid.");
    // Moving the stop time into the future reopens a tier that closed on its own.
    if (await patch({ quantityTotal: n, salesEndAt: iso })) setEditing(false);
  }

  return (
    <div className="flex flex-col items-end gap-1.5 text-right">
      <span className={`text-xs font-medium ${status.tone}`}>{status.text}</span>
      <div className="flex flex-wrap justify-end gap-2">
        {open ? (
          <button
            type="button"
            disabled={busy}
            onClick={() => patch({ salesClosed: true }, "Stop selling this ticket type now? Buyers will see “Sales closed”.")}
            className="rounded-md border border-be-border px-2.5 py-1 text-xs font-medium hover:bg-be-surface-2 disabled:opacity-50"
          >
            Close sales now
          </button>
        ) : (
          <button
            type="button"
            disabled={busy}
            onClick={() =>
              patch(
                { salesClosed: false, ...(ended ? { salesEndAt: null } : {}) },
                ended ? "Reopen sales? This also removes the stop-selling time." : undefined
              )
            }
            className="rounded-md border border-be-border px-2.5 py-1 text-xs font-medium hover:bg-be-surface-2 disabled:opacity-50"
          >
            Reopen sales
          </button>
        )}
        <button
          type="button"
          onClick={() => {
            setEditing((v) => !v);
            setError(null);
          }}
          className="rounded-md border border-be-border px-2.5 py-1 text-xs font-medium hover:bg-be-surface-2"
        >
          {editing ? "Cancel" : "Edit"}
        </button>
      </div>

      {editing && (
        <form onSubmit={saveEdit} className="mt-1 w-72 space-y-2 rounded-md border border-be-border bg-be-surface-2 p-3 text-left">
          <label className="block">
            <span className="mb-1 block text-xs text-be-muted">Total available ({quantitySold} sold so far)</span>
            <input
              type="number"
              min={quantitySold}
              step={1}
              value={total}
              onChange={(e) => setTotal(e.target.value)}
              className="input w-full"
            />
          </label>
          <label className="block">
            <span className="mb-1 block text-xs text-be-muted">Stop selling at (Kenya time) · optional</span>
            <input type="datetime-local" value={endAt} onChange={(e) => setEndAt(e.target.value)} className="input w-full" />
          </label>
          {endAt && (
            <button type="button" onClick={() => setEndAt("")} className="text-xs text-be-muted hover:underline">
              Remove stop-selling time
            </button>
          )}
          <button
            type="submit"
            disabled={busy}
            className="block w-full rounded-md bg-brand-green px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-green-deep disabled:opacity-50"
          >
            {busy ? "Saving…" : "Save"}
          </button>
        </form>
      )}
      {error && <p className="max-w-72 text-xs text-red-500">{error}</p>}
    </div>
  );
}
