import { useState, useEffect } from 'react';
import studentService from '../services/serviceStudents';

const useStudents = () => {
    const [students, setStudents] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [fileImport, setFileImport] = useState(null);

    const [selectedStudent, setSelectedStudent] = useState(null);
    const [formData, setFormData] = useState({
        fullName: '',
        nisn: '',
        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 = () =>{
        setFileImport(null);
        setFormData({
            fullName: '',
            nisn: '',
            email:  '',
            pass: '',
            confirm_pass: '',
        });
    }

    const resetImportFile = () => {setFileImport(null)}

    const createStudent = async (data) => {
        try {
            const newStudent ={
                NAME_USERS: data.fullName,
                NISN: data.nisn,
            };
            const createdStudent = await studentService.createData(newStudent);
            setStudents((prevStudents) => [...prevStudents, createdStudent.payload]);
            resetForm();
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your new entry has been successfully created and saved.'
            }));
        } catch (err) {
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.response.data.message
            }));
        }
    };

    const importRegister = async () => {
        const fileData = new FormData();
        const file = fileImport;
        fileData.append('file', file);
        console.log(file);
        try {
            const response = await studentService.registerImport(fileData);
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your new entry has been successfully created and saved.'
            }));
            resetForm();
        } catch (err) {
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.response.data.message
            }));
        }
    }

    const editStudent = async (id, data) => {
        const formData = new FormData();
        formData.append('NAME_USERS', data.fullName);
        formData.append('EMAIL', data.email);
        formData.append('NISN', data.nisn);
        try {
            const student = await studentService.updateData(id, formData);
            setStudents((prevStudents) => 
                prevStudents.map((s) => (s.ID === id ? student.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 deleteStudent = async (id) => {
        handleShowLoader('Deleted', '', true)
        try {
            await studentService.deleteData(id);
            setStudents((prevStudents) => prevStudents.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 handleFileChange = (e) => {
        setFileImport(e.target.files[0]);
    };

    const handleShow = (data) => {
        setSelectedStudent(data);
        setFormData({
            fullName: data?.NAME_USERS || '',
            nisn: data?.NISN || '',
            email: data?.EMAIL || ''
        });
        setShow(true);
    };
    const handleClose = () => {setShow(false); resetForm(); setSelectedStudent(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 studentService.fetchData(search, sort, page, limit);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalStudents);
            setStudents(data.payload.students);
        } 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]);


    const handleDownloadTemplate = async () => {
        try {
            const response = await studentService.getTemplate();
    
            const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const downloadUrl = URL.createObjectURL(blob);
    
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = 'template.xlsx';
            link.click();
    
            URL.revokeObjectURL(downloadUrl);
        } catch (error) {
            console.error('Error downloading file:', error);
            alert('Gagal mengunduh file');
        }
    }

    return { 
        students, 
        loading, 
        error, 
        selectedStudent, 
        formData, 

        createStudent, 
        editStudent, 
        deleteStudent,
        setSelectedStudent,
        setFormData,
        handleFormChange,
        resetForm,

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

        totalPages,
        totalData,
        setSearch,
        page, 
        handlePageChange,
        handleLimitsChange,
        handleSerachChange,
        handleFileChange,
        handleDownloadTemplate,
        importRegister,
        fileImport,
        resetImportFile
    };
};

export default useStudents;
