import {useEffect, useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {notification} from "antd";
import {
    useAddLensIssuesMutation,
    useGetLensIssuesQuery,
} from "../../../Api/lensIssuesApi.js";
import {useGetAllPatientsQuery} from "../../../Api/patientsApi.js";
import {
    closeModal,
    openModal,
    selectIssue,
    setCurrentPage,
    setEndFilterDate,
    setPageSize,
    setViewMode,
    setStartFilterDate,
} from "../../../Redux/Slices/lensIssuesSlice.js";
import {getCachedInfo} from "../../../Utils/cachedInfoUtils.js";
import dayjs from "dayjs";
import {useGetNotIssuedLensesQuery} from "../../../Api/lensesApi.js";

const useIssues = () => {
    const dispatch = useDispatch();
    const {
        currentPage,
        pageSize,
        selectedIssue,
        isModalVisible,
        viewMode,
        startFilterDate,
        endFilterDate,
    } = useSelector(state => state.lensIssuesUI);

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

    const {
        data: issuesData = {issues: [], total_count: 0},
        isLoading: isIssuesLoading,
        isError: isIssuesError,
        error: issuesError,
        refetch
    } = useGetLensIssuesQuery({
        page: currentPage,
        pageSize,
        search: tempSearchText || undefined, // Используем tempSearchText напрямую
        sortOrder: 'desc',
        startDate: startFilterDate ? dayjs(startFilterDate).format('YYYY-MM-DD') : undefined,
        endDate: endFilterDate ? dayjs(endFilterDate).format('YYYY-MM-DD') : undefined,
    }, {
        pollingInterval: 20000,
    });

    const {data: patients = [], isLoading: isPatientsLoading, isError: isPatientsError} = useGetAllPatientsQuery();
    const {data: lenses = [], isLoading: isLensesLoading, isError: isLensesError} = useGetNotIssuedLensesQuery();
    const [addIssue, {isLoading: isAdding}] = useAddLensIssuesMutation();

    const isLoading = isIssuesLoading || isPatientsLoading || isLensesLoading;
    const isError = isIssuesError || isPatientsError || isLensesError;

    useEffect(() => {
        document.title = "Выдача линз";
        const cachedViewMode = getCachedInfo("viewModeIssues");
        if (cachedViewMode) dispatch(setViewMode(cachedViewMode));
    }, [dispatch]);

    useEffect(() => {
        if (isIssuesError) {
            notification.error({
                message: "Ошибка загрузки выдач",
                description: issuesError?.data?.detail || "Не удалось загрузить выдачи линз",
                placement: "topRight",
            });
        }
        if (isPatientsError) {
            notification.error({
                message: "Ошибка загрузки пациентов",
                description: "Не удалось загрузить список пациентов",
                placement: "topRight",
            });
        }
        if (isLensesError) {
            notification.error({
                message: "Ошибка загрузки линз",
                description: "Не удалось загрузить список линз",
                placement: "topRight",
            });
        }
    }, [isIssuesError, isPatientsError, isLensesError, issuesError]);

    const startFilterDateConverted = startFilterDate ? dayjs(startFilterDate) : null;
    const endFilterDateConverted = endFilterDate ? dayjs(endFilterDate) : null;
    const filterDates = [startFilterDateConverted, endFilterDateConverted];
    const isFilterDates = startFilterDate && endFilterDate;

    const containerStyle = {padding: 20};
    const filterBarStyle = {marginBottom: 20};
    const formItemStyle = {width: "100%"};
    const viewModIconStyle = {marginRight: 8};
    const advancedSearchCardStyle = {
        marginBottom: 20,
        boxShadow: "0 1px 6px rgba(0, 0, 0, 0.15)",
        borderRadius: 8
    };

    const handleSetTempSearchText = (value) => {
        setTempSearchText(value);
        dispatch(setCurrentPage(1)); // Сбрасываем на первую страницу
        refetch(); // Обновляем данные при изменении поиска
    };

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

    const handleSetViewMode = (mode) => dispatch(setViewMode(mode));
    const handleSetCurrentPage = (page) => {
        dispatch(setCurrentPage(page));
    };

    const handleSetPageSize = (size) => {
        dispatch(setPageSize(size));
    };
    const handleCloseModal = () => dispatch(closeModal());
    const handleSelectIssue = (issue) => dispatch(selectIssue(issue));
    const resetSelectedIssue = () => dispatch(selectIssue(null));

    const handleAddIssue = () => {
        dispatch(selectIssue(null));
        dispatch(openModal());
    };

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

    const handleFilterDateChange = (dates) => {
        if (dates) {
            const [start, end] = dates;
            dispatch(setStartFilterDate(start.toISOString()));
            dispatch(setEndFilterDate(end.toISOString()));
            dispatch(setCurrentPage(1));
            refetch();
        }
    };

    const handleResetFilterDate = () => {
        dispatch(setStartFilterDate(null));
        dispatch(setEndFilterDate(null));
        dispatch(setCurrentPage(1));
        refetch();
    };

    const pagination = {
        current: currentPage,
        pageSize,
        total: issuesData.total_count,
        showSizeChanger: true,
        pageSizeOptions: ["5", "10", "20", "50"],
        onChange: handlePaginationChange,
        onShowSizeChange: handlePaginationChange,
    };

    const handleSubmitFormModal = async (issueDate, patientId, lensId) => {
        dispatch(closeModal());
        try {
            const formattedIssueDate = dayjs(issueDate).format('YYYY-MM-DD');
            await addIssue({issue_date: formattedIssueDate, patient_id: patientId, lens_id: lensId}).unwrap();
            notification.success({
                message: "Линза выдана",
                description: "Линза успешно выдана пациенту.",
                placement: "topRight",
            });
            refetch();
        } catch (error) {
            console.error('Add lens issue error:', error);
            notification.error({
                message: "Ошибка выдачи линзы",
                description: error?.data?.detail || "Не удалось выдать линзу пациенту.",
                placement: "topRight",
            });
        }
    };

    return {
        issues: issuesData.issues,
        total_count: issuesData.total_count,
        patients,
        lenses,
        isLoading,
        isError,
        isProcessing: isAdding,
        tempSearchText, // Возвращаем только tempSearchText
        selectedIssue,
        isModalVisible,
        viewMode,
        currentPage,
        pageSize,
        filterDates,
        isFilterDates,
        containerStyle,
        filterBarStyle,
        formItemStyle,
        viewModIconStyle,
        advancedSearchCardStyle,
        pagination,
        handleAddIssue,
        handlePaginationChange,
        handleSetTempSearchText,
        handleClearSearch,
        handleSetViewMode,
        handleCloseModal,
        handleFilterDateChange,
        resetSelectedIssue,
        handleSelectIssue,
        handleResetFilterDate,
        handleSubmitFormModal,
    };
};

export default useIssues;