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);
            setTeachers((prevTeachers) => [...prevTeachers, createdTeacher.payload]);
        } catch (err) {
            setError(err);
        }finally{
            resetForm();
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your new entry has been successfully created and saved.'
            }));
        }
    };

    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))
            );
        } catch (err) {
            setError(err);
        }finally{
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your data has been successfully updated.'
            }));
        }
    };

    const deleteTeacher = async (id) => {
        handleShowLoader('Deleted', '', true)
        try {
            await teacherService.deleteData(id);
        } catch (err) {
            setError(err);
        }finally{
            setTeachers((prevTeachers) => prevTeachers.filter((s) => s.ID !== id));
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your data has been successfully deleted.'
            }));
        }
    };

    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;
