"use client";

import { useState, useTransition } from "react";
import { ReminderPicker } from "@/components/reminder-picker";
import { Button } from "@/components/ui/button";
import { setDefaultEventReminderOffsets } from "@/app/settings/reminder-actions";

export function DefaultEventRemindersSetting({ initialOffsets }: { initialOffsets: number[] }) {
  const [saved, setSaved] = useState(initialOffsets);
  const [offsets, setOffsets] = useState(initialOffsets);
  const [isPending, startTransition] = useTransition();

  const dirty =
    offsets.length !== saved.length || offsets.some((value, index) => value !== saved[index]);

  function handleSave() {
    startTransition(async () => {
      await setDefaultEventReminderOffsets(offsets);
      setSaved(offsets);
    });
  }

  return (
    <div className="space-y-3">
      <p className="muted text-[13px]">
        Applied when you create a new calendar event. You can still customize reminders per event.
      </p>
      <ReminderPicker offsets={offsets} onChange={setOffsets} disabled={isPending} />
      <Button type="button" size="sm" disabled={!dirty || isPending} onClick={handleSave}>
        {isPending ? "Saving…" : "Save defaults"}
      </Button>
    </div>
  );
}
