"use client";

import { useEffect, useState } from "react";
import useUserSettings from "@/hooks/use-user-settings";
import { useNotificationsContext } from "@/hooks/notifications-context";

export default function SettingsContent() {
    const { settings, loading, error, updateSettings } = useUserSettings();
    const { notify } = useNotificationsContext();
    const [entryPanelPageSize, setEntryPanelPageSize] = useState("10");

    useEffect(() => {
        setEntryPanelPageSize(String(settings.entryPanelPageSize || 10));
    }, [settings.entryPanelPageSize]);

    async function handleSave(e: React.FormEvent<HTMLFormElement>) {
        e.preventDefault();
        const nextSize = Number(entryPanelPageSize);
        if (!Number.isFinite(nextSize) || nextSize <= 0) return;
        const ok = await updateSettings({ entryPanelPageSize: nextSize });
        if (!ok) return;
        notify({ title: "Settings saved", message: `Entry panel page size: ${nextSize}`, tone: "success" });
    }

    if (loading) {
        return (
            <div className="panel panel-accent p-4">
                <div className="text-sm text-muted">Loading settings...</div>
            </div>
        );
    }

    return (
        <div className="space-y-4">
            <div className="panel panel-accent p-4">
                <h1 className="text-xl font-semibold">User settings</h1>
                <p className="mt-1 text-sm text-muted">These settings apply to your account across groups.</p>
                <form className="mt-4 space-y-3" onSubmit={handleSave}>
                    <label className="block text-sm text-muted">
                        Entry/Schedule cards per page
                        <input
                            type="number"
                            min={1}
                            max={100}
                            value={entryPanelPageSize}
                            onChange={event => setEntryPanelPageSize(event.target.value)}
                            className="mt-1 w-40 input-base px-3 py-2 text-sm"
                        />
                    </label>
                    <button type="submit" className="rounded-lg btn-accent px-4 py-2 text-sm font-semibold">
                        Save
                    </button>
                    {error ? <div className="text-sm text-red-400">{error}</div> : null}
                </form>
            </div>
        </div>
    );
}
