"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";

import { Skeleton } from "@/components/ui";
import {
  fetchMyChatSettings,
  updateChatSettings,
} from "@/entities/chats/actions";
import type { IChatSettings } from "@/entities/chats/types";

import styles from "./AutoTopUpToggle.module.scss";

export default function AutoTopUpToggle() {
  const t = useTranslations("Profile");
  const [loading, setLoading] = useState(true);
  const [isUpdating, setIsUpdating] = useState(false);
  const [settings, setSettings] = useState<IChatSettings | null>(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const res = await fetchMyChatSettings();
        if (mounted && res.data) {
          setSettings(res.data.settings);
        }
      } catch (e) {
        // silent failure
        // eslint-disable-next-line no-console
        console.error("Failed to fetch chat settings", e);
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => {
      mounted = false;
    };
  }, []);

  const onToggle = async () => {
    if (!settings || isUpdating) return;
    const next = { ...settings, autoTopUp: !settings.autoTopUp };
    setSettings(next); // optimistic
    setIsUpdating(true);
    try {
      const res = await updateChatSettings(next);
      if (res.data) {
        setSettings(res.data.settings);
      }
    } catch (e) {
      // revert on error silently
      setSettings(settings);
      // eslint-disable-next-line no-console
      console.error("Failed to update chat settings", e);
    } finally {
      setIsUpdating(false);
    }
  };

  if (loading) {
    return <Skeleton style={{ height: 72 }} />;
  }

  return (
    <div className={styles.container}>
      <div className={styles.text}>
        <div className={styles.title}>{t("auto_top_up.title")}</div>
        <div className={styles.description}>{t("auto_top_up.description")}</div>
      </div>
      <button
        type="button"
        className={styles.switchButton}
        role="switch"
        aria-checked={settings?.autoTopUp ? "true" : "false"}
        onClick={onToggle}
        aria-label={t("auto_top_up.title")}
        disabled={isUpdating}
      >
        <span className={styles.thumb} />
      </button>
    </div>
  );
}
