"use client";

import { useState } from "react";
import { changeEmail, updatePreferences, type MeResponse } from "@/lib/api";

export function useProfileSettings(
  user: MeResponse | null,
  refresh: () => Promise<void> | void
) {
  // ── Email state ───────────────────────────────────────────────────────
  const [email, setEmail] = useState("");
  const [emailInitialized, setEmailInitialized] = useState(false);
  const [emailError, setEmailError] = useState("");
  const [emailSuccess, setEmailSuccess] = useState("");
  const [emailLoading, setEmailLoading] = useState(false);

  // ── Listenanzahl (Eintraege pro Seite) ────────────────────────────────
  const [listPageSize, setListPageSize] = useState("25");
  const [listPageSizeInitialized, setListPageSizeInitialized] = useState(false);
  const [listPageSizeError, setListPageSizeError] = useState("");
  const [listPageSizeSuccess, setListPageSizeSuccess] = useState("");
  const [listPageSizeLoading, setListPageSizeLoading] = useState(false);

  // Initialize email from user data once available
  if (user && !emailInitialized) {
    setEmail(user.email || "");
    setEmailInitialized(true);
  }

  // Initialize list page size from user data once available
  if (user && !listPageSizeInitialized) {
    setListPageSize(String(user.list_page_size || 25));
    setListPageSizeInitialized(true);
  }

  async function handleChangeEmail(e: React.FormEvent) {
    e.preventDefault();
    setEmailError("");
    setEmailSuccess("");

    if (!email || !email.includes("@")) {
      setEmailError("Bitte eine gueltige E-Mail-Adresse eingeben.");
      return;
    }

    setEmailLoading(true);
    try {
      const result = await changeEmail(email);
      setEmail(result.email);
      setEmailSuccess("E-Mail-Adresse wurde erfolgreich geaendert.");
    } catch (err) {
      setEmailError(err instanceof Error ? err.message : "Fehler beim Aendern der E-Mail");
    } finally {
      setEmailLoading(false);
    }
  }

  async function handleChangeListPageSize(value: string) {
    setListPageSizeError("");
    setListPageSizeSuccess("");
    const parsed = Number(value);

    setListPageSizeLoading(true);
    try {
      const result = await updatePreferences(parsed);
      setListPageSize(String(result.list_page_size));
      setListPageSizeSuccess("Eintraege pro Seite wurden gespeichert.");
      await refresh();
    } catch (err) {
      setListPageSizeError(err instanceof Error ? err.message : "Fehler beim Speichern");
    } finally {
      setListPageSizeLoading(false);
    }
  }

  return {
    email,
    setEmail,
    emailError,
    emailSuccess,
    emailLoading,
    handleChangeEmail,
    listPageSize,
    listPageSizeError,
    listPageSizeSuccess,
    listPageSizeLoading,
    handleChangeListPageSize,
  };
}
