import {
    Input,
    Select,
    List,
    FloatButton,
    Row,
    Col,
    Table,
    Button,
    Popconfirm,
    Typography,
    Result, Tooltip
} from "antd";
import {
    BuildOutlined,
    PlusOutlined,
    SortAscendingOutlined,
    SortDescendingOutlined, TableOutlined,
    TeamOutlined
} from "@ant-design/icons";
import PatientListCard from "../../Dummies/PatientListCard.jsx";
import PatientFormModal from "../../Dummies/PatientFormModal/PatientFormModal.jsx";
import SelectViewMode from "../../Widgets/SelectViewMode/SelectViewMode.jsx";
import LoadingIndicator from "../../Widgets/LoadingIndicator/LoadingIndicator.jsx";
import usePatients from "./usePatients.js";
import usePatientsUI from "./usePatientsUI.js";

const {Option} = Select;
const {Title} = Typography;

const PatientsPage = () => {
    const patientsData = usePatients();
    const patientsUI = usePatientsUI(patientsData.patients);

    const columns = [
        {
            title: "Фамилия",
            dataIndex: "last_name",
            key: "last_name",
            sorter: (a, b) => a.last_name.localeCompare(b.last_name),
            sortDirections: ["ascend", "descend"],
        },
        {
            title: "Имя",
            dataIndex: "first_name",
            key: "first_name",
            sorter: (a, b) => a.first_name.localeCompare(b.first_name),
            sortDirections: ["ascend", "descend"],
        },
        {
            title: "Отчество",
            dataIndex: "patronymic",
            key: "patronymic",
            sortDirections: ["ascend", "descend"],
        },
        {
            title: "Дата рождения",
            dataIndex: "birthday",
            sorter: (a, b) => new Date(a.birthday).getTime() - new Date(b.birthday).getTime(),
            sortDirections: ["ascend", "descend"],
            render: patientsUI.formatDate,
        },
        {
            title: "Телефон",
            dataIndex: "phone",
        },
        {
            title: "Email",
            dataIndex: "email",
        },
        {
            title: "Действия",
            fixed: 'right',
            render: (_, record) => (
                <Row gutter={[8, 8]}>
                    <Col xs={24} xl={12}>
                        <Button block onClick={() => patientsUI.handleEditPatient(record)}>Изменить</Button>
                    </Col>

                    <Col xs={24} xl={12}>
                        <Popconfirm
                            title="Вы уверены, что хотите удалить пациента?"
                            onConfirm={() => patientsData.handleDeletePatient(record.id)}
                            okText="Да, удалить"
                            cancelText="Отмена"
                        >
                            <Button danger block>Удалить</Button>
                        </Popconfirm>
                    </Col>
                </Row>
            ),
        },
    ];

    const viewModes = [
        {
            value: "tile",
            label: "Плитка",
            icon: <BuildOutlined style={patientsUI.viewModIconStyle}/>
        },
        {
            value: "table",
            label: "Таблица",
            icon: <TableOutlined style={patientsUI.viewModIconStyle}/>
        }
    ];

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

    return (
        <div style={patientsUI.containerStyle}>
            <Title level={1}><TeamOutlined/> Пациенты</Title>
            <Row gutter={[16, 16]} style={patientsUI.filterBarStyle}>
                <Col xs={24} md={14} sm={10} xl={18} xxl={19}>
                    <Input
                        placeholder="Поиск пациента"
                        value={patientsUI.searchText}
                        onChange={(e) => patientsUI.handleSetSearchText(e.target.value)}
                        style={patientsUI.formItemStyle}
                        allowClear
                    />
                </Col>

                {patientsUI.viewMode === "tile" && (
                    <Col xs={24} md={5} sm={6} xl={3} xxl={2}>
                        <Tooltip title={"Сортировка пациентов"}>
                            <Select
                                value={patientsUI.sortOrder}
                                onChange={patientsUI.handleSetSortOrder}
                                style={patientsUI.formItemStyle}
                            >
                                <Option value="asc"><SortAscendingOutlined/> А-Я</Option>
                                <Option value="desc"><SortDescendingOutlined/> Я-А</Option>
                            </Select>
                        </Tooltip>
                    </Col>
                )}

                <Col xs={24} md={patientsUI.viewMode === "tile" ? 5 : 10}
                     sm={patientsUI.viewMode === "tile" ? 8 : 14}
                     xl={patientsUI.viewMode === "tile" ? 3 : 5}
                     xxl={patientsUI.viewMode === "tile" ? 3 : 5}>
                    <SelectViewMode
                        viewMode={patientsUI.viewMode}
                        setViewMode={patientsUI.handleSetViewMode}
                        localStorageKey={"viewModePatients"}
                        toolTipText={"Формат отображения пациентов"}
                        viewModes={viewModes}
                    />
                </Col>
            </Row>

            {patientsData.isLoading ? <LoadingIndicator/> : patientsUI.viewMode === "tile" ? (
                <List
                    grid={{gutter: 16, column: 3}}
                    dataSource={patientsUI.filteredPatients}
                    renderItem={patient => (
                        <List.Item>
                            <PatientListCard
                                patient={patient}
                                handleEditPatient={patientsUI.handleEditPatient}
                                handleDeletePatient={patientsData.handleDeletePatient}
                            />
                        </List.Item>
                    )}
                    pagination={patientsUI.pagination}
                />
            ) : (
                <Table
                    columns={columns}
                    dataSource={patientsUI.filteredPatients}
                    pagination={patientsUI.pagination}
                />
            )}

            <FloatButton
                icon={<PlusOutlined/>}
                type="primary"
                onClick={patientsUI.handleAddPatient}
                tooltip="Добавить пациента"
            />

            <PatientFormModal/>
        </div>
    );
};

export default PatientsPage;