/** @odoo-module */
import { Component, useState, useRef, onMounted } from "@odoo/owl";
import { Dialog } from "@web/core/dialog/dialog";
import { _t } from "@web/core/l10n/translation";

export class LaundryDeliveryDetailsPopup extends Component {
    static components = { Dialog };
    static template = "laundry_management.LaundryDeliveryDetailsPopup";
    static props = {
        defaultAddress: { type: String, optional: true },
        defaultScheduledAt: { type: String, optional: true },
        requireAddress: { type: Boolean, optional: true },
        requireScheduledTime: { type: Boolean, optional: true },
        title: { type: String, optional: true },
        getPayload: { type: Function },
        close: { type: Function },
    };
    static defaultProps = {
        defaultAddress: "",
        defaultScheduledAt: "",
        requireAddress: true,
        requireScheduledTime: false,
        title: _t("Delivery Details"),
    };

    setup() {
        this.state = useState({
            address: this.props.defaultAddress || "",
            scheduledAt: this.props.defaultScheduledAt || "",
            addressError: false,
            timeError: false,
        });
        this.addressRef = useRef("addressInput");
        onMounted(() => {
            if (this.addressRef.el) {
                this.addressRef.el.focus();
            }
        });
    }

    confirm() {
        this.state.addressError =
            this.props.requireAddress && !this.state.address.trim();
        this.state.timeError =
            this.props.requireScheduledTime && !this.state.scheduledAt;
        if (this.state.addressError || this.state.timeError) {
            return;
        }
        this.props.getPayload({
            address: this.state.address.trim(),
            scheduledAt: this.state.scheduledAt || false,
        });
        this.props.close();
    }

    cancel() {
        this.props.close();
    }
}
