import { useState, useCallback } from 'react';
import api from '../api';

export interface Product {
    id: number;
    nombre: string;
    categoria: string;
    precio: number;
    ultima_actualizacion: string;
}

export function usePrices() {
    const [products, setProducts] = useState<Product[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const fetchPrices = useCallback(async () => {
        setIsLoading(true);
        setError(null);
        try {
            const response = await api.get('/productos');
            setProducts(response.data);
        } catch (err: any) {
            setError(err.response?.data?.message || 'Error al obtener precios');
        } finally {
            setIsLoading(false);
        }
    }, []);

    const updatePrice = async (id: number, data: Partial<Product>) => {
        try {
            const response = await api.put(`/productos/${id}`, data);
            // Actualizar localmente la lista tras una modificación exitosa
            setProducts(prev => prev.map(p => p.id === id ? { ...p, ...response.data } : p));
            return response.data;
        } catch (err: any) {
            console.error('Update price error:', err);
            throw new Error(err.response?.data?.message || 'Error al actualizar precio');
        }
    };

    const downloadPDF = async () => {
        try {
            const response = await api.get('/productos/export/pdf', {
                responseType: 'blob', // Necesario para procesar el stream binario del PDF
            });
            const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `lista_precios_belen_${new Date().toISOString().split('T')[0]}.pdf`);
            document.body.appendChild(link);
            link.click();
            link.parentNode?.removeChild(link);
        } catch (err: any) {
            console.error('PDF error:', err);
            throw new Error('Error al descargar el PDF de precios');
        }
    };

    return { products, isLoading, error, fetchPrices, updatePrice, downloadPDF };
}
