import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { notification } from "antd";
import {
    useGetPatientsQuery,
    useDeletePatientMutation,
} from "../../../Api/patientsApi.js";
import {
    closeModal,
    openModal,
    selectPatient,
    setCurrentPage,
    setPageSize,
    setSortOrder,
    setViewMode
} from "../../../Redux/Slices/patientsSlice.js";
import { getCachedInfo } from "../../../Utils/cachedInfoUtils.js";

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

    const [tempSearchText, setTempSearchText] = useState("");

    const { data = { patients: [], total_count: 0 }, isLoading, isError } = useGetPatientsQuery(
        { page: currentPage, pageSize, search: tempSearchText || undefined, sortOrder },
        {
            pollingInterval: 20000, // Автообновление каждые 20 секунд
            refetchOnMountOrArgChange: true, // Обновление при изменении параметров
        }
    );

    const [deletePatient] = useDeletePatientMutation();

    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 handleSetTempSearchText = (value) => {
        setTempSearchText(value);
        dispatch(setCurrentPage(1)); // Сбрасываем на первую страницу при изменении поиска
    };

    const handleClearSearch = () => {
        setTempSearchText("");
        dispatch(setCurrentPage(1));
    };

    const handleDeletePatient = async (patientId) => {
        try {
            await deletePatient(patientId).unwrap();
            notification.success({
                message: "Пациент удалён",
                description: "Пациент успешно удалён из базы.",
                placement: "topRight",
            });
        } catch (error) {
            notification.error({
                message: "Ошибка удаления",
                description: error?.data?.detail || "Не удалось удалить пациента",
                placement: "topRight",
            });
        }
    };

    const handleSetSortOrder = (value) => {
        dispatch(setSortOrder(value));
        dispatch(setCurrentPage(1)); // Сбрасываем на первую страницу при изменении сортировки
    };

    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 formatDate = (date) => new Date(date).toLocaleDateString();

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

    return {
        searchText: tempSearchText,
        sortOrder,
        viewMode,
        isModalVisible,
        currentPage,
        pageSize,
        containerStyle,
        filterBarStyle,
        formItemStyle,
        viewModIconStyle,
        pagination,
        patients: data.patients,
        totalCount: data.total_count,
        isLoading,
        isError,
        filteredPatients: data.patients.map(p => ({ ...p, key: p.id })),
        handleSetSearchText: handleSetTempSearchText,
        handleClearSearch,
        handleDeletePatient,
        handleSetSortOrder,
        handleSetCurrentPage,
        handleSetPageSize,
        handleSetViewMode,
        handleCloseModal,
        handleAddPatient,
        handleEditPatient,
        formatDate,
        handlePaginationChange,
    };
};

export default usePatients;