"use client";

import { useState } from "react";
import { toast } from "sonner";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";

export function SignupsToggle({ initialDisabled }: { initialDisabled: boolean }) {
  const [enabled, setEnabled] = useState(!initialDisabled);
  const [saving, setSaving] = useState(false);

  async function handleChange(checked: boolean) {
    setSaving(true);
    const previous = enabled;
    setEnabled(checked);
    try {
      const res = await fetch("/api/v1/admin/settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ SIGNUPS_DISABLED: checked ? null : "true" }),
      });
      if (!res.ok) throw new Error("Save failed");
      toast.success(checked ? "Signups enabled" : "Signups disabled");
    } catch {
      setEnabled(previous);
      toast.error("Failed to update");
    } finally {
      setSaving(false);
    }
  }

  return (
    <section className="rounded-xl border p-6 space-y-1">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="font-semibold text-lg">Signups</h2>
          <p className="text-sm text-muted-foreground mt-1">
            When off, only people with a valid invite link can create an account.
          </p>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <Label htmlFor="signups-enabled" className="text-sm">
            {enabled ? "Open" : "Disabled"}
          </Label>
          <Switch
            id="signups-enabled"
            checked={enabled}
            disabled={saving}
            onCheckedChange={(checked) => { void handleChange(checked); }}
          />
        </div>
      </div>
    </section>
  );
}
