"""Element Plus Dialog 组件关键字"""

from playwright.sync_api import Page, Locator
from typing import Optional

from ..base_keyword import BaseKeyword
from ...reference import INFO


class ElDialogKeyword(BaseKeyword):
    """Element Plus Dialog 组件关键字

    处理对话框、消息框、通知等弹出层组件。
    """

    def __init__(self, page: Page):
        super().__init__(page)

    def el_dialog_wait(self, *, content: str = '10000') -> None:
        """等待对话框出现

        Args:
            content: 超时时间 (毫秒)
        """
        timeout = int(content)
        INFO("等待对话框出现")

        dialog = self.page.locator('.el-dialog__wrapper:visible, .el-overlay:visible .el-dialog')
        dialog.wait_for(state='visible', timeout=timeout)

    def el_dialog_close(self) -> None:
        """关闭对话框"""
        INFO("关闭对话框")

        # 尝试点击关闭按钮
        close_btn = self.page.locator('.el-dialog__wrapper:visible .el-dialog__headerbtn, .el-overlay:visible .el-dialog__headerbtn')
        if close_btn.is_visible():
            close_btn.click()
        else:
            # 按 Escape 关闭
            self.page.keyboard.press('Escape')

        # 等待关闭
        try:
            self.page.locator('.el-dialog:visible').wait_for(state='hidden', timeout=3000)
        except Exception:
            pass

    def el_dialog_confirm(self, *, content: str = '确定') -> None:
        """点击对话框确认按钮

        Args:
            content: 按钮文本
        """
        INFO(f"点击对话框按钮: {content}")

        dialog = self.page.locator('.el-dialog__wrapper:visible, .el-overlay:visible .el-dialog')
        confirm_btn = dialog.locator(f'.el-dialog__footer .el-button:has-text("{content}")')

        if confirm_btn.is_visible():
            confirm_btn.click()
        else:
            # 尝试 Primary 按钮
            primary_btn = dialog.locator('.el-dialog__footer .el-button--primary')
            if primary_btn.is_visible():
                primary_btn.click()

    def el_dialog_cancel(self, *, content: str = '取消') -> None:
        """点击对话框取消按钮

        Args:
            content: 按钮文本
        """
        INFO(f"点击取消按钮: {content}")

        dialog = self.page.locator('.el-dialog__wrapper:visible, .el-overlay:visible .el-dialog')
        cancel_btn = dialog.locator(f'.el-dialog__footer .el-button:has-text("{content}")')

        if cancel_btn.is_visible():
            cancel_btn.click()
        else:
            # 尝试非 Primary 按钮
            default_btn = dialog.locator('.el-dialog__footer .el-button:not(.el-button--primary)').first
            if default_btn.is_visible():
                default_btn.click()

    def el_dialog_input(
        self,
        targeting: str = None,
        element: str = None,
        index: Optional[int] = None,
        *,
        content: str
    ) -> None:
        """在对话框中输入

        Args:
            targeting: 定位类型（可选，默认定位对话框内输入框）
            element: 定位表达式
            index: 索引
            content: 输入内容
        """
        INFO(f"对话框输入: {content}")

        dialog = self.page.locator('.el-dialog:visible')

        if targeting and element:
            input_el = self.locator(targeting, element, index)
        else:
            input_el = dialog.locator('.el-input__inner, .el-textarea__inner').first

        input_el.fill(str(content))

    def el_dialog_get_title(self) -> str:
        """获取对话框标题

        Returns:
            str: 对话框标题
        """
        dialog = self.page.locator('.el-dialog:visible')
        title = dialog.locator('.el-dialog__title').text_content() or ''
        return title.strip()

    def el_dialog_get_content(self) -> str:
        """获取对话框内容

        Returns:
            str: 对话框内容
        """
        dialog = self.page.locator('.el-dialog:visible')
        content = dialog.locator('.el-dialog__body').text_content() or ''
        return content.strip()

    # ==================== MessageBox ====================

    def el_message_box_wait(self, *, content: str = '10000') -> None:
        """等待 MessageBox 出现

        Args:
            content: 超时时间 (毫秒)
        """
        timeout = int(content)
        INFO("等待 MessageBox")

        box = self.page.locator('.el-message-box__wrapper:visible, .el-overlay:visible .el-message-box')
        box.wait_for(state='visible', timeout=timeout)

    def el_message_box_confirm(self, *, content: str = 'true') -> None:
        """处理 MessageBox 确认框

        Args:
            content: 是否确认 (true/false)
        """
        accept = str(content).lower() in ('true', '1', 'yes', '确定')
        INFO(f"MessageBox: {'确认' if accept else '取消'}")

        box = self.page.locator('.el-message-box__wrapper:visible, .el-overlay:visible .el-message-box')
        box.wait_for(state='visible', timeout=5000)

        if accept:
            box.locator('.el-message-box__btns .el-button--primary').click()
        else:
            box.locator('.el-message-box__btns .el-button:not(.el-button--primary)').first.click()

    def el_message_box_input(self, *, content: str) -> None:
        """MessageBox prompt 输入

        Args:
            content: 输入内容
        """
        INFO(f"MessageBox 输入: {content}")

        box = self.page.locator('.el-message-box:visible')
        input_el = box.locator('.el-message-box__input .el-input__inner')
        input_el.fill(str(content))

    def el_message_box_get_message(self) -> str:
        """获取 MessageBox 消息

        Returns:
            str: 消息内容
        """
        box = self.page.locator('.el-message-box:visible')
        message = box.locator('.el-message-box__message').text_content() or ''
        return message.strip()

    # ==================== Message ====================

    def el_message_wait(self, *, content: str = '5000') -> None:
        """等待 Message 消息出现

        Args:
            content: 超时时间 (毫秒)
        """
        timeout = int(content)
        INFO("等待 Message")

        message = self.page.locator('.el-message:visible')
        message.wait_for(state='visible', timeout=timeout)

    def el_message_get_text(self) -> str:
        """获取 Message 消息文本

        Returns:
            str: 消息文本
        """
        message = self.page.locator('.el-message:visible')
        text = message.locator('.el-message__content').text_content() or ''
        return text.strip()

    def el_message_assert(self, *, content: str, mode: str = 'contains') -> bool:
        """断言 Message 消息

        Args:
            content: 期望内容
            mode: 断言模式

        Returns:
            bool: 断言结果
        """
        actual = self.el_message_get_text()

        if mode == 'equals':
            result = actual == content
        elif mode == 'contains':
            result = content in actual
        else:
            result = content in actual

        INFO(f"Message 断言: '{actual}' {mode} '{content}' -> {result}")
        return result

    def el_message_close(self) -> None:
        """关闭 Message 消息"""
        INFO("关闭 Message")

        message = self.page.locator('.el-message:visible')
        close_btn = message.locator('.el-message__closeBtn, .el-icon-close')
        if close_btn.is_visible():
            close_btn.click()

    # ==================== Notification ====================

    def el_notification_wait(self, *, content: str = '5000') -> None:
        """等待 Notification 通知出现

        Args:
            content: 超时时间 (毫秒)
        """
        timeout = int(content)
        INFO("等待 Notification")

        notification = self.page.locator('.el-notification:visible')
        notification.wait_for(state='visible', timeout=timeout)

    def el_notification_get_title(self) -> str:
        """获取 Notification 标题

        Returns:
            str: 通知标题
        """
        notification = self.page.locator('.el-notification:visible')
        title = notification.locator('.el-notification__title').text_content() or ''
        return title.strip()

    def el_notification_get_content(self) -> str:
        """获取 Notification 内容

        Returns:
            str: 通知内容
        """
        notification = self.page.locator('.el-notification:visible')
        content = notification.locator('.el-notification__content').text_content() or ''
        return content.strip()

    def el_notification_close(self) -> None:
        """关闭 Notification"""
        INFO("关闭 Notification")

        notification = self.page.locator('.el-notification:visible')
        close_btn = notification.locator('.el-notification__closeBtn')
        if close_btn.is_visible():
            close_btn.click()

    # ==================== Drawer ====================

    def el_drawer_wait(self, *, content: str = '10000') -> None:
        """等待 Drawer 抽屉出现

        Args:
            content: 超时时间 (毫秒)
        """
        timeout = int(content)
        INFO("等待 Drawer")

        drawer = self.page.locator('.el-drawer:visible')
        drawer.wait_for(state='visible', timeout=timeout)

    def el_drawer_close(self) -> None:
        """关闭 Drawer"""
        INFO("关闭 Drawer")

        close_btn = self.page.locator('.el-drawer:visible .el-drawer__close-btn')
        if close_btn.is_visible():
            close_btn.click()
        else:
            self.page.keyboard.press('Escape')

    def el_drawer_get_title(self) -> str:
        """获取 Drawer 标题

        Returns:
            str: 抽屉标题
        """
        drawer = self.page.locator('.el-drawer:visible')
        title = drawer.locator('.el-drawer__title').text_content() or ''
        return title.strip()
