"use client";

import React, { createContext, useCallback, useContext, useEffect, useState, ReactNode } from "react";
import { favoritesAPI } from "@/lib/api/favorites";
import { useAuth } from "@/hooks/useAuth";

interface FavoritesContextType {
  /** 즐겨찾기 메뉴 행 (MENU_INFO JOIN 결과) */
  favorites: Record<string, any>[];
  /** menu_objid 기준 Set — 별표 ON/OFF 빠른 체크용 */
  favoriteIds: Set<string>;
  loading: boolean;
  isFavorite: (menuObjid: string | number) => boolean;
  toggle: (menuObjid: string | number) => Promise<void>;
  refresh: () => Promise<void>;
}

const FavoritesContext = createContext<FavoritesContextType | undefined>(undefined);

export function FavoritesProvider({ children }: { children: ReactNode }) {
  const { user } = useAuth();
  const [favorites, setFavorites] = useState<Record<string, any>[]>([]);
  const [favoriteIds, setFavoriteIds] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await favoritesAPI.getList();
      const rows = res?.success && Array.isArray(res.data) ? res.data : [];
      setFavorites(rows);
      setFavoriteIds(new Set(rows.map((r) => String(r.menu_objid))));
    } catch (err) {
      console.error("즐겨찾기 로드 오류:", err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (!user?.user_id) {
      setFavorites([]);
      setFavoriteIds(new Set());
      return;
    }
    load();
  }, [user?.user_id, load]);

  const isFavorite = useCallback((menuObjid: string | number) => favoriteIds.has(String(menuObjid)), [favoriteIds]);

  const toggle = useCallback(
    async (menuObjid: string | number) => {
      const id = String(menuObjid);
      const currentlyOn = favoriteIds.has(id);

      // 낙관적 업데이트
      setFavoriteIds((prev) => {
        const next = new Set(prev);
        if (currentlyOn) next.delete(id);
        else next.add(id);
        return next;
      });

      try {
        if (currentlyOn) await favoritesAPI.remove(id);
        else await favoritesAPI.add(id);
        await load();
      } catch (err) {
        console.error("즐겨찾기 토글 오류:", err);
        // 롤백
        setFavoriteIds((prev) => {
          const next = new Set(prev);
          if (currentlyOn) next.add(id);
          else next.delete(id);
          return next;
        });
      }
    },
    [favoriteIds, load],
  );

  return (
    <FavoritesContext.Provider
      value={{ favorites, favoriteIds, loading, isFavorite, toggle, refresh: load }}
    >
      {children}
    </FavoritesContext.Provider>
  );
}

export function useFavorites() {
  const ctx = useContext(FavoritesContext);
  if (ctx === undefined) {
    throw new Error("useFavorites must be used within a FavoritesProvider");
  }
  return ctx;
}
