import { useEffect, useState } from 'react';
import serviceHistory from '../services/historyService';
import { useSlugContext } from '../../../../utils/SlugContext';

const useHistories = () => {
  const [historyData, setHistoryData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [loadingTopic, setLoadingTopic] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('all');
  const { sectionSlugMap } = useSlugContext();
  const sectionData = Object.keys(sectionSlugMap);

  const [topicsBySection, setTopicsBySection] = useState({});
  const [selectedTopic, setSelectedTopic] = useState(null);

    const findKeyById = (id) => {
        for (const key in sectionSlugMap) {
            if (sectionSlugMap[key] === id) {
                return key;
            }
        }
        return null;
    };

    useEffect(() => {
        const fetchTopics = async () => {
            setLoadingTopic(true);
            try {
                const topics = await serviceHistory.fetchTopic();
                const groupedTopics = topics.payload.reduce((acc, topic) => {
                    const section = findKeyById(topic.ID_SECTION);
                    if (!acc[section]) acc[section] = [];
                    acc[section].push(topic);
                    return acc;
                }, {});
                setTopicsBySection(groupedTopics);
            } catch (error) {
                console.log('Failed to fetch topics', error);
            } finally {
                setLoadingTopic(false);
            }
        };

        fetchTopics();
    }, []);

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            setError(null);
            try {
                let data;
                if (selectedTopic) {
                    data = await serviceHistory.fetchHistoryByTopic(selectedTopic);
                } else if (activeTab === 'all') {
                    data = await serviceHistory.fetchAllHistory();
                } else {
                    data = await serviceHistory.fetchHistoryBySection(sectionSlugMap[activeTab]);
                }
                console.log(data.payload);
                setHistoryData(data.payload);
            } catch (error) {
                if (error.status == 404) {
                    setHistoryData([]);
                }else{
                    console.log(error);
                    setError(error.message);
                }
            } finally {
                setLoading(false);
            }
        };
        
        fetchData();
    }, [activeTab, selectedTopic]);

    function formatLocalDate(isoDate) {
        const date = new Date(isoDate);
    
        const options = {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false,
            timeZone: 'Asia/Jakarta'
        };
    
        return new Intl.DateTimeFormat('id-ID', options).format(date)
            .replace(/\//g, '-')
            .replace(/\./g, ':') + ' WIB';
    }

    function compareLevels(currentLevel, nextLevel) {
        function extractNumber(level) {
            if (level !== null) {
                const match = level.match(/\d+/);
                return match ? parseInt(match[0]) : 0;
            }else{
                console.error('some parameter is null');
                return null;
            }
        }
    
        const current = extractNumber(currentLevel);
        const next = extractNumber(nextLevel);
    
        if (current === next) {
            return 'stay';
        } else if (current > next) {
            return 'down';
        } else {
            return 'jump';
        }
    }

    return { 
        historyData, 
        sectionData,
        loading, 
        error, 
        activeTab, 
        topicsBySection,
        selectedTopic,
        setActiveTab, 
        formatLocalDate, 
        compareLevels, 
        setSelectedTopic,
    };
};

export default useHistories;
