import {
    Modal, Input, Button, Typography, Collapse, Steps, Row, Alert, Col, DatePicker, Spin
} from "antd";
import PropTypes from "prop-types";
import useLensIssueForm from "./useLensIssueForm.js";
import useLensIssueFormUI from "./useLensIssueFormUI.js";
import {useMemo} from "react";

const LensIssueFormModal = ({visible, onCancel, onSubmit}) => {
    const lensIssueFormModalData = useLensIssueForm();
    const lensIssueFormModalUI = useLensIssueFormUI(visible, onCancel, onSubmit, lensIssueFormModalData.patients, lensIssueFormModalData.lenses);

    const patientsItems = lensIssueFormModalUI.filteredPatients.map((patient) => ({
        key: patient.id,
        label: `${patient.last_name} ${patient.first_name} (${lensIssueFormModalUI.getDateString(patient.birthday)})`,
        children: <div>
            <p><b>Пациент:</b> {patient.last_name} {patient.first_name}</p>
            <p><b>Дата рождения:</b> {lensIssueFormModalUI.getDateString(patient.birthday)}</p>
            <p><b>Диагноз:</b> {patient.diagnosis}</p>
            <p><b>Email:</b> {patient.email}</p>
            <p><b>Телефон:</b> {patient.phone}</p>
            <Button type="primary" onClick={() => lensIssueFormModalUI.setSelectedPatient(patient)}>Выбрать</Button>
        </div>,
    }));

    const lensesItems = lensIssueFormModalUI.filteredLenses.map((lens) => ({
        key: lens.id, label: `Линза ${lens.side} ${lens.diameter} мм`, children: <div>
            <p><b>Диаметр:</b> {lens.diameter}</p>
            <p><b>Тор:</b> {lens.tor}</p>
            <p><b>Пресетная рефракция:</b> {lens.preset_refraction}</p>
            <p><b>Диаметр:</b> {lens.diameter}</p>
            <p><b>FVC:</b> {lens.fvc}</p>
            <p><b>Острота зрения (Trial):</b> {lens.trial}</p>
            <p><b>Периферийная торичность:</b> {lens.periphery_toricity}</p>
            <p><b>Сторона:</b> {lens.side}</p>
            <p><b>Esa:</b> {lens.esa}</p>
            <Button type="primary" onClick={() => lensIssueFormModalUI.setSelectedLens(lens)}>Выбрать</Button>
        </div>,
    }));

    const SelectPatientStep = useMemo(() => {
        return lensIssueFormModalUI.selectedPatient ? (
            <div style={lensIssueFormModalUI.blockStepStyle}>
                <Typography.Text strong>
                    {lensIssueFormModalUI.selectedPatient.last_name} {lensIssueFormModalUI.selectedPatient.first_name}
                </Typography.Text>
                <p><b>Дата
                    рождения:</b> {lensIssueFormModalUI.getSelectedPatientBirthdayString()}
                </p>
                <p><b>Email:</b> {lensIssueFormModalUI.selectedPatient.email}</p>
                <p><b>Телефон:</b> {lensIssueFormModalUI.selectedPatient.phone}</p>
                <Button
                    type="primary"
                    onClick={lensIssueFormModalUI.resetPatient}
                    danger
                >
                    Выбрать другого пациента
                </Button>
            </div>
        ) : (
            <>
                <Input
                    placeholder="Поиск пациента"
                    value={lensIssueFormModalUI.searchPatientString}
                    onChange={lensIssueFormModalUI.handleSetSearchPatientString}
                    style={lensIssueFormModalUI.searchInputStyle}
                    allowClear
                />

                <div style={lensIssueFormModalUI.chooseContainerStyle}>
                    <Collapse
                        items={patientsItems}
                    />
                </div>
            </>
        );
    }, [lensIssueFormModalUI, patientsItems]);

    const SelectLensStep = useMemo(() => {
        return lensIssueFormModalUI.selectedLens ? (
            <div style={lensIssueFormModalUI.blockStepStyle}>
                <Typography.Text strong>
                    {lensIssueFormModalUI.selectedLens.diameter} {lensIssueFormModalUI.selectedLens.tor} {lensIssueFormModalUI.selectedLens.preset_refraction}
                </Typography.Text>
                <p><b>Диаметр:</b> {lensIssueFormModalUI.selectedLens.diameter}</p>
                <p><b>Тор:</b> {lensIssueFormModalUI.selectedLens.tor}</p>
                <p><b>Пресетная рефракция:</b> {lensIssueFormModalUI.selectedLens.preset_refraction}</p>
                <p><b>Диаметр:</b> {lensIssueFormModalUI.selectedLens.diameter}</p>
                <p><b>FVC:</b> {lensIssueFormModalUI.selectedLens.fvc}</p>
                <p><b>Острота зрения (Trial):</b> {lensIssueFormModalUI.selectedLens.trial}</p>
                <p><b>Периферийная торичность:</b> {lensIssueFormModalUI.selectedLens.periphery_toricity}</p>
                <p><b>Сторона:</b> {lensIssueFormModalUI.selectedLens.side}</p>
                <p><b>Esa:</b> {lensIssueFormModalUI.selectedLens.esa}</p>
                <Button
                    type="primary"
                    onClick={lensIssueFormModalUI.resetLens}
                    danger
                >
                    Выбрать другую линзу
                </Button>
            </div>
        ) : (
            <>
                <Input
                    placeholder="Поиск линз"
                    value={lensIssueFormModalUI.searchLensString}
                    onChange={lensIssueFormModalUI.handleSetSearchLensString}
                    style={lensIssueFormModalUI.searchInputStyle}
                    allowClear
                />

                <div style={lensIssueFormModalUI.chooseContainerStyle}>
                    <Collapse
                        items={lensesItems}
                    />
                </div>
            </>
        );
    }, [lensIssueFormModalUI.blockStepStyle, lensIssueFormModalUI.chooseContainerStyle, lensIssueFormModalUI.handleSetSearchLensString, lensIssueFormModalUI.resetLens, lensIssueFormModalUI.searchInputStyle, lensIssueFormModalUI.searchLensString, lensIssueFormModalUI.selectedLens, lensesItems]);

    const ConfirmStep = useMemo(() => {
        if (!lensIssueFormModalUI.selectedPatient || !lensIssueFormModalUI.selectedLens) {
            return null;
        }

        return (
            <>
                <Alert
                    type="warning"
                    message="Внимание! После подтверждения линза будет считаться выданной, данное действие нельзя будет отменить."
                    style={lensIssueFormModalUI.alertStyle}
                />

                <Row style={lensIssueFormModalUI.blockStepStyle}
                     gutter={[16, 16]}>
                    <Col xs={24} md={16} style={lensIssueFormModalUI.issueDateContainerStyle}>
                        <Typography.Text strong>
                            Дата выдачи: {lensIssueFormModalUI.issueDate?.toDate().toLocaleDateString("ru-RU")}
                        </Typography.Text>
                    </Col>
                    <Col xs={24} md={8}>
                        <DatePicker
                            placeholder={"Дата выдачи"}
                            value={lensIssueFormModalUI.issueDate}
                            onChange={lensIssueFormModalUI.handleSetIssueDate}
                            format={"DD.MM.YYYY"}
                            style={lensIssueFormModalUI.datePickerStyle}
                        />
                    </Col>
                </Row>

                <div style={lensIssueFormModalUI.blockStepStyle}>
                    <Typography.Text strong>
                        {lensIssueFormModalUI.selectedPatient.last_name} {lensIssueFormModalUI.selectedPatient.first_name}
                    </Typography.Text>
                    <p><b>Дата
                        рождения:</b> {lensIssueFormModalUI.getSelectedPatientBirthdayString()}
                    </p>
                    <p><b>Email:</b> {lensIssueFormModalUI.selectedPatient.email}</p>
                    <p><b>Телефон:</b> {lensIssueFormModalUI.selectedPatient.phone}</p>
                    <p>
                        <b>Линза:</b> {lensIssueFormModalUI.selectedLens.diameter} {lensIssueFormModalUI.selectedLens.tor} {lensIssueFormModalUI.selectedLens.preset_refraction}
                    </p>
                </div>

                <div style={lensIssueFormModalUI.blockStepStyle}>
                    <Typography.Text strong>
                        {lensIssueFormModalUI.selectedLens.diameter} {lensIssueFormModalUI.selectedLens.tor} {lensIssueFormModalUI.selectedLens.preset_refraction}
                    </Typography.Text>
                    <p><b>Диаметр:</b> {lensIssueFormModalUI.selectedLens.diameter}</p>
                    <p><b>Тор:</b> {lensIssueFormModalUI.selectedLens.tor}</p>
                    <p><b>Пресетная рефракция:</b> {lensIssueFormModalUI.selectedLens.preset_refraction}</p>
                    <p><b>Диаметр:</b> {lensIssueFormModalUI.selectedLens.diameter}</p>
                    <p><b>FVC:</b> {lensIssueFormModalUI.selectedLens.fvc}</p>
                    <p><b>Острота зрения (Trial):</b> {lensIssueFormModalUI.selectedLens.trial}</p>
                    <p><b>Периферийная торичность:</b> {lensIssueFormModalUI.selectedLens.periphery_toricity}</p>
                    <p><b>Сторона:</b> {lensIssueFormModalUI.selectedLens.side}</p>
                    <p><b>Esa:</b> {lensIssueFormModalUI.selectedLens.esa}</p>
                </div>
            </>
        );
    }, [lensIssueFormModalUI]);

    const steps = [{
        title: 'Выбор пациента', content: SelectPatientStep,
    }, {
        title: 'Выбор линзы', content: SelectLensStep,
    }, {
        title: 'Подтверждение', content: ConfirmStep,
    }];

    return (
        <Modal
            title="Выдача линзы пациенту"
            open={visible}
            onCancel={lensIssueFormModalUI.cancelModal}
            footer={null}
            maskClosable={false}
            width={lensIssueFormModalUI.modalWidth}
            centered
        >
            {lensIssueFormModalData.loading ? (
                <div style={lensIssueFormModalUI.loadingContainerStyle}>
                    <Spin size="large"/>
                </div>
            ) : (
                <div style={lensIssueFormModalUI.stepsContentStyle}>
                    {steps[lensIssueFormModalUI.currentStep].content}
                </div>
            )}


            {!lensIssueFormModalUI.screenXS && (
                <Steps
                    current={lensIssueFormModalUI.currentStep}
                    items={steps}
                    style={lensIssueFormModalUI.stepsIndicatorStyle}
                    direction={lensIssueFormModalUI.direction}
                />
            )}

            <Row
                justify="end"
                style={lensIssueFormModalUI.footerRowStyle}
                gutter={[8, 8]}
            >
                <Button
                    style={lensIssueFormModalUI.footerButtonStyle}
                    onClick={lensIssueFormModalUI.handleClickBackButton}
                    disabled={lensIssueFormModalUI.disableBackButton}
                >
                    Назад
                </Button>
                <Button
                    type="primary"
                    onClick={lensIssueFormModalUI.handleClickNextButton}
                    disabled={lensIssueFormModalUI.disableNextButton}
                >
                    {lensIssueFormModalUI.nextButtonText}
                </Button>
            </Row>
        </Modal>
    );
};

LensIssueFormModal.propTypes = {
    visible: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
};

export default LensIssueFormModal;
