// Reviewed integration example. Native interaction has not been executed.
// AppButton and AppText represent existing project components; adapt their props.
import { useRef, useState } from 'react';
import { AppButton, AppText } from './project-components';
import { createSaveGate } from './save-gate';

type Props = {
  onSave: () => Promise<void>;
  labels: { save: string; saving: string; failed: string };
};

export function SaveAction({ onSave, labels }: Props) {
  const runSave = useRef(createSaveGate()).current;
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSave() {
    // The task callback runs only when this instance admits a new save.
    try {
      await runSave(async () => {
        setBusy(true);
        setError(null);
        try {
          await onSave();
        } finally {
          setBusy(false);
        }
      });
    } catch {
      setError(labels.failed);
    }
  }

  return (
    <>
      <AppButton
        title={busy ? labels.saving : labels.save}
        onPress={handleSave}
        disabled={busy}
        loading={busy}
        accessibilityState={{ disabled: busy, busy }}
      />
      {error ? <AppText accessibilityRole="alert">{error}</AppText> : null}
    </>
  );
}
