import { useState, useEffect } from 'react';
import topicService from '../services/serviceTopics';

const useTopics = () => {
    const [topics, setTopics] = useState([]);
    const [sections, setSections] = useState([]);
    const [sectionSlug, setSectionSlug] = useState({});
    const [loading, setLoading] = useState(true);
    const [loadingSlug, setLoadingSlug] = useState(true);
    const [error, setError] = useState(null);
    const [selectedTopic, setSelectedTopic] = useState(null);
    const [formData, setFormData] = useState({
        sectionId: '',
        topicName: '',
        description:  '',
    });
    const [show, setShow] = useState(false);
    const [showLoader, setShowLoader] = useState(false);
    const [loaderState, setLoaderState] = useState({ loading: false, successMessage: '', title: '', description: '', confirmAction: false });

    const handleFormChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleShow = (data) => {
        setSelectedTopic(data);
        setFormData({
            sectionId: data?.ID_SECTION || '',
            topicName: data?.NAME_TOPIC || '',
            description: data?.DESCRIPTION_TOPIC || '',
        });
        setShow(true);
    };
    const handleClose = () => {setShow(false); resetForm(); setSelectedTopic(null)};
    
    const handleCloseLoader = () => setShowLoader(false);
    const handleShowLoader = (title, description, loading = false, successMessage = '', confirmAction = false) => {
        setLoaderState({ title, description, loading, successMessage, confirmAction });
        setShowLoader(true);
    };

    const resetForm = () =>{
        setFormData({
            sectionId: '',
            topicName: '',
            description:  '',
        });
    }
    
    const fetchDataSection = async () => {
        setLoadingSlug(true);
        try {
            const sectionArray = {};
            const data = await topicService.fetchDataSection();
            setSections(data.payload);
            data.payload.map((s) => {
                sectionArray[s.ID_SECTION] = s.NAME_SECTION;
            });
            setSectionSlug(sectionArray);
        } catch (err) {
            setError(err);
        } finally {
            setLoadingSlug(false);
        }
    };

    const createTopic = async () => {
        const data = formData;
        handleShowLoader('Created', '', true);
        try {
            const newTopic = {
                ID_SECTION: data.sectionId,
                NAME_TOPIC: data.topicName,
                DESCRIPTION_TOPIC: data.description,
            };
            const createdTopic = await topicService.createData(newTopic);
            setTopics((prevTopics) => [...prevTopics, createdTopic.payload.topic]);
            resetForm();
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your new entry has been successfully created and saved.'
            }));
        } catch (err) {
            setError(err);
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.message
            }));
        }
    };

    const editTopic = async () => {
        const id = selectedTopic.ID_TOPIC
        const updateData = {
            ID_SECTION: formData.sectionId,
            NAME_TOPIC: formData.topicName,
            DESCRIPTION_TOPIC: formData.description,
        };
        handleClose();
        handleShowLoader('Updated', '', true);
        try {
            const topic = await topicService.updateData(id, updateData);
            setTopics((prevTopics) => 
                prevTopics.map((s) => (s.ID_TOPIC === id ? topic.payload : s))
            );
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your data has been successfully updated.'
            }));
        } catch (err) {
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.response.data.message
            }));
        }
    };

    const deleteTopic = async (id) => {
        handleShowLoader('Deleted', 'Are you sure you want to delete this Topic?', false, '', true);
        const confirmDelete = async () => {
            handleCloseLoader();

            handleShowLoader('Deleted', '', true)
            try {
                await topicService.deleteData(id);
                setTopics((prevTopics) => prevTopics.filter((s) => s.ID_TOPIC !== id));
                setLoaderState(prev => ({
                    ...prev,
                    loading: false,
                    successMessage: 'Your data has been successfully deleted.'
                }));
            } catch (err) {
                setLoaderState(prev => ({
                    ...prev,
                    title: "ERROR",
                    loading: false,
                    successMessage: err.response.data.message
                }));
            }
        }
        setLoaderState(prev => ({ ...prev, handleConfirm: confirmDelete }));
    };

    const [search, setSearch] = useState("");
    const [sort, setSort] = useState("");
    const [page, setCurrentPage] = useState(1);
    const [limit, setLimit] = useState(7);
    const [totalPages, setTotalPages] = useState(0);
    const [totalData, setTotalData] = useState(null);
    
    const fetchData = async () => {
        setLoading(true);
        try {
            const data = await topicService.fetchData(search, sort, page, limit);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalItems);
            setTopics(data.payload.topics);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };

    const handleSerachChange = () => {
        fetchData();
        setCurrentPage(1);
    }

    const handlePageChange = (pages) => {
        setCurrentPage(pages);
    }

    const handleLimitsChange = (e) => {
        setLimit(e.target.value);
        setCurrentPage(1);
    }

    useEffect(() => {
        fetchDataSection();
    }, []);

    useEffect(() => {
        fetchData();
    }, [page, limit]);

    return { 
        topics, 
        sections,
        sectionSlug,
        loading, 
        loadingSlug,
        error, 
        selectedTopic, 
        formData, 

        createTopic, 
        editTopic, 
        deleteTopic,
        setSelectedTopic,
        setFormData,
        handleFormChange,
        resetForm,

        show,
        setShow,
        handleShow,
        handleClose,
        showLoader,
        handleShowLoader,
        handleCloseLoader,
        loaderState,
        setLoaderState,

        totalPages,
        totalData,
        setSearch,
        page, 
        handlePageChange,
        handleLimitsChange,
        handleSerachChange
    };
};

export default useTopics;
