import { ref } from 'vue';
import axios from 'axios';

export function useChapters() {
    const loading = ref(false);
    const error = ref(null);

    const fetchHierarchy = async ({ chapterId = null } = {}) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/Hierarchy', { chapter_id: chapterId });
            return response.data;
        } catch (err) {
            error.value = 'Failed to load chapter hierarchy.';
            console.error(err);
            return { chapters: [], current: null, breadcrumb: [] };
        } finally {
            loading.value = false;
        }
    };

    const fetchMapData = async ({ level = 'region', parentId = null } = {}) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/MapData', { level, parent_id: parentId });
            return response.data;
        } catch (err) {
            error.value = 'Failed to load map data.';
            console.error(err);
            return { chapters: [] };
        } finally {
            loading.value = false;
        }
    };

    const fetchOrgHierarchy = async ({ chapterId = null, island = null } = {}) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/OrgHierarchy', { chapter_id: chapterId, island });
            return response.data;
        } catch (err) {
            error.value = 'Failed to load organization hierarchy.';
            console.error(err);
            return { chapters: [], current: null, breadcrumb: [] };
        } finally {
            loading.value = false;
        }
    };

    const fetchOrgMapData = async ({ level = 'island_group', parentId = null, island = null } = {}) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/OrgMapData', { level, parent_id: parentId, island });
            return response.data;
        } catch (err) {
            error.value = 'Failed to load organization map data.';
            console.error(err);
            return { chapters: [] };
        } finally {
            loading.value = false;
        }
    };

    const fetchMembers = async (chapterId) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/Members', { chapter_id: chapterId });
            return response.data;
        } catch (err) {
            error.value = 'Failed to load members.';
            console.error(err);
            return { members: [] };
        } finally {
            loading.value = false;
        }
    };

    const assignMember = async ({ userHashkey, chapterId, position = null, isManual = true }) => {
        try {
            const response = await axios.post('/Chapters/Member/Assign', {
                user_hashkey: userHashkey,
                chapter_id: chapterId,
                position,
                is_manual: isManual,
            });
            return response.data;
        } catch (err) {
            console.error(err);
            throw err;
        }
    };

    const removeMember = async (hashkey) => {
        try {
            const response = await axios.post('/Chapters/Member/Remove', { hashkey });
            return response.data;
        } catch (err) {
            console.error(err);
            throw err;
        }
    };

    const fetchPositions = async () => {
        try {
            const response = await axios.get('/Chapters/Positions');
            return response.data.positions ?? [];
        } catch (err) {
            console.error(err);
            return [];
        }
    };

    const syncAutoAssignments = async () => {
        try {
            const response = await axios.post('/Chapters/SyncAutoAssignments');
            return response.data;
        } catch (err) {
            console.error(err);
            throw err;
        }
    };

    const fetchOrgChart = async ({ chapterId = null } = {}) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/OrgChart', { chapter_id: chapterId });
            return response.data;
        } catch (err) {
            error.value = 'Failed to load org chart.';
            console.error(err);
            return { own_chapter: null, children: [] };
        } finally {
            loading.value = false;
        }
    };

    const fetchOfficerScope = async () => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/Officer/Scope', {});
            return response.data;
        } catch (err) {
            error.value = 'Failed to load chapter scope.';
            console.error(err);
            return { own_chapter: null, child_chapters: [], cooperative: null, eligible_members: [] };
        } finally {
            loading.value = false;
        }
    };

    const searchMembers = async (query) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await axios.post('/Chapters/Members/Search', { query });
            return response.data?.members ?? [];
        } catch (err) {
            error.value = 'Failed to search members.';
            console.error(err);
            return [];
        } finally {
            loading.value = false;
        }
    };

    const assignOfficer = async ({ memberUserHashkey, childChapterId, role }) => {
        try {
            const response = await axios.post('/Chapters/Officer/Assign', {
                member_user_hashkey: memberUserHashkey,
                child_chapter_id: childChapterId,
                role,
            });
            return response.data;
        } catch (err) {
            console.error(err);
            throw err;
        }
    };

    const createChapter = async ({ name, locationKey, lat = null, lng = null }) => {
        try {
            const response = await axios.post('/Chapters/Create', {
                name,
                location_key: locationKey,
                lat,
                lng,
            });
            return response.data;
        } catch (err) {
            console.error(err);
            throw err;
        }
    };

    return {
        loading,
        error,
        fetchHierarchy,
        fetchMapData,
        fetchOrgHierarchy,
        fetchOrgMapData,
        fetchMembers,
        assignMember,
        removeMember,
        fetchPositions,
        syncAutoAssignments,
        fetchOrgChart,
        fetchOfficerScope,
        searchMembers,
        assignOfficer,
        createChapter,
    };
}
