import {
    Table,
    Input,
    Row,
    Col,
    DatePicker,
    Tooltip,
    Button,
    FloatButton,
    Typography,
    Timeline,
    Grid,
    Pagination, Result
} from "antd";
import {DatabaseOutlined, PlusOutlined, UnorderedListOutlined} from "@ant-design/icons";
import LensIssueViewModal from "./Components/LensIssueViewModal/LensIssueViewModal.jsx";
import dayjs from "dayjs";
import LensIssueFormModal from "./Components/LensIssueFormModal/LensIssueFormModal.jsx";
import SelectViewMode from "../../Widgets/SelectViewMode/SelectViewMode.jsx";
import LoadingIndicator from "../../Widgets/LoadingIndicator/LoadingIndicator.jsx";
import useIssues from "./useIssues.js";
import useIssuesUI from "./useIssuesUI.js";

const {Title} = Typography;
const {useBreakpoint} = Grid;

const IssuesPage = () => {
    const issuesData = useIssues();
    const issuesUI = useIssuesUI(issuesData.issues);

    const screens = useBreakpoint();

    const viewModes = [
        {
            value: "table",
            label: "Таблица",
            icon: <DatabaseOutlined style={issuesUI.viewModIconStyle}/>,
        },
        {
            value: "timeline",
            label: "Лента",
            icon: <UnorderedListOutlined style={issuesUI.viewModIconStyle}/>,
        },
    ];

    const columns = [
        {
            title: "Дата выдачи",
            dataIndex: "issue_date",
            key: "issue_date",
            render: (text) => new Date(text).toLocaleDateString(),
            sorter: (a, b) => new Date(b.issue_date) - new Date(a.issue_date),
        },
        {
            title: "Пациент",
            dataIndex: "patient",
            key: "patient",
            render: (patient) => `${patient.last_name} ${patient.first_name}`,
        },
        {
            title: "Выдал",
            dataIndex: "doctor",
            key: "doctor",
            render: (doctor) => `${doctor.last_name} ${doctor.first_name}`,
        },
        {
            title: "Линза",
            dataIndex: "lens",
            key: "lens",
            render: (lens) => `Сторона: ${lens.side}, Диаметр: ${lens.diameter}`,
        },
        {
            title: "Действия",
            key: "actions",
            render: (_, issue) => (
                <Button type={"link"} onClick={() => issuesUI.handleSelectIssue(issue)}>Подробнее</Button>
            ),
        },
    ];

    const TableView = () => (
        <Table
            columns={columns}
            dataSource={issuesUI.filteredIssues}
            rowKey="id"
            pagination={issuesUI.pagination}
            showSorterTooltip={false}
        />
    );

    const timeLineItems = issuesUI.filteredIssues.map(issue => ({
        label: dayjs(issue.issue_date).format("DD.MM.YYYY"),
        children: (
            <Row
                gutter={[16, 16]}
                align={"middle"}
            >
                <Col xs={24} md={24} sm={24} xl={13}>
                    <p style={{textAlign: "right"}}>Пациент: {issue.patient.last_name} {issue.patient.first_name}</p>
                </Col>
                <Col xs={24} md={24} sm={24} xl={5}>
                    <p style={{textAlign: "right"}}>Линза: {issue.lens.side} {issue.lens.diameter}</p>
                </Col>
                <Col xs={24} md={24} sm={24} xl={6}>
                    <Button
                        type={"dashed"}
                        onClick={() => issuesUI.handleSelectIssue(issue)}
                        style={{marginRight: 40}}
                    >
                        Подробнее
                    </Button>
                </Col>
            </Row>
        ),
    }));

    const TimeLineView = () => {
        const paginatedItems = timeLineItems.slice(
            (issuesUI.currentPage - 1) * issuesUI.pageSize,
            issuesUI.currentPage * issuesUI.pageSize
        );

        return (
            <>
                <Timeline
                    items={paginatedItems}
                    mode={screens.xs ? "left" : "right"}
                />
                <Row
                    style={{textAlign: "center", marginTop: 20}}
                    align={"middle"}
                    justify={"end"}
                >
                    <Pagination
                        current={issuesUI.currentPage}
                        pageSize={issuesUI.pageSize}
                        total={timeLineItems.length}
                        onChange={issuesUI.handlePaginationChange}
                        showSizeChanger={true}
                        pageSizeOptions={["5", "10", "20", "50"]}
                    />
                </Row>
            </>
        );
    };

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

    return (
        <div style={issuesUI.containerStyle}>
            <Title level={1}><DatabaseOutlined/> Выдача линз</Title>
            <Row gutter={[16, 16]} style={issuesUI.filterBarStyle}>
                <Col xs={24} md={24} sm={24} xl={12}>
                    <Input
                        placeholder="Поиск по пациенту или врачу"
                        onChange={(e) => issuesUI.handleSetSearchText(e.target.value)}
                        style={issuesUI.formItemStyle}
                        allowClear
                    />
                </Col>

                <Col xs={24} md={
                    issuesUI.isFilterDates ? 12 : 16
                } sm={
                    16
                } xl={
                    issuesUI.isFilterDates ? 6 : 8
                }>
                    <Tooltip
                        title="Фильтр по дате выдачи линзы"
                    >
                        <DatePicker.RangePicker
                            allowClear={false}
                            style={issuesUI.formItemStyle}
                            placeholder={["Дата начала", "Дата окончания"]}
                            format="DD.MM.YYYY"
                            value={issuesUI.isFilterDates && issuesUI.filterDates}
                            onChange={issuesUI.handleFilterDateChange}
                        />
                    </Tooltip>
                </Col>
                {issuesUI.isFilterDates && (
                    <Col xs={24} md={4} sm={8} xl={2}>
                        <Tooltip
                            title="Cбросить фильтр"
                        >
                            <Button
                                onClick={issuesUI.handleResetFilterDate}
                                type={"primary"}
                                block
                            >
                                Сбросить
                            </Button>
                        </Tooltip>
                    </Col>
                )}
                <Col xs={24}
                     md={issuesUI.isFilterDates ? 8 : 8}
                     sm={issuesUI.isFilterDates ? 24 : 8}
                     xl={4}>
                    <SelectViewMode
                        viewMode={issuesUI.viewMode}
                        setViewMode={issuesUI.handleSetViewMode}
                        localStorageKey={"viewModeIssues"}
                        toolTipText={"Формат отображения выдач линз"}
                        viewModes={viewModes}
                    />
                </Col>
            </Row>
            {issuesData.isLoading ? (
                <LoadingIndicator/>
            ) : issuesUI.viewMode === "table" ? (
                <TableView/>
            ) : (
                <TimeLineView/>
            )}

            <FloatButton
                icon={<PlusOutlined/>}
                type={"primary"}
                onClick={issuesUI.handleAddIssue}
                tooltip={"Добавить выдачу линзы"}
            />

            <LensIssueFormModal
                visible={issuesUI.isModalVisible}
                onCancel={issuesUI.handleCloseModal}
                onSubmit={issuesData.handleSubmitFormModal}
            />

            <LensIssueViewModal
                visible={issuesUI.selectedIssue !== null}
                onCancel={issuesUI.resetSelectedIssue}
                lensIssue={issuesUI.selectedIssue}
            />
        </div>
    );
};

export default IssuesPage;
