import { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';

export const useDashboardHistory = (userId: string) => {
    const [history, setHistory] = useState<any[]>([]);
    const [loadingHistory, setLoadingHistory] = useState(false);

    const fetchHistory = async () => {
        if (!userId) return;

        setLoadingHistory(true);
        try {
            const { data, error } = await supabase
                .from('food_analyses')
                .select('*')
                .eq('user_id', userId)
                .order('created_at', { ascending: false })
                .limit(20);

            if (error) {
                console.error("Error fetching history:", error);
                setHistory([]);
                return;
            }

            if (data) {
                const formatted = data.map((item: any) => {
                    // Parse do ai_structured para pegar os itens
                    let itemDetails = '';
                    try {
                        // Verifica se é string antes de parsear, se já for objeto usa direto
                        const structured = typeof item.ai_structured === 'string'
                            ? JSON.parse(item.ai_structured)
                            : item.ai_structured;

                        if (structured?.items && Array.isArray(structured.items)) {
                            itemDetails = structured.items.map((i: any) => i.name).join(', ');
                        }
                    } catch (e) {
                        console.log('Error parsing AI structure', e);
                    }

                    // Construção da URL do Bucket
                    const bucketUrl = `https://mnhgpnqkwuqzpvfrwftp.supabase.co/storage/v1/object/public/consultas/${item.user_id}/${item.id}.jpg`;

                    return {
                        id: item.id,
                        date: new Date(item.created_at).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }),
                        category: item.category || 'Refeição',
                        details: itemDetails,
                        score: item.nutrition_score || 0,
                        cals: Math.round(item.total_calories || 0),
                        protein: Math.round(item.total_protein || 0) + 'g',
                        carbs: Math.round(item.total_carbs || 0) + 'g',
                        fat: Math.round(item.total_fat || 0) + 'g',
                        img: bucketUrl
                    };
                });
                setHistory(formatted);
            }
        } catch (err) {
            console.error("Error fetching history:", err);
        } finally {
            setLoadingHistory(false);
        }
    };

    useEffect(() => {
        fetchHistory();
    }, [userId]);

    return { history, loadingHistory, refetchHistory: fetchHistory };
};
