'use client';

import { useState, useEffect } from 'react';

interface UseEditorDataProps {
  type: 'latest' | 'trending' | 'latest-author' | string;
  count?: number;
  skip?: boolean;
}

export function useEditorData<T>({ type, count = 5, skip = false }: UseEditorDataProps) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(!skip);

  useEffect(() => {
    if (skip) {
      setLoading(false);
      return;
    }

    let active = true;
    setLoading(true);

    fetch(`/api/editor/data?type=${type}&count=${count}`)
      .then((res) => {
        if (!res.ok) throw new Error('Failed to fetch');
        return res.json();
      })
      .then((json) => {
        if (active) {
          setData(json.data);
          setLoading(false);
        }
      })
      .catch((err) => {
        console.error('Error fetching editor data:', err);
        if (active) {
          setLoading(false);
        }
      });

    return () => {
      active = false;
    };
  }, [type, count, skip]);

  return { data, loading };
}
