import { useState, useEffect, useCallback } from 'react';
import { MinistryDTO } from '@/types/org';
import { PageResponse, PageRequest } from '@/types/backend';
import { orgService } from '@/services/orgService';

interface UseMinistriesOptions extends PageRequest {
    autoFetch?: boolean;
}

interface UseMinistriesReturn {
    ministries: MinistryDTO[];
    loading: boolean;
    error: string | null;
    page: number;
    totalPages: number;
    totalElements: number;
    refetch: () => Promise<void>;
    setPage: (page: number) => void;
    createMinistry: (ministry: Omit<MinistryDTO, 'id'>) => Promise<MinistryDTO>;
    updateMinistry: (id: string, ministry: MinistryDTO) => Promise<MinistryDTO>;
    deleteMinistry: (id: string) => Promise<void>;
    getMinistryById: (id: string) => Promise<MinistryDTO>;
}

export function useMinistries(options: UseMinistriesOptions = {}): UseMinistriesReturn {
    const {
        page: initialPage = 0,
        size = 20,
        sortBy,
        sortDirection = 'ASC',
        autoFetch = true,
    } = options;

    const [ministries, setMinistries] = useState<MinistryDTO[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [page, setPage] = useState(initialPage);
    const [totalPages, setTotalPages] = useState(0);
    const [totalElements, setTotalElements] = useState(0);

    const fetchMinistries = useCallback(async () => {
        try {
            setLoading(true);
            setError(null);
            const response: PageResponse<MinistryDTO> = await orgService.getMinistries({
                page,
                size,
                sortBy,
                sortDirection,
            });
            setMinistries(response.content);
            setTotalPages(response.totalPages);
            setTotalElements(response.totalElements);
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao carregar ministérios';
            setError(errorMessage);
            console.error('Erro ao buscar ministérios:', err);
        } finally {
            setLoading(false);
        }
    }, [page, size, sortBy, sortDirection]);

    useEffect(() => {
        if (autoFetch) {
            fetchMinistries();
        }
    }, [fetchMinistries, autoFetch]);

    const createMinistry = async (
        ministry: Omit<MinistryDTO, 'id'>
    ): Promise<MinistryDTO> => {
        try {
            setError(null);
            // Casting para MinistryDTO pois o ID será gerado pelo backend
            const newMinistry = await orgService.createMinistry(ministry as MinistryDTO);
            await fetchMinistries();
            return newMinistry;
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao criar ministério';
            setError(errorMessage);
            throw new Error(errorMessage);
        }
    };

    const updateMinistry = async (
        id: string,
        ministry: MinistryDTO
    ): Promise<MinistryDTO> => {
        try {
            setError(null);
            const updated = await orgService.updateMinistry(id, ministry);
            await fetchMinistries();
            return updated;
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao atualizar ministério';
            setError(errorMessage);
            throw new Error(errorMessage);
        }
    };

    const getMinistryById = async (id: string): Promise<MinistryDTO> => {
        try {
            setError(null);
            const ministry = await orgService.getMinistryById(id);
            return ministry;
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao buscar ministério';
            setError(errorMessage);
            throw new Error(errorMessage);
        }
    };

    const deleteMinistry = async (id: string): Promise<void> => {
        try {
            setError(null);
            await orgService.deleteMinistry(id);
            await fetchMinistries();
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao excluir ministério';
            setError(errorMessage);
            throw new Error(errorMessage);
        }
    };

    return {
        ministries,
        loading,
        error,
        page,
        totalPages,
        totalElements,
        refetch: fetchMinistries,
        setPage,
        createMinistry,
        updateMinistry,
        deleteMinistry,
        getMinistryById,
    };
}
