"use client";
import { useEffect, useRef, useState } from "react";
import { formatDuration, parseDuration, maskDurationInput } from "@/lib/aula/duration";
import { Field } from "./EditorUI";

export default function DurationField({
  label,
  value,
  onChange,
  maxSeconds = 86400,
}: {
  label: string;
  value: number;
  onChange: (minutes: number) => void;
  maxSeconds?: number;
}) {
  const input = useRef<HTMLInputElement>(null);
  const [draft, setDraft] = useState<{ source: number; text: string } | null>(null);
  const text = draft?.source === value ? draft.text : formatDuration(Math.round(value * 60));
  useEffect(() => {
    const seconds = parseDuration(text);
    input.current?.setCustomValidity(
      seconds !== null && seconds > 0 && seconds <= maxSeconds
        ? ""
        : `Escribe una duración entre 00:00:01 y ${formatDuration(maxSeconds)}. Los minutos y segundos deben estar entre 00 y 59.`,
    );
  }, [text, maxSeconds]);
  return (
    <Field
      label={`${label} (hh:mm:ss)`}
      inputRef={input}
      type="text"
      required
      placeholder="00:00:00"
      inputMode="numeric"
      maxLength={8}
      pattern="[0-9]{2}:[0-5][0-9]:[0-5][0-9]"
      className="font-mono tabular-nums"
      value={text}
      onFocus={(event) => event.currentTarget.select()}
      onKeyDown={(event) => {
        const el = event.currentTarget;
        const cursor = el.selectionStart ?? 0;
        if (el.selectionEnd !== cursor) return;
        if (event.key === "Backspace" && el.value[cursor - 1] === ":")
          el.setSelectionRange(cursor - 1, cursor - 1);
        if (event.key === "Delete" && el.value[cursor] === ":")
          el.setSelectionRange(cursor + 1, cursor + 1);
      }}
      onChange={(event) => {
        const raw = event.target.value;
        const digitCount = raw
          .slice(0, event.target.selectionStart ?? raw.length)
          .replace(/\D/g, "").length;
        const next = maskDurationInput(raw);
        const seconds = parseDuration(next);
        const valid = seconds !== null && seconds > 0 && seconds <= maxSeconds;
        const minutes = valid ? seconds / 60 : value;
        setDraft({ source: minutes, text: next });
        if (valid) onChange(minutes);
        let cursor = 0;
        let seen = 0;
        while (cursor < next.length && seen < digitCount) {
          if (next[cursor] !== ":") seen++;
          cursor++;
        }
        requestAnimationFrame(() => input.current?.setSelectionRange(cursor, cursor));
      }}
    />
  );
}
