import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { notification } from "antd";
import {
    useAddLensMutation,
    useDeleteLensMutation,
    useGetLensesQuery,
    useUpdateLensMutation
} from "../../../../../Api/lensesApi.js";
import {
    closeModal,
    openModal,
    selectLens,
    setCurrentPage,
    setPageSize,
    setSearchParams,
    setSearchText,
    setShowAdvancedSearch,
    setViewMode,
    setSortOrder
} from "../../../../../Redux/Slices/lensesSlice.js";
import { getCachedInfo } from "../../../../../Utils/cachedInfoUtils.js";

const useLenses = () => {
    const dispatch = useDispatch();
    const {
        viewMode,
        currentPage,
        pageSize,
        selectedLens,
        isModalVisible,
        showAdvancedSearch,
        searchParams,
        sortOrder,
    } = useSelector(state => state.lensesUI);

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

    const { data = { lenses: [], total_count: 0 }, isLoading, isError, error } = useGetLensesQuery(
        {
            page: currentPage,
            pageSize,
            search: tempSearchText  || undefined,
            sortOrder,
            searchParams,
        },
        {
            pollingInterval: 20000,
            refetchOnMountOrArgChange: true,
        }
    );

    useEffect(() => {
        if (isError) {
            console.error('useGetLensesQuery error:', error);
            notification.error({
                message: "Ошибка загрузки данных",
                description: error?.data?.detail || "Не удалось загрузить линзы",
                placement: "topRight",
            });
        }
    }, [isError, error]);

    const [addLens, { isLoading: isAdding }] = useAddLensMutation();
    const [updateLens, { isLoading: isUpdating }] = useUpdateLensMutation();
    const [deleteLens, { isLoading: isDeleting }] = useDeleteLensMutation();

    useEffect(() => {
        document.title = "Линзы";
        const cachedViewMode = getCachedInfo("viewModeLenses");
        if (cachedViewMode) dispatch(setViewMode(cachedViewMode));
    }, [dispatch]);

    const containerStyle = { padding: 20 };
    const filterBarStyle = { marginBottom: 20 };
    const formItemStyle = { width: "100%" };
    const viewModIconStyle = { marginRight: 8 };
    const tableActionButtonsStyle = { display: "flex", gap: "8px" };
    const advancedSearchCardStyle = { marginBottom: 20 };

    const handleSetTempSearchText = (value) => {
        setTempSearchText(value);
    };

    const handleSearch = () => {
        dispatch(setSearchText(tempSearchText));
        dispatch(setCurrentPage(1));
    };

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

    const handleSetSortOrder = (value) => {
        dispatch(setSortOrder(value));
        dispatch(setCurrentPage(1));
    };

    const handleCloseModal = () => dispatch(closeModal());

    const handleSetCurrentPage = (page) => dispatch(setCurrentPage(page));
    const handleSetPageSize = (size) => dispatch(setPageSize(size));
    const handleSetViewMode = (mode) => dispatch(setViewMode(mode));

    const handleAddLens = () => {
        dispatch(selectLens(null));
        dispatch(openModal());
    };

    const handleEditLens = (lens) => {
        dispatch(selectLens(lens));
        dispatch(openModal());
    };

    const handleParamChange = (param, value) => {
        if (typeof param === "object") {
            dispatch(setSearchParams(param));
        } else {
            dispatch(setSearchParams({ ...searchParams, [param]: value }));
        }
        dispatch(setCurrentPage(1));
    };

    const toggleAdvancedSearch = () => {
        dispatch(setShowAdvancedSearch(!showAdvancedSearch));
    };

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

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

    const handleModalSubmit = async (lensData) => {
        dispatch(closeModal());
        try {
            if (selectedLens) {
                await updateLens({ id: selectedLens.id, ...lensData }).unwrap();
                notification.success({
                    message: "Линза обновлена",
                    description: "Линза успешно обновлена.",
                    placement: "topRight",
                });
            } else {
                await addLens(lensData).unwrap();
                notification.success({
                    message: "Линза добавлена",
                    description: "Линза успешно добавлена.",
                    placement: "topRight",
                });
            }
        } catch (error) {
            notification.error({
                message: "Ошибка",
                description: error?.data?.detail || "Произошла ошибка при сохранении",
                placement: "topRight",
            });
        }
    };

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

    return {
        lenses: data.lenses || [],
        filteredLenses: (data.lenses || []).map(lens => ({ ...lens, key: lens.id })),
        isLoading,
        isError,
        isProcessing: isAdding || isUpdating || isDeleting,
        tempSearchText,
        viewMode,
        currentPage,
        pageSize,
        selectedLens,
        isModalVisible,
        showAdvancedSearch,
        searchParams,
        sortOrder,
        pagination,
        containerStyle,
        filterBarStyle,
        formItemStyle,
        viewModIconStyle,
        tableActionButtonsStyle,
        advancedSearchCardStyle,
        handleSetTempSearchText,
        handleSearch,
        handleClearSearch,
        handleSetSortOrder,
        handleAddLens,
        handleEditLens,
        handleCloseModal,
        handleDeleteLens,
        handleModalSubmit,
        handleParamChange,
        toggleAdvancedSearch,
        handleSetViewMode,
    };
};

export default useLenses;