import { useState, useEffect } from 'react';
import teacherService from '../services/serviceTeachers';

const useTeachers = () => {
    const [teachers, setTeachers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const [selectedTeacher, setSelectedTeacher] = useState(null);
    const [formData, setFormData] = useState({
        fullName: '',
        nip: '',
        email: '',
        pass: '',
        confirm_pass: '',
    });

    const [show, setShow] = useState(false);

    const [showLoader, setShowLoader] = useState(false);
    const [loaderState, setLoaderState] = useState({ loading: false, successMessage: '', title: '', description: '', confirmAction: false });

    const resetForm = () =>{
        setFormData({
            fullName: '',
            nip: '',
            email:  '',
            pass: '',
            confirm_pass: '',
        });
    }

    const createTeacher = async (data) => {
        try {
            const newTeacher ={
                NAME_USERS: data.fullName,
                EMAIL: data.email,
                NIP: data.nip,
                PASSWORD: data.pass,
                CONFIRM_PASSWORD: data.confirm_pass,
            };
            const createdTeacher = await teacherService.createData(newTeacher);
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'New teacher has been successfully created. waiting to verify the email.'
            }));
            resetForm();
        } catch (err) {
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.response.data.message
            }));
        }
    };

    const editTeacher = async (id, data) => {
        const formData = new FormData();
        formData.append('NAME_USERS', data.fullName);
        formData.append('EMAIL', data.email);
        formData.append('NIP', data.nip);
        try {
            const Teacher = await teacherService.updateData(id, formData);
            setTeachers((prevTeachers) => 
                prevTeachers.map((s) => (s.ID === id ? Teacher.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 deleteTeacher = async (id) => {
        handleShowLoader('Deleted', '', true)
        try {
            await teacherService.deleteData(id);
            setTeachers((prevTeachers) => prevTeachers.filter((s) => s.ID !== 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
            }));
        }
    };

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

    const handleShow = (data) => {
        setSelectedTeacher(data);
        setFormData({
            fullName: data?.NAME_USERS || '',
            nip: data?.NIP || '',
            email: data?.EMAIL || ''
        });
        setShow(true);
    };
    const handleClose = () => {setShow(false); resetForm(); setSelectedTeacher(null)};
    
    const handleCloseLoader = () => setShowLoader(false);
    const handleShowLoader = (title, description, loading = false, successMessage = '', confirmAction = false) => {
        setLoaderState({ title, description, loading, successMessage, confirmAction });
        setShowLoader(true);
    };

    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 teacherService.fetchData(search, sort, page, limit);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalTeachers);
            setTeachers(data.payload.teachers);
        } 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();
    }, [page, limit]);


    return { 
        teachers, 
        loading, 
        error, 
        selectedTeacher, 
        formData, 

        createTeacher, 
        editTeacher, 
        deleteTeacher,
        setSelectedTeacher,
        setFormData,
        handleFormChange,
        resetForm,

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

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

export default useTeachers;
