"use client";

import React, { useEffect, useState } from "react";
import { OptionGroup } from "../ui/OptionGroup";
import { getUserSettings, saveUserSetting } from "@/app/lib/api/profile";

import { useSelector } from "react-redux";
import { User } from "@/constants/types";
interface AuthState {
  user: User; // adjust type as needed
  status: string;
}
type UserSettings = {
  brand: string;
  theme: string;
  effect: string;
  sound: string;
  speed: string;
  mode: string;
};
const DEFAULT_SETTINGS: UserSettings = {
  brand: "",
  speed: "",
  theme: "",
  effect: "",
  sound: "",
  mode: "",
};
const SettingsPanel = () => {
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMsg, setModalMsg] = useState("");
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [settings, setSettings] = useState<UserSettings>(DEFAULT_SETTINGS);
  const [settingsLoading, setSettingsLoading] = useState(true);

  const user = useSelector((state: { auth: AuthState }) => state.auth.user);
  type SaveUserSettingResponse = {
    resp: "success" | "error";
    msg: string;
    user?: {
      user: AppUser; // matches backend: { user: { userId, name, settings, ... } }
    };
  };

  type UserSettings = {
    brand: string;
    theme: string;
    effect: string;
    sound: string;
    speed: string;
    mode: string;
  };

  type UserLevel = {
    lavel: number;
    next: number;
    xp: number;
  };

  type AppUser = {
    userId: string;
    image: Record<string, unknown>;
    name: string;
    balance: number;
    level: UserLevel;
    settings: UserSettings;
  };

  useEffect(() => {
    if (!user?.userId || !user?.token) return;

    setSettingsLoading(true);

    (async () => {
      try {
        const fresh = await getUserSettings({
          user_id: user.userId,
          token: user.token,
        });

        setSettings({
          ...DEFAULT_SETTINGS,
          ...(fresh || {}),
          brand: fresh?.brand || DEFAULT_SETTINGS.brand,
          speed: fresh?.speed || DEFAULT_SETTINGS.speed,
          theme: fresh?.theme || DEFAULT_SETTINGS.theme,
          effect: fresh?.effect || DEFAULT_SETTINGS.effect,
          sound: fresh?.sound || DEFAULT_SETTINGS.sound,
          mode: fresh?.mode || DEFAULT_SETTINGS.mode,
        });
      } catch (e) {
        setSettings(DEFAULT_SETTINGS);
      } finally {
        setSettingsLoading(false); // ✅ loader stop
      }
    })();
  }, [user?.userId, user?.token]);

  const saveAndRefresh = async (key: keyof UserSettings, value: string) => {
    try {
      const res = await saveUserSetting({
        key,
        value: value.toLowerCase(),
        user_id: user.userId,
        token: user.token,
      });

      if (res.resp === "success") {
        const fresh = await getUserSettings({
          user_id: user.userId,
          token: user.token,
        });
        setSettings(fresh); // ✅ select updated
        setModalType("success");
        setModalMsg(res.msg || "Updated.");
      } else {
        setModalType("error");
        setModalMsg(res.msg || "Something happened.");
      }
    } catch (e) {
      setModalType("error");
      setModalMsg("Something went wrong while saving your settings.");
    } finally {
      setModalOpen(true);
      setTimeout(()=>{
setModalOpen(false)
      },2000)
    }
  };

  return (
    <>
      <div className="space-y-4">
        {/* SECTION 1 */}
        <h1 className="bg-[var(--color-gray)] font-onest font-bold text-sm md:text-xl 2xl:text-2xl p-4">
          Settings
        </h1>

        <div className="py-4 px-4 border border-[var(--color-gray)] space-y-6">
          {settingsLoading ? (
            <div className="flex w-full h-[160px] items-center justify-center">
              <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
            </div>
          ) : (
            <>
              <div>
                <h1 className="font-onest mb-2 font-medium text-sm md:text-base 2xl:text-lg">
                  Favorite Brand
                </h1>

                <OptionGroup
                  options={["POKEMON", "MAGIC", "LORCANA"]}
                  value={(settings?.brand ?? "POKEMON").toUpperCase()}
                  // onChange={handleBrandChange}
                  onChange={(v) => saveAndRefresh("brand", v)}
                />
                {/* )} */}
              </div>

              <div>
                <h1 className="font-onest mb-2 font-medium text-sm md:text-base 2xl:text-lg">
                  Opening Speed
                </h1>
                <OptionGroup
                  options={["MANUAL", "SLOW", "FAST", "TURBO"]}
                  value={(settings?.speed ?? "POKEMON").toUpperCase()}
                  // onChange={handleSpeedChange}
                  onChange={(v) => saveAndRefresh("speed", v)}
                />
              </div>
            </>
          )}
        </div>

        {/* SECTION 2 */}
        <h1 className="bg-[var(--color-gray)] font-onest font-bold text-sm md:text-xl 2xl:text-2xl p-4">
          Theme Settings
        </h1>

        <div className="py-4 px-4 border border-[var(--color-gray)] space-y-6">
          {settingsLoading ? (
            <div className="flex w-full h-[160px] items-center justify-center">
              <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
            </div>
          ) : (
            <>
              <div>
                <h1 className="font-onest mb-2 font-medium text-sm md:text-base 2xl:text-lg">
                  Theme Colors
                </h1>
                <OptionGroup
                  options={["OG", "CLEAN", "BLUE", "BASIC"]}
                  value={(settings?.theme ?? "BASIC").toUpperCase()}
                  // onChange={handleThemeChange}
                  onChange={(v) => saveAndRefresh("theme", v)}
                />
              </div>
              <div>
                <h1 className="font-onest mb-2 font-medium text-sm md:text-base 2xl:text-lg">
                  Visual Effects
                </h1>
                <OptionGroup
                  options={["DEFAULT", "LOW", "NONE"]}
                  value={(settings?.sound ?? "BASIC").toUpperCase()}
                  // onChange={handleEffectChange}
                  onChange={(v) => saveAndRefresh("sound", v)}
                />
              </div>
              <div>
                <h1 className="font-onest mb-2 font-medium text-sm md:text-base 2xl:text-lg">
                  Sound Effects
                </h1>
                <OptionGroup
                  value={(settings?.effect ?? "BASIC").toUpperCase()}
                  options={["ON", "OFF"]}
                  // onChange={handleSoundChange}
                  onChange={(v) => saveAndRefresh("effect", v)}
                />
              </div>
            </>
          )}
        </div>
      </div>

      {/* Simple modal */}
      {modalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-[black/40]">
          <div className="bg-[var(--color-naviBlue)]  p-6  min-w-[480px] space-y-4 shadow-xl">
            <h2
              className={`"text-sm md:text-xl text-center font-sofia font-extrabold mb-2 ${
                modalType === "success" ? "text-green-600" : "text-red-600"
              }`}
            >
              {modalType === "success" ? "Success" : "Error"}
            </h2>
            <p className="text-sm md:text-xl text-center mb-4">{modalMsg}</p>
            <div className="flex justify-end">
              <button
                onClick={() => setModalOpen(false)}
                className="w-full cursor-pointer py-2 text-sm md:text-base font-sofia font-extrabold bg-[var(--color-blue)]  hover:bg-[var(--color-hoverBlue)] duration-300"
            >
              OK
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default SettingsPanel;
