import {Button, Card, Col, List, Row, Space, Statistic, Typography, Result} from "antd";
import {
    HomeOutlined,
    PlusOutlined,
    CalendarOutlined,
    UserAddOutlined,
} from "@ant-design/icons";
import useHomePage from "./useHomePage.js";
import useHomePageUI from "./useHomePageUI.js";
import dayjs from "dayjs";
import LoadingIndicator from "../../Widgets/LoadingIndicator/LoadingIndicator.jsx";
import {Bar} from "react-chartjs-2";
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    BarElement,
    Title,
    Tooltip,
    Legend,
} from "chart.js";
import AppointmentFormModal from "../../Dummies/AppointmentFormModal/AppointmentFormModal.jsx";
import ScheduledAppointmentFormModal
    from "../../Dummies/ScheduledAppintmentFormModal/ScheduledAppointmentFormModal.jsx";
import AppointmentViewModal from "../../Widgets/AppointmentViewModal/AppointmentViewModal.jsx";
import ScheduledAppointmentsViewModal
    from "../../Widgets/ScheduledAppointmentsViewModal/ScheduledAppointmentsViewModal.jsx";
import PatientFormModal from "../../Dummies/PatientFormModal/PatientFormModal.jsx";

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);

const HomePage = () => {
    const homePageData = useHomePage();
    const homePageUI = useHomePageUI(homePageData.appointments, homePageData.scheduledAppointments, homePageData.patients);
    // const selectedScheduledAppointment = useSelector((state) => state.appointmentsUI.selectedScheduledAppointment);

    if (homePageData.isError) {
        return (
            <Result
                status="error"
                title="Ошибка"
                subTitle="Произошла ошибка при загрузке данных"
            />
        );
    }

    return (
        <div style={homePageUI.containerStyle}>
            {homePageData.isLoading ? (
                <LoadingIndicator/>
            ) : (
                <>
                    <Typography.Title level={1}>
                        <HomeOutlined/> Главная страница
                    </Typography.Title>

                    <div style={homePageUI.sectionStyle}>
                        <Space direction={homePageUI.isMobile ? "vertical" : "horizontal"} size="middle"
                               style={{width: "100%"}}>
                            <Button
                                type="primary"
                                icon={<PlusOutlined/>}
                                onClick={homePageData.handleCreateAppointment}
                                style={homePageUI.buttonStyle}
                            >
                                Новый прием
                            </Button>
                            <Button
                                type="primary"
                                icon={<CalendarOutlined/>}
                                onClick={homePageData.handleCreateScheduledAppointment}
                                style={homePageUI.buttonStyle}
                            >
                                Запланировать
                            </Button>
                            <Button
                                type="primary"
                                icon={<UserAddOutlined/>}
                                onClick={homePageData.handleCreatePatient}
                                style={homePageUI.buttonStyle}
                            >
                                Добавить пациента
                            </Button>
                        </Space>
                    </div>

                    <Row gutter={[16, 16]} style={homePageUI.sectionStyle}>
                        <Col span={homePageUI.isMobile ? 24 : 8}>
                            <Card style={homePageUI.cardStyle}>
                                <Statistic title="Пациенты" value={homePageData.patients.length}/>
                            </Card>
                        </Col>
                        <Col span={homePageUI.isMobile ? 24 : 8}>
                            <Card style={homePageUI.cardStyle}>
                                <Statistic
                                    title="Приемы за месяц"
                                    value={
                                        homePageData.appointments.filter((a) => dayjs(a.appointment_datetime).isSame(dayjs(), "month")).length
                                    }
                                />
                            </Card>
                        </Col>
                        <Col span={homePageUI.isMobile ? 24 : 8}>
                            <Card style={homePageUI.cardStyle}>
                                <Statistic title="Запланировано" value={homePageData.scheduledAppointments.length}/>
                            </Card>
                        </Col>
                    </Row>

                    <Card
                        title={`События на сегодня (${dayjs().format("DD.MM.YYYY")})`}
                        style={homePageUI.sectionStyle}
                    >
                        <List
                            dataSource={homePageUI.todayEvents}
                            renderItem={(item) => (
                                <List.Item
                                    onClick={() => homePageData.handleEventClick(item)}
                                    style={homePageUI.listItemStyle}
                                >
                                    <Space>
                                        <Typography.Text strong>
                                            {dayjs(item.appointment_datetime || item.scheduled_datetime).format("HH:mm")}
                                        </Typography.Text>
                                        <Typography.Text>
                                            {item.patient ? `${item.patient.last_name} ${item.patient.first_name}` : "Без пациента"} -{" "}
                                            {item.type?.title || "Не указан"}
                                        </Typography.Text>
                                    </Space>
                                </List.Item>
                            )}
                        />
                        {homePageUI.todayEvents.length === 0 && (
                            <Typography.Text type="secondary">Нет событий на сегодня</Typography.Text>
                        )}
                    </Card>

                    <Card title="Статистика приемов" style={homePageUI.sectionStyle}>
                        <div style={{...homePageUI.chartContainerStyle, height: 300}}>
                            <Bar data={homePageUI.chartData} options={homePageUI.chartOptions}/>
                        </div>
                    </Card>

                    <PatientFormModal/>
                    <AppointmentFormModal/>
                    <AppointmentViewModal/>
                    <ScheduledAppointmentFormModal/>
                    <ScheduledAppointmentsViewModal/>
                </>
            )}
        </div>
    );
};

export default HomePage;