import { useState, useEffect } from 'react';
import sectionService from '../services/serviceSections';
import { MEDIA_URL } from '../../../../utils/Constant';

const useSections = () => {
    const thumbPath = `${MEDIA_URL}/section/`;
    const [sections, setSections] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [selectedSection, setSelectedSection] = useState(null);
    const [selectedImage, setSelectedImage] = useState(null);
    const [formData, setFormData] = useState({
        sectionName: '',
        description:  '',
        thumbnail: ''
    });
    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 handleImageChange = (e) => {
        const file = e.target.files[0];
        if (file && file.size <= 5 * 1024 * 1024) {
          setSelectedImage(file);
        } else {
          setError('File size must be less than 5 MB');
        }
    };

    const handleShow = (data) => {
        setSelectedSection(data);
        setFormData({
            sectionName: data?.NAME_SECTION || '',
            description: data?.DESCRIPTION_SECTION || '',
            thumbnail: data?.THUMBNAIL || '',
        });
        setShow(true);
    };
    const handleClose = () => {setShow(false); resetForm(); setSelectedSection(null)};
    
    const handleCloseLoader = () => setShowLoader(false);
    const handleShowLoader = (title, description, loading = false, successMessage = '', confirmAction = false) => {
        setLoaderState({ title, description, loading, successMessage, confirmAction });
        setShowLoader(true);
    };

    const resetForm = () =>{
        setSelectedImage(null);
        setFormData({
            sectionName: '',
            description:  '',
            thumbnail: ''
        });
    }

    const createSection = async () => {
        const createData = new FormData();
        createData.append('NAME_SECTION', formData.sectionName,);
        createData.append('DESCRIPTION_SECTION', formData.description,);
        if (selectedImage) {
            createData.append('THUMBNAIL', selectedImage);
        }

        handleShowLoader('Created', '', true);
        try {
            const createdSection = await sectionService.createData(createData);
            setSections((prevSections) => [...prevSections, createdSection.payload]);
            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 editSection = async () => {
        const id = selectedSection.ID_SECTION

        const updateData = new FormData();
        updateData.append('NAME_SECTION', formData.sectionName,);
        updateData.append('DESCRIPTION_SECTION', formData.description,);
        if (selectedImage) {
            updateData.append('THUMBNAIL', selectedImage);
        }

        handleClose();
        handleShowLoader('Updated', '', true);
        try {
            const section = await sectionService.updateData(id, updateData);
            setSections((prevSections) => 
                prevSections.map((s) => (s.ID_SECTION === id ? section.payload : s))
            );
        } catch (err) {
            setError(err);
        }finally{
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your data has been successfully updated.'
            }));
        }
    };

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

            handleShowLoader('Deleted', '', true)
            try {
                await sectionService.deleteData(id);
            } catch (err) {
                setError(err);
            }finally{
                setSections((prevSections) => prevSections.filter((s) => s.ID_SECTION !== id));
                setLoaderState(prev => ({
                    ...prev,
                    loading: false,
                    successMessage: 'Your data has been successfully deleted.'
                }));
            }
        }
        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 sectionService.fetchData(search, sort, page, limit);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalItems);
            setSections(data.payload.sections);
        } 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(() => {
        fetchData();
    }, []);


    return { 
        sections, 
        loading, 
        error, 
        selectedSection, 
        selectedImage, 
        formData, 

        createSection, 
        editSection, 
        deleteSection,
        setSelectedSection,
        setFormData,
        handleFormChange,
        handleImageChange,
        resetForm,

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

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

export default useSections;
