import {useMemo, useState} from "react";
import dayjs from "dayjs";
import {Grid, notification} from "antd";

const {useBreakpoint} = Grid;

const useLensIssueFormUI = (visible, onCancel, onSubmit, patients, lenses) => {
    const screens = useBreakpoint();

    const [searchPatientString, setSearchPatientString] = useState("");
    const [searchLensString, setSearchLensString] = useState("");
    const [issueDate, setIssueDate] = useState(dayjs(new Date()));

    const [selectedPatient, setSelectedPatient] = useState(null);
    const [selectedLens, setSelectedLens] = useState(null);

    const [currentStep, setCurrentStep] = useState(0);

    const blockStepStyle = {padding: "10px", background: "#f5f5f5", borderRadius: 5, marginBottom: 15};
    const searchInputStyle = {marginBottom: 16};
    const chooseContainerStyle = {maxHeight: 300, overflowY: "auto", border: "1px solid #d9d9d9", padding: 8};
    const alertStyle = {marginBottom: 15};
    const issueDateContainerStyle = {display: "flex", alignItems: "center"};
    const datePickerStyle = {width: "100%"};
    const loadingContainerStyle = {display: "flex", justifyContent: "center", alignItems: "center", height: "70vh"};
    const stepsContentStyle = {maxHeight: "70vh", overflowY: "auto", padding: "10px"};
    const stepsIndicatorStyle = {marginTop: 16};
    const footerRowStyle = {marginTop: 20};
    const footerButtonStyle = {marginRight: 8};

    const filteredPatients = useMemo(() => patients.filter((patient) => {
        const searchLower = searchPatientString.toLowerCase();

        return Object.values(patient)
            .filter(value => typeof value === "string")
            .some(value => value.toLowerCase().includes(searchLower));
    }), [patients, searchPatientString]);

    const filteredLenses = useMemo(() => lenses.filter((lens) => {
        const searchLower = searchLensString.toLowerCase();

        return Object.values(lens)
            .some(value => value.toString().toLowerCase().includes(searchLower));
    }), [lenses, searchLensString]);

    const resetPatient = () => setSelectedPatient(null);
    const resetLens = () => setSelectedLens(null);

    const screenXS = useMemo(() => screens.xs, [screens]);
    const direction = useMemo(() => !screenXS ? "horizontal" : "vertical", [screenXS]);
    const modalWidth = useMemo(() => screenXS ? 700 : "90%", [screenXS]);

    const nextButtonText = useMemo(() => {
        if (currentStep === 2) {
            return "Создать";
        } else {
            return "Далее";
        }
    }, [currentStep]);

    const handleSetSearchPatientString = (e) => setSearchPatientString(e.target.value);
    const handleSetSearchLensString = (e) => setSearchLensString(e.target.value);
    const handleSetIssueDate = (date) => setIssueDate(date);

    const handleOk = async () => {
        try {
            setCurrentStep(0);
            onSubmit(issueDate.format("YYYY-MM-DD"), selectedPatient.id, selectedLens.id);
            setSelectedPatient(null);
            setSelectedLens(null);
            setIssueDate(dayjs(new Date()));
        } catch (errorInfo) {
            console.error("Validation Failed:", errorInfo);
            notification.error({
                message: "Ошибка валидации",
                description: "Проверьте правильность заполнения полей.",
                placement: "topRight",
            });
        }
    };

    const isActiveNextButton = useMemo(() => {
        if (currentStep === 0 && !selectedPatient) {
            return false;
        }

        return !(currentStep === 1 && !selectedLens);
    }, [currentStep, selectedPatient, selectedLens]);

    const isActivePrevButton = useMemo(() => {
        return currentStep > 0;
    }, [currentStep]);

    const cancelModal = () => {
        setSelectedPatient(null);
        setSelectedLens(null);
        setCurrentStep(0);
        setIssueDate(dayjs(new Date()));
        onCancel();
    };

    const handleClickBackButton = () => {
        setCurrentStep(currentStep - 1);
    };

    const isActiveFinishButton = useMemo(() => {
        return currentStep === 2;
    }, [currentStep]);

    const handleClickNextButton = async () => {
        if (isActiveFinishButton) {

            if (!validateIssue()) {
                notification.error({
                    message: "Ошибка валидации",
                    description: "Проверьте правильность заполнения полей.",
                    placement: "topRight",
                });
                return;
            }

            await handleOk().then(reset);
        } else {
            setCurrentStep(currentStep + 1);
        }
    };

    const validateIssue = () => {
        return issueDate && selectedPatient && selectedLens;
    };

    const getDateString = (date) => {
        return new Date(date).toLocaleDateString('ru-RU');
    };

    const getSelectedPatientBirthdayString = () => {
        if (!selectedPatient) {
            return "";
        }

        return getDateString(selectedPatient.birthday);
    };

    const reset = () => {
        setSelectedPatient(null);
        setSelectedLens(null);
        setCurrentStep(0);
        setIssueDate(dayjs(new Date()));
    };

    const disableBackButton = useMemo(() => !isActivePrevButton, [isActivePrevButton]);
    const disableNextButton = useMemo(() => !isActiveNextButton && !isActiveFinishButton, [isActiveFinishButton, isActiveNextButton]);

    return {
        filteredPatients,
        filteredLenses,
        searchPatientString,
        searchLensString,
        issueDate,
        selectedPatient,
        setSelectedPatient,
        selectedLens,
        setSelectedLens,
        currentStep,
        disableBackButton,
        disableNextButton,
        nextButtonText,
        blockStepStyle,
        searchInputStyle,
        chooseContainerStyle,
        alertStyle,
        issueDateContainerStyle,
        datePickerStyle,
        loadingContainerStyle,
        stepsContentStyle,
        stepsIndicatorStyle,
        footerRowStyle,
        footerButtonStyle,
        screenXS,
        direction,
        modalWidth,
        handleOk,
        cancelModal,
        handleClickBackButton,
        handleClickNextButton,
        resetPatient,
        resetLens,
        getDateString,
        handleSetSearchPatientString,
        handleSetSearchLensString,
        handleSetIssueDate,
        getSelectedPatientBirthdayString,
    };
};

export default useLensIssueFormUI;