import { useEffect, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
    closeModal,
    openModal,
    selectPatient,
    setCurrentPage,
    setPageSize,
    setSearchText,
    setSortOrder,
    setViewMode
} from "../../../Redux/Slices/patientsSlice.js";
import { getCachedInfo } from "../../../Utils/cachedInfoUtils.js";

const usePatientsUI = (patients) => {
    const dispatch = useDispatch();
    const {
        searchText,
        sortOrder,
        viewMode,
        isModalVisible,
        currentPage,
        pageSize,
    } = useSelector(state => state.patientsUI);

    useEffect(() => {
        document.title = "Пациенты";
        const cachedViewMode = getCachedInfo("viewModePatients");
        if (cachedViewMode) dispatch(setViewMode(cachedViewMode));
    }, [dispatch]);

    const containerStyle = { padding: 20 };
    const filterBarStyle = { marginBottom: 20 };
    const formItemStyle = { width: "100%" };
    const viewModIconStyle = { marginRight: 8 };

    const handleSetSearchText = (value) => dispatch(setSearchText(value));
    const handleSetSortOrder = (value) => dispatch(setSortOrder(value));
    const handleSetCurrentPage = (page) => dispatch(setCurrentPage(page));
    const handleSetPageSize = (size) => dispatch(setPageSize(size));
    const handleSetViewMode = (mode) => dispatch(setViewMode(mode));
    const handleCloseModal = () => dispatch(closeModal());

    const handlePaginationChange = (page, pageSize) => {
        handleSetCurrentPage(page);
        handleSetPageSize(pageSize);
    };

    const handleAddPatient = () => {
        dispatch(selectPatient(null));
        dispatch(openModal());
    };

    const handleEditPatient = (patient) => {
        dispatch(selectPatient(patient));
        dispatch(openModal());
    };

    const filteredPatients = useMemo(() => {
        return patients
            .filter(patient =>
                Object.values(patient)
                    .filter(value => typeof value === "string")
                    .some(value => value.toLowerCase().includes(searchText.toLowerCase()))
            )
            .sort((a, b) => {
                const fullNameA = `${a.last_name} ${a.first_name}`;
                const fullNameB = `${b.last_name} ${b.first_name}`;
                return sortOrder === "asc" ? fullNameA.localeCompare(fullNameB) : fullNameB.localeCompare(fullNameA);
            });
    }, [patients, searchText, sortOrder]);

    const formatDate = (date) => new Date(date).toLocaleDateString();

    const pagination = {
        currentPage: currentPage,
        pageSize: pageSize,
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "20", "50"],
        onChange: (page, newPageSize) => {
            handlePaginationChange(page, newPageSize);
        },
    };

    return {
        searchText,
        sortOrder,
        viewMode,
        isModalVisible,
        currentPage,
        pageSize,
        containerStyle,
        filterBarStyle,
        formItemStyle,
        viewModIconStyle,
        pagination,
        filteredPatients: filteredPatients.map(p => ({ ...p, key: p.id })),
        handleSetSearchText,
        handleSetSortOrder,
        handleSetViewMode,
        handleCloseModal,
        handleAddPatient,
        handleEditPatient,
        formatDate,
        handlePaginationChange,
    };
};

export default usePatientsUI;
