import { useDispatch, useSelector } from "react-redux";
import { setSelectedScheduledAppointment, openModalWithScheduledData } from "../../../Redux/Slices/appointmentsSlice.js";
import { notification } from "antd";
import dayjs from "dayjs";

const useScheduledAppointmentsViewModalUI = (cancelAppointment) => {
    const dispatch = useDispatch();
    const { selectedScheduledAppointment } = useSelector((state) => state.appointmentsUI);

    const modalWidth = 700;
    const blockStyle = { marginBottom: 16 };
    const footerRowStyle = { marginTop: 16, gap: 8 };
    const footerButtonStyle = { marginRight: 8 };

    const labels = {
        title: "Просмотр запланированного приема",
        patient: "Пациент:",
        birthday: "Дата рождения:",
        email: "Email:",
        phone: "Телефон:",
        type: "Тип приема:",
        appointmentTime: "Время приема:",
        closeButton: "Закрыть",
        convertButton: "Конвертировать в прием",
        cancelButton: "Отмена приема",
        popconfirmTitle: "Вы уверены, что хотите отменить прием?",
        popconfirmOk: "Да, отменить",
        popconfirmCancel: "Отмена",
        notSpecified: "Не указан",
    };

    const visible = !!selectedScheduledAppointment;

    const getDateString = (date) => {
        return date ? dayjs(date).format("DD.MM.YYYY") : labels.notSpecified;
    };

    const getAppointmentTime = (datetime) => {
        return datetime
            ? dayjs(datetime).format("DD.MM.YYYY HH:mm")
            : labels.notSpecified;
    };

    const getPatientName = (patient) => {
        return patient
            ? `${patient.last_name} ${patient.first_name}`
            : labels.notSpecified;
    };

    const getPatientField = (field) => {
        return field || labels.notSpecified;
    };

    const onCancel = () => {
        dispatch(setSelectedScheduledAppointment(null));
    };

    const cancelScheduledAppointment = async () => {
        try {
            await cancelAppointment(selectedScheduledAppointment.id);
            notification.success({
                message: "Прием отменен",
                placement: "topRight",
                description: "Прием успешно отменен.",
            });
            onCancel();
        } catch (error) {
            notification.error({
                message: "Ошибка",
                description: error.data?.message || "Не удалось отменить прием.",
                placement: "topRight",
            });
        }
    };

    const handleConvertToAppointment = () => {
        if (selectedScheduledAppointment) {
            dispatch(
                openModalWithScheduledData({
                    id: selectedScheduledAppointment.id,
                    patient_id: selectedScheduledAppointment.patient?.id,
                    type_id: selectedScheduledAppointment.type?.id,
                    appointment_datetime: selectedScheduledAppointment.scheduled_datetime,
                })
            );
        }
    };

    return {
        selectedScheduledAppointment,
        modalWidth,
        blockStyle,
        footerRowStyle,
        footerButtonStyle,
        labels,
        visible,
        getDateString,
        getAppointmentTime,
        getPatientName,
        getPatientField,
        onCancel,
        cancelScheduledAppointment,
        handleConvertToAppointment,
    };
};

export default useScheduledAppointmentsViewModalUI;