import { useCallback, useEffect, useMemo, useRef } from 'react';
import type { Recipient } from '../services/recipientService';
import {
    useRecipientsStore,
    type RecipientDetailCacheEntry,
} from '../stores/recipientsStore';
import { useGlobalLoading } from './useGlobalLoading';

interface UseRecipientDetailReturn {
    recipient: Recipient | null;
    loading: boolean;
    error: string | null;
    refreshRecipient: () => Promise<void>;
}

const defaultEntry: RecipientDetailCacheEntry = {
    recipient: null,
    loading: false,
    error: null,
};

export const useRecipientDetail = (
    recipientId: string | null | undefined
): UseRecipientDetailReturn => {
    const id = recipientId ?? null;
    const lastIdRef = useRef<string | null>(null);

    const ensureDetail = useRecipientsStore((state) => state.ensureRecipientDetail);
    const refreshDetail = useRecipientsStore((state) => state.refreshRecipientDetail);
    const removeDetail = useRecipientsStore((state) => state.removeRecipientDetail);

    const entry = useRecipientsStore(
        useCallback(
            (state) => (id ? state.recipientDetails[id] ?? defaultEntry : defaultEntry),
            [id]
        )
    );
    const { withLoading } = useGlobalLoading();

    useEffect(() => {
        if (lastIdRef.current && lastIdRef.current !== id) {
            removeDetail(lastIdRef.current);
        }
        lastIdRef.current = id;
    }, [id, removeDetail]);

    useEffect(() => {
        if (!id) {
            return;
        }
        ensureDetail(id);
    }, [ensureDetail, id]);

    const refreshRecipient = useCallback(async () => {
        if (!id) {
            return;
        }
        await withLoading(() => refreshDetail(id));
    }, [id, refreshDetail, withLoading]);

    return useMemo(
        () => ({
            recipient: id ? entry.recipient : null,
            loading: id ? entry.loading : false,
            error: id ? entry.error : null,
            refreshRecipient,
        }),
        [entry.error, entry.loading, entry.recipient, id, refreshRecipient]
    );
};


