"use client";

import { useState, useCallback, useEffect } from "react";
import { subscribeService } from "@/services/subscribeService";
import { useRequireAuth } from "@/hooks/useRequireAuth";

/**
 * Reusable subscribe / unsubscribe toggle hook.
 *
 * Performs an optimistic UI update: flips state immediately, then calls
 * the API. On failure it rolls back to the previous state.
 *
 * @param toUserId      Channel owner's user_id (from API response `id` or `user_id` field).
 * @param initialState  Current subscription status (`is_subscriber === 1`).
 * @param userType      User type (1 = regular, 2 = creator). Defaults to 1.
 */
export function useSubscribe(
  toUserId: string | number,
  initialState: boolean,
  userType = 1,
) {
  const [subscribed, setSubscribed] = useState(initialState);
  const [loading, setLoading]       = useState(false);
  const requireAuth = useRequireAuth();

  // Sync state when the authoritative initial value arrives (e.g. profile API
  // response loads after the first render — useState ignores later changes to
  // the initial arg, so we mirror it here explicitly).
  useEffect(() => {
    setSubscribed(initialState);
  }, [initialState]);

  const doToggle = useCallback(async () => {
    if (loading) return;
    const prev = subscribed;
    setSubscribed(!prev);
    setLoading(true);
    try {
      const res = await subscribeService.toggle(toUserId, userType);
      if (res.status !== 200) setSubscribed(prev);
    } catch {
      setSubscribed(prev);
    } finally {
      setLoading(false);
    }
  }, [loading, subscribed, toUserId, userType]);

  const toggle = useCallback(
    () => requireAuth(() => { doToggle(); }),
    [requireAuth, doToggle],
  );

  return { subscribed, loading, toggle };
}
