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

interface UseOrgUnitsOptions extends PageRequest {
    autoFetch?: boolean;
    ministryId?: string;
    parentUnitId?: string;
}

interface UseOrgUnitsReturn {
    orgUnits: OrgUnitDTO[];
    loading: boolean;
    error: string | null;
    page: number;
    totalPages: number;
    totalElements: number;
    refetch: () => Promise<void>;
    setPage: (page: number) => void;
    createOrgUnit: (orgUnit: Omit<OrgUnitDTO, 'id'>) => Promise<OrgUnitDTO>;
    updateOrgUnit: (id: string, orgUnit: OrgUnitDTO) => Promise<OrgUnitDTO>;
    getOrgUnitById: (id: string) => Promise<OrgUnitDTO>;
}

export function useOrgUnits(options: UseOrgUnitsOptions = {}): UseOrgUnitsReturn {
    const {
        page: initialPage = 0,
        size = 20,
        sortBy,
        sortDirection = 'ASC',
        autoFetch = true,
        ministryId,
        parentUnitId,
    } = options;

    const [orgUnits, setOrgUnits] = useState<OrgUnitDTO[]>([]);
    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 fetchOrgUnits = useCallback(async () => {
        try {
            setLoading(true);
            setError(null);
            const response: any = await orgService.getOrgUnits({
                page,
                size,
                sortBy,
                sortDirection,
                ministryId,
                parentUnitId,
            });

            if (Array.isArray(response)) {
                setOrgUnits(response);
                setTotalPages(1);
                setTotalElements(response.length);
            } else {
                setOrgUnits(response.content);
                setTotalPages(response.totalPages);
                setTotalElements(response.totalElements);
            }
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao carregar unidades orgânicas';
            setError(errorMessage);
            console.error('Erro ao buscar unidades orgânicas:', err);
        } finally {
            setLoading(false);
        }
    }, [page, size, sortBy, sortDirection, ministryId, parentUnitId]);

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

    const createOrgUnit = async (
        orgUnit: Omit<OrgUnitDTO, 'id'>
    ): Promise<OrgUnitDTO> => {
        try {
            setError(null);
            const newOrgUnit = await orgService.createOrgUnit(orgUnit as OrgUnitDTO);
            await fetchOrgUnits();
            return newOrgUnit;
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao criar unidade orgânica';
            setError(errorMessage);
            throw new Error(errorMessage);
        }
    };

    const updateOrgUnit = async (
        id: string,
        orgUnit: OrgUnitDTO
    ): Promise<OrgUnitDTO> => {
        try {
            setError(null);
            const updated = await orgService.updateOrgUnit(id, orgUnit);
            await fetchOrgUnits();
            return updated;
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao atualizar unidade orgânica';
            setError(errorMessage);
            throw new Error(errorMessage);
        }
    };

    const getOrgUnitById = async (id: string): Promise<OrgUnitDTO> => {
        try {
            setError(null);
            const orgUnit = await orgService.getOrgUnitById(id);
            return orgUnit;
        } catch (err: any) {
            const errorMessage =
                err.response?.data?.message ||
                err.message ||
                'Erro ao buscar unidade orgânica';
            setError(errorMessage);
            throw new Error(errorMessage);
        }
    };

    return {
        orgUnits,
        loading,
        error,
        page,
        totalPages,
        totalElements,
        refetch: fetchOrgUnits,
        setPage,
        createOrgUnit,
        updateOrgUnit,
        getOrgUnitById,
    };
}
