import { useState } from 'react';
import { apiFetch } from '@/lib/loading/api-fetch';

interface FetchSuggestionsParams {
    comment: string;
    postCaption: string;
    platform: 'facebook' | 'instagram';
}

interface UseMetaAiSuggestionsResult {
    suggestions: string[];
    setSuggestions: React.Dispatch<React.SetStateAction<string[]>>;
    loading: boolean;
    fetchSuggestions: (params: FetchSuggestionsParams) => Promise<void>;
}

export function useMetaAiSuggestions(): UseMetaAiSuggestionsResult {
    const [suggestions, setSuggestions] = useState<string[]>([]);
    const [loading, setLoading] = useState(false);

    const fetchSuggestions = async ({ comment, postCaption, platform }: FetchSuggestionsParams) => {
        if (loading) return;
        setLoading(true);
        setSuggestions([]);
        try {
            const res = await apiFetch('/meta/ai/suggest-reply', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
                },
                body: JSON.stringify({ comment, post_caption: postCaption, platform }),
            });
            if (res.ok) {
                const data = await res.json();
                setSuggestions(data.suggestions ?? []);
            }
        } catch {
            /* ignore */
        } finally {
            setLoading(false);
        }
    };

    return { suggestions, setSuggestions, loading, fetchSuggestions };
}
