import { useState, useEffect } from 'react';
import type { PDFPage } from '../types';
import apiService from '../services/apiService';

export function usePdfPages(storageKey: string | undefined | null) {
    const [pdfPages, setPdfPages] = useState<PDFPage[] | undefined>(undefined);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (!storageKey || !storageKey.toLowerCase().endsWith('.pdf')) {
            setPdfPages(undefined);
            return;
        }

        let cancelled = false;
        const loadPages = async () => {
            setLoading(true);
            setError(null);
            try {
                const pages = await apiService.getPdfPages(storageKey);
                if (!cancelled) setPdfPages(pages);
            } catch (err) {
                if (!cancelled) {
                    setError(err instanceof Error ? err.message : 'Failed to load PDF');
                    setPdfPages(undefined);
                }
            } finally {
                if (!cancelled) setLoading(false);
            }
        };
        loadPages();
        return () => { cancelled = true; };
    }, [storageKey]);

    return { pdfPages, loading, error };
}
