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 {useMemo} from "react";

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

const IssuesPage = () => {
    const issuesData = useIssues();
    const screens = useBreakpoint();

    const viewModes = [
        {
            value: "table",
            label: "Таблица",
            icon: <DatabaseOutlined style={issuesData.viewModIconStyle}/>,
        },
        {
            value: "timeline",
            label: "Лента",
            icon: <UnorderedListOutlined style={issuesData.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={() => issuesData.handleSelectIssue(issue)}>Подробнее</Button>
            ),
        },
    ];

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

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

        return (
            <>
                <Timeline
                    items={timeLineItems}
                    mode={screens.xs ? "left" : "right"}
                />
                <Row
                    style={{textAlign: "center", marginTop: 20}}
                    align="middle"
                    justify="end"
                >
                    <Pagination
                        {...issuesData.pagination}
                    />
                </Row>
            </>
        );
    };
    
    if (issuesData.isError) return (
        <Result
            status="error"
            title="Ошибка"
            subTitle="Произошла ошибка в работе страницы"
        />
    );

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

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

            <LensIssueFormModal
                visible={issuesData.isModalVisible}
                onCancel={issuesData.handleCloseModal}
                onSubmit={issuesData.handleSubmitFormModal}
                isProcessing={issuesData.isProcessing}
                patients={issuesData.patients}
                lenses={issuesData.lenses}
            />

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

export default IssuesPage;