import { Badge, Button, FloatButton, List, Result, Row, Space, Tag, Typography } from "antd";
import { Splitter } from "antd";
import {
    CalendarOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    PlusOutlined,
    ClockCircleOutlined,
} from "@ant-design/icons";
import AppointmentsCalendarTab from "./Components/AppointmentCalendarTab/AppointmentsCalendarTab.jsx";
import useAppointments from "./useAppointments.js";
import dayjs from 'dayjs';
import LoadingIndicator from "../../Widgets/LoadingIndicator/LoadingIndicator.jsx";
import AppointmentFormModal from "../../Dummies/AppointmentFormModal/AppointmentFormModal.jsx";
import AppointmentViewModal from "../../Dummies/AppointmentViewModal/AppointmentViewModal.jsx";
import ScheduledAppointmentFormModal from "../../Dummies/ScheduledAppintmentFormModal/ScheduledAppointmentFormModal.jsx";
import ScheduledAppointmentsViewModal from "../../Widgets/ScheduledAppointmentsViewModal/ScheduledAppointmentsViewModal.jsx";
import AppointmentsListModal from "./Components/AppointmentsListModal/AppointmentsListModal.jsx";

const AppointmentsPage = () => {
    const {
        patients, // Добавляем
        appointments, // Добавляем
        scheduledAppointments, // Добавляем
        isLoading,
        isError,
        collapsed,
        siderWidth,
        showSplitterPanel,
        siderButtonText,
        splitterStyle,
        splitterContentPanelStyle,
        splitterSiderPanelStyle,
        siderTitleStyle,
        siderButtonContainerStyle,
        siderButtonStyle,
        badgeTextStyle,
        upcomingEvents,
        handleToggleSider,
        handleHoverSider,
        handleLeaveSider,
        handleSetSiderWidth,
        openCreateScheduledAppointmentModal,
        currentMonth,
        handleMonthChange,
        handleEventClick,
        openCreateAppointmentModal,
    } = useAppointments();

    if (isError) return (
        <Result
            status="error"
            title="Ошибка"
            subTitle="Произошла ошибка в работе страницы"
        />
    );

    return (
        <>
            <Typography.Title level={1}><CalendarOutlined /> Приемы</Typography.Title>
            {isLoading ? (
                <LoadingIndicator />
            ) : (
                <>
                    <Row justify="end" style={{ marginBottom: 10, marginRight: "2.4rem" }}>
                        <Space direction={"vertical"}>
                            <Tag color={"blue"} style={{ width: "100%" }}>
                                <Badge status={"processing"}
                                       text={<span style={badgeTextStyle}>Запланированный прием</span>} />
                            </Tag>
                            <Tag color={"green"} style={{ width: "100%" }}>
                                <Badge status={"success"}
                                       text={<span style={badgeTextStyle}>Прошедший прием</span>} />
                            </Tag>
                        </Space>
                    </Row>
                    <Splitter
                        style={splitterStyle}
                        min={200}
                        max={400}
                        initial={siderWidth}
                        onChange={handleSetSiderWidth}
                    >
                        <Splitter.Panel
                            style={splitterContentPanelStyle}
                            defaultSize="80%"
                            min="25%"
                            max="90%"
                        >
                            <AppointmentsCalendarTab
                                currentMonth={currentMonth}
                                onMonthChange={handleMonthChange}
                                appointments={appointments} // Добавляем
                                scheduledAppointments={scheduledAppointments} // Добавляем
                            />
                        </Splitter.Panel>
                        {showSplitterPanel && (
                            <Splitter.Panel
                                style={splitterSiderPanelStyle}
                                defaultSize="20%"
                                min="20%"
                                max="75%"
                            >
                                <Typography.Title level={3} style={siderTitleStyle}>
                                    Предстоящие события
                                </Typography.Title>
                                {upcomingEvents.length ? (
                                    <List
                                        dataSource={upcomingEvents.sort((a, b) =>
                                            dayjs(a.appointment_datetime || a.scheduled_datetime).diff(
                                                dayjs(b.appointment_datetime || b.scheduled_datetime)
                                            ))}
                                        renderItem={(item) => (
                                            <List.Item
                                                onClick={() => handleEventClick(item)}
                                                style={{
                                                    padding: "12px",
                                                    marginBottom: "8px",
                                                    borderRadius: "4px",
                                                    background: item.appointment_datetime ? "#f6ffed" : "#e6f7ff",
                                                    cursor: "pointer",
                                                    transition: "background 0.3s",
                                                }}
                                                onMouseEnter={(e) => (e.currentTarget.style.background = item.appointment_datetime ? "#efffdb" : "#d9efff")}
                                                onMouseLeave={(e) => (e.currentTarget.style.background = item.appointment_datetime ? "#f6ffed" : "#e6f7ff")}
                                            >
                                                <Space direction="vertical" size={2}>
                                                    <Space>
                                                        {item.appointment_datetime ? (
                                                            <ClockCircleOutlined style={{ color: "#52c41a" }} />
                                                        ) : (
                                                            <CalendarOutlined style={{ color: "#1890ff" }} />
                                                        )}
                                                        <Typography.Text strong>
                                                            {dayjs(item.appointment_datetime || item.scheduled_datetime).format('DD.MM.YYYY HH:mm')}
                                                        </Typography.Text>
                                                    </Space>
                                                    <Typography.Text>
                                                        {item.appointment_datetime ? 'Прием' : 'Запланировано'}
                                                        {item.patient ? ` - ${item.patient.last_name} ${item.patient.first_name}` : ''}
                                                    </Typography.Text>
                                                    <Typography.Text type="secondary">
                                                        Тип: {item.type?.title || 'Не указан'}
                                                    </Typography.Text>
                                                    {dayjs(item.appointment_datetime || item.scheduled_datetime).isSame(dayjs(), 'day') && (
                                                        <Typography.Text type="warning">Сегодня</Typography.Text>
                                                    )}
                                                </Space>
                                            </List.Item>
                                        )}
                                    />
                                ) : (
                                    <Typography.Text type="secondary">Нет предстоящих событий</Typography.Text>
                                )}
                            </Splitter.Panel>
                        )}
                    </Splitter>
                    <div
                        style={siderButtonContainerStyle}
                        onMouseEnter={handleHoverSider}
                        onMouseLeave={handleLeaveSider}
                    >
                        <Button
                            type="primary"
                            onClick={handleToggleSider}
                            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                            style={siderButtonStyle}
                        >
                            {siderButtonText}
                        </Button>
                    </div>
                    <FloatButton.Group
                        placement={"left"}
                        trigger="hover"
                        type="primary"
                        icon={<PlusOutlined />}
                        tooltip="Создать"
                    >
                        <FloatButton
                            icon={<PlusOutlined />}
                            onClick={openCreateAppointmentModal}
                            tooltip="Прием"
                        />
                        <FloatButton
                            icon={<CalendarOutlined />}
                            onClick={openCreateScheduledAppointmentModal}
                            tooltip="Запланированный прием"
                        />
                    </FloatButton.Group>

                    <AppointmentFormModal />
                    <AppointmentViewModal />
                    <ScheduledAppointmentFormModal />
                    <ScheduledAppointmentsViewModal />
                    <AppointmentsListModal />
                </>
            )}
        </>
    );
};

export default AppointmentsPage;
