import {
    Input,
    Select,
    List,
    FloatButton,
    Row,
    Col,
    Button,
    Form,
    InputNumber,
    Card,
    Grid,
    Table,
    Popconfirm,
    Typography, Result
} from "antd";
import {
    PlusOutlined,
    DownOutlined,
    UpOutlined,
    FolderViewOutlined,
    TableOutlined,
    BuildOutlined
} from "@ant-design/icons";
import LensCard from "../../../../Dummies/LensListCard.jsx";
import LensFormModal from "./Components/LensFormModal/LensFormModal.jsx";
import SelectViewMode from "../../../../Widgets/SelectViewMode/SelectViewMode.jsx";
import LoadingIndicator from "../../../../Widgets/LoadingIndicator/LoadingIndicator.jsx";
import useLenses from "./useLenses.js";
import useLensesUI from "./useLensesUI.js";

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

const LensesTab = () => {
    const lensesData = useLenses();
    const lensesUI = useLensesUI(lensesData.lenses);

    const screens = useBreakpoint();

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

    const columns = [
        {
            title: "Тор",
            dataIndex: "tor",
            key: "tor",
            sorter: (a, b) => a.tor - b.tor,
        },
        {
            title: "Диаметр",
            dataIndex: "diameter",
            key: "diameter",
            sorter: (a, b) => a.diameter - b.diameter,
        },
        {
            title: "Пресетная рефракция",
            dataIndex: "preset_refraction",
            key: "preset_refraction",
            sorter: (a, b) => a.preset_refraction - b.preset_refraction,
        },
        {
            title: "Периферия торичность",
            dataIndex: "periphery_toricity",
            key: "periphery_toricity",
            sorter: (a, b) => a.periphery_toricity - b.periphery_toricity,
        },
        {
            title: "FVC",
            dataIndex: "fvc",
            key: "fvc",
            sorter: (a, b) => a.fvc - b.fvc,
        },
        {
            title: "Trial",
            dataIndex: "trial",
            key: "trial",
            sorter: (a, b) => a.trial - b.trial,
        },
        {
            title: "Сторона",
            dataIndex: "side",
            key: "side",
            filters: [
                {text: "Левая", value: "левая"},
                {text: "Правая", value: "правая"},
            ],
            onFilter: (value, record) => record.side === value,
        },
        {
            title: "Выдана",
            dataIndex: "issued",
            key: "issued",
            render: (issued) => (issued ? "Да" : "Нет"),
            filters: [
                {text: "Да", value: true},
                {text: "Нет", value: false},
            ],
            onFilter: (value, record) => record.issued === value,
        },
        {
            title: "Действия",
            key: "actions",
            fixed: 'right',
            render: (text, record) => (
                <div style={lensesUI.tableActionButtonsStyle}>
                    <Button onClick={() => lensesUI.handleEditLens(record)}>Изменить</Button>

                    <Popconfirm
                        title="Вы уверены, что хотите удалить линзу?"
                        onConfirm={() => lensesData.handleDeleteLens(record.id)}
                        okText="Да, удалить"
                        cancelText="Отмена"
                    >
                        <Button danger>Удалить</Button>
                    </Popconfirm>
                </div>
            ),
        },
    ];

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

    return (
        <div style={lensesUI.containerStyle}>
            <Title level={1}><FolderViewOutlined/> Линзы</Title>
            <Row gutter={[16, 16]} style={lensesUI.filterBarStyle}>
                <Col xs={24} md={24} sm={24} xl={15}>
                    <Input
                        placeholder="Поиск линзы"
                        value={lensesUI.searchText}
                        onChange={(e) => lensesUI.handleSetSearchText(e.target.value)}
                        style={lensesUI.formItemStyle}
                        allowClear
                    />
                </Col>
                <Col xs={24} md={12} sm={24} xl={5}>
                    <Button
                        onClick={lensesUI.toggleAdvancedSearch}
                        icon={lensesUI.showAdvancedSearch ? <UpOutlined/> : <DownOutlined/>}
                        block
                    >
                        Расширенный поиск
                    </Button>
                </Col>
                <Col xs={24} md={12} sm={24} xl={4}>
                    <SelectViewMode
                        viewMode={lensesUI.viewMode}
                        setViewMode={lensesUI.handleSetViewMode}
                        localStorageKey={"viewModeLenses"}
                        toolTipText={"Формат отображения линз"}
                        viewModes={viewModes}
                    />
                </Col>
            </Row>

            {lensesUI.showAdvancedSearch && (
                <Card
                    title="Расширенный поиск"
                    style={lensesUI.advancedSearchCardStyle}
                >
                    <Row gutter={16}>
                        <Col xs={24} sm={12}>
                            <Form layout="vertical">
                                <Form.Item label="Тор">
                                    <InputNumber
                                        value={lensesUI.searchParams.tor || 0}
                                        onChange={(value) => lensesUI.handleParamChange("tor", value)}
                                        style={lensesUI.formItemStyle}
                                        defaultValue={0}
                                        step={0.1}
                                    />
                                </Form.Item>

                                <Form.Item label="Диаметр">
                                    <InputNumber
                                        value={lensesUI.searchParams.diameter || 0}
                                        onChange={(value) => lensesUI.handleParamChange("diameter", value)}
                                        style={lensesUI.formItemStyle}
                                        defaultValue={0}
                                        step={0.1}
                                    />
                                </Form.Item>

                                <Form.Item label="Рефракция">
                                    <InputNumber
                                        value={lensesUI.searchParams.preset_refraction || 0}
                                        onChange={(value) => lensesUI.handleParamChange("preset_refraction", value)}
                                        style={lensesUI.formItemStyle}
                                        defaultValue={0}
                                        step={0.1}
                                    />
                                </Form.Item>

                                <Form.Item label="Периферическая торичность">
                                    <InputNumber
                                        value={lensesUI.searchParams.periphery_toricity || 0}
                                        onChange={(value) => lensesUI.handleParamChange("periphery_toricity", value)}
                                        style={lensesUI.formItemStyle}
                                        defaultValue={0}
                                        step={0.1}
                                    />
                                </Form.Item>
                            </Form>
                        </Col>

                        <Col xs={24} sm={12}>
                            <Form layout="vertical">
                                <Form.Item label="Сторона">
                                    <Select
                                        value={lensesUI.searchParams.side}
                                        onChange={(value) => lensesUI.handleParamChange("side", value)}
                                        style={lensesUI.formItemStyle}
                                    >
                                        <Option value="all">Все</Option>
                                        <Option value="левая">Левая</Option>
                                        <Option value="правая">Правая</Option>
                                    </Select>
                                </Form.Item>

                                <Form.Item label="Выдана">
                                    <Select
                                        value={lensesUI.searchParams.issued}
                                        onChange={(value) => lensesUI.handleParamChange("issued", value)}
                                        style={lensesUI.formItemStyle}
                                    >
                                        <Option value="all">Все</Option>
                                        <Option value={true}>Да</Option>
                                        <Option value={false}>Нет</Option>
                                    </Select>
                                </Form.Item>

                                <Form.Item label="Острота зрения (Trial)">
                                    <InputNumber
                                        value={lensesUI.searchParams.trial || 0}
                                        onChange={(value) => lensesUI.handleParamChange("trial", value)}
                                        style={lensesUI.formItemStyle}
                                        defaultValue={0}
                                        step={0.1}
                                    />
                                </Form.Item>

                                <Row>
                                    <Col xs={24} sm={12} offset={screens.sm ? 12 : 0}
                                         style={{textAlign: screens.sm ? "right" : "center", marginTop: "1.7rem"}}>
                                        <Button
                                            type="primary"
                                            block={!screens.sm}
                                            onClick={() => {
                                                lensesUI.handleParamChange({
                                                    tor: null,
                                                    diameter: null,
                                                    preset_refraction: null,
                                                    periphery_toricity: null,
                                                    side: 'all',
                                                    issued: false,
                                                    trial: null
                                                });
                                            }}
                                        >
                                            Сбросить
                                        </Button>
                                    </Col>
                                </Row>
                            </Form>
                        </Col>
                    </Row>
                </Card>
            )}

            {lensesData.isLoading ? (
                <LoadingIndicator/>
            ) : lensesUI.viewMode === "tile" ? (
                <List
                    grid={{gutter: 16, xs: 1, sm: 1, md: 2, lg: 3, xl: 4}}
                    dataSource={lensesUI.filteredLenses}
                    renderItem={(lens) => (
                        <List.Item>
                            <LensCard
                                lens={lens}
                                handleDeleteLens={() => lensesData.handleDeleteLens(lens.id)}
                                handleEditLens={() => lensesUI.handleEditLens(lens)}
                            />
                        </List.Item>
                    )}
                    pagination={lensesUI.pagination}
                />
            ) : (
                <Table
                    columns={columns}
                    dataSource={lensesUI.filteredLenses}
                    scroll={{
                        x: "max-content"
                    }}
                    showSorterTooltip={false}
                    pagination={lensesUI.pagination}
                />
            )}

            <FloatButton
                icon={<PlusOutlined/>}
                type="primary"
                onClick={lensesUI.handleAddLens}
                tooltip="Добавить линзу"
            />

            <LensFormModal
                visible={lensesUI.isModalVisible}
                onCancel={lensesUI.handleCloseModal}
                onSubmit={lensesData.handleModalSubmit}
                lens={lensesUI.selectedLens}
            />
        </div>
    );
};

export default LensesTab;