"use client";

import { useCallback, useRef, useState } from "react";
import { useTranslation } from "@enode/core/translations/hooks";
import { toast } from "../feedback/toast-store";

/** How long the "Saved" toast stays visible, in milliseconds. */
export const SAVED_TOAST_DURATION_MS = 1800;

/** Return value of {@link useSaveFeedback}. */
export interface SaveFeedback {
  /** Shows the short "Saved" toast (replacing a still-visible one) and clears `id`'s error if given. */
  saved(id?: string): void;
  /** Marks the control `id` as failed to save. */
  failed(id: string): void;
  /** Removes the failed mark of control `id`. */
  clear(id: string): void;
  /** Whether control `id` is currently marked as failed. */
  errorFor(id: string): boolean;
}

/**
 * State and toast helpers for "saves instantly" settings. Success uses the
 * global success toast (check-circle pill); rapid repeated saves replace the
 * previous "Saved" toast instead of stacking. Failures are tracked per control
 * id so a row can render {@link SaveErrorLine}.
 */
export function useSaveFeedback(): SaveFeedback {
  const { t } = useTranslation();
  const [failedIds, setFailedIds] = useState<ReadonlySet<string>>(new Set());
  const lastToastId = useRef<number | null>(null);

  const clear = useCallback((id: string) => {
    setFailedIds((prev) => {
      if (!prev.has(id)) return prev;
      const next = new Set(prev);
      next.delete(id);
      return next;
    });
  }, []);

  const failed = useCallback((id: string) => {
    setFailedIds((prev) => (prev.has(id) ? prev : new Set(prev).add(id)));
  }, []);

  const saved = useCallback(
    (id?: string) => {
      if (id !== undefined) clear(id);
      if (lastToastId.current !== null) toast.dismiss(lastToastId.current);
      lastToastId.current = toast.success(t("Saved"), {
        durationMs: SAVED_TOAST_DURATION_MS,
      });
    },
    [clear, t],
  );

  const errorFor = useCallback((id: string) => failedIds.has(id), [failedIds]);

  return { saved, failed, clear, errorFor };
}

/** Props of {@link SaveErrorLine}. */
export interface SaveErrorLineProps {
  /** When given, a "Try again." button is shown that calls it. */
  onRetry?: () => void;
  className?: string;
}

/**
 * Inline red error line shown under a settings row whose instant save failed.
 * Announced politely to screen readers.
 */
export function SaveErrorLine({ onRetry, className = "" }: SaveErrorLineProps) {
  const { t } = useTranslation();
  return (
    <p
      role="alert"
      className={`text-[13px] leading-[1.3] text-feedback-error ${className}`.trim()}
    >
      {onRetry ? (
        <>
          {t("Couldn't save.")}{" "}
          <button type="button" onClick={onRetry} className="relative underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground-red-orange after:absolute after:-inset-x-2 after:-inset-y-3 after:content-['']">
            {t("Try again.")}
          </button>
        </>
      ) : (
        t("Couldn't save. Try again.")
      )}
    </p>
  );
}
