"use client";
// components/admin/CutoffEditor.tsx
// Admin editor for the raffle cutoff dates (cierre de inscripciones + fecha del
// sorteo). Calls setCutoffAction, which enforces the fairness lock server-side.
// Datetime inputs are in Peru time (the action reads them as UTC-5). When the
// cutoff is locked (raffle closed/drawn or draw committed) it renders read-only.

import * as React from "react";
import { setCutoffAction } from "@/app/admin/_lib/actions";
import type { ActionResult } from "@/app/admin/_lib/actions";

export function CutoffEditor({
  raffleId,
  closesAtLocal,
  drawAtLocal,
  closesAtLabel,
  drawAtLabel,
  locked,
  lockedReason,
}: {
  raffleId: string;
  closesAtLocal: string; // "YYYY-MM-DDTHH:mm" in Peru time (for the input)
  drawAtLocal: string;
  closesAtLabel: string; // human-readable current value (for the locked view)
  drawAtLabel: string;
  locked: boolean;
  lockedReason: string;
}) {
  const [closesAt, setClosesAt] = React.useState(closesAtLocal);
  const [drawAt, setDrawAt] = React.useState(drawAtLocal);
  const [pending, setPending] = React.useState(false);
  const [result, setResult] = React.useState<ActionResult | null>(null);

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setPending(true);
    setResult(null);
    setResult(await setCutoffAction(raffleId, { closesAt, drawAt }));
    setPending(false);
  }

  return (
    <div className="rounded-lg border border-hairline bg-canvas p-lg">
      <h2 className="font-display text-heading-md font-bold text-ink-strong">
        Fechas del sorteo
      </h2>
      <p className="mt-1 font-body text-body-sm text-muted">
        El cierre congela el pool de boletos; la fecha del sorteo define la ronda
        drand. Horas en zona horaria de Perú.
      </p>

      {locked ? (
        <div className="mt-4">
          <p className="rounded-md border border-hairline px-4 py-3 font-body text-body-sm text-muted">
            Las fechas están bloqueadas: {lockedReason}
          </p>
          <dl className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
            <div>
              <dt className="font-body text-caption text-muted-label">Cierre</dt>
              <dd className="font-body text-body-md text-ink-strong">{closesAtLabel}</dd>
            </div>
            <div>
              <dt className="font-body text-caption text-muted-label">Sorteo</dt>
              <dd className="font-body text-body-md text-ink-strong">{drawAtLabel}</dd>
            </div>
          </dl>
        </div>
      ) : (
        <form onSubmit={save} className="mt-4 flex flex-col gap-4">
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <label className="flex flex-col gap-1.5">
              <span className="font-body text-body-md font-medium text-ink-strong">
                Cierre de inscripciones
              </span>
              <input
                type="datetime-local"
                value={closesAt}
                onChange={(e) => setClosesAt(e.target.value)}
                required
                className="min-h-11 rounded-md border border-track bg-canvas px-3 font-body text-body-md text-ink-strong focus-visible:outline focus-visible:outline-[3px] focus-visible:outline-offset-1 focus-visible:outline-steelblue"
              />
            </label>
            <label className="flex flex-col gap-1.5">
              <span className="font-body text-body-md font-medium text-ink-strong">
                Fecha del sorteo
              </span>
              <input
                type="datetime-local"
                value={drawAt}
                onChange={(e) => setDrawAt(e.target.value)}
                required
                className="min-h-11 rounded-md border border-track bg-canvas px-3 font-body text-body-md text-ink-strong focus-visible:outline focus-visible:outline-[3px] focus-visible:outline-offset-1 focus-visible:outline-steelblue"
              />
            </label>
          </div>
          <div className="flex flex-wrap items-center gap-3">
            <button
              type="submit"
              disabled={pending}
              className="min-h-11 rounded-md border border-primary px-5 font-body text-body-md font-bold text-primary hover:bg-primary hover:text-on-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-50"
            >
              {pending ? "Guardando..." : "Guardar fechas"}
            </button>
            {result ? (
              <span
                className={`font-body text-body-sm ${result.ok ? "text-ink-strong" : "text-primary"}`}
                role="status"
              >
                {result.ok ? result.message : result.error}
              </span>
            ) : null}
          </div>
        </form>
      )}
    </div>
  );
}
