from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ..client import WhatsrbCloud
    from .message import Message


class BusinessAccount:
    def __init__(self, data: dict, *, client: WhatsrbCloud | None = None):
        self.id = data.get("id")
        self.waba_id = data.get("waba_id")
        self.business_name = data.get("business_name")
        self.display_name = data.get("display_name")
        self.phone_number = data.get("phone_number")
        self.phone_number_id = data.get("phone_number_id")
        self.status = data.get("status")
        self.quality_rating = data.get("quality_rating")
        self.connected = data.get("connected")
        self.meta_token_expires_at = data.get("meta_token_expires_at")
        self._client = client
        self._raw = data

    @property
    def is_connected(self) -> bool:
        return self.connected is True or self.status == "connected"

    def send_text(self, *, to: str, text: str) -> Message:
        return self._messages_resource().create(to=to, message_type="text", content=text)

    def send_template(self, *, to: str, template_name: str, template_language: str) -> Message:
        return self._messages_resource().create(
            to=to,
            message_type="template",
            template_name=template_name,
            template_language=template_language,
        )

    def send_image(self, *, to: str, url: str) -> Message:
        return self._messages_resource().create(to=to, message_type="image", content=url)

    def send_video(self, *, to: str, url: str) -> Message:
        return self._messages_resource().create(to=to, message_type="video", content=url)

    def send_audio(self, *, to: str, url: str) -> Message:
        return self._messages_resource().create(to=to, message_type="audio", content=url)

    def send_document(self, *, to: str, url: str) -> Message:
        return self._messages_resource().create(to=to, message_type="document", content=url)

    def send_buttons(self, *, to: str, body: str, buttons: list) -> Message:
        formatted = []
        for i, btn in enumerate(buttons[:3]):
            if isinstance(btn, dict):
                formatted.append(btn)
            elif isinstance(btn, str):
                formatted.append({"id": f"btn_{i}", "title": btn})

        return self._messages_resource().create(
            to=to,
            message_type="interactive",
            content=body,
            message_metadata={"buttons": formatted},
        )

    def messages(self):
        return self._messages_resource()

    def window_open(self, phone_number: str) -> bool:
        result = self._client.business_accounts.window(self.id, phone_number=phone_number)
        return result.get("open") is True

    def window(self, phone_number: str) -> dict:
        return self._client.business_accounts.window(self.id, phone_number=phone_number)

    def templates(self):
        return self._client.templates(self.id)

    def reload(self) -> BusinessAccount:
        refreshed = self._client.business_accounts.retrieve(self.id)
        self.status = refreshed.status
        self.quality_rating = refreshed.quality_rating
        self.connected = refreshed.connected
        self.meta_token_expires_at = refreshed.meta_token_expires_at
        self.display_name = refreshed.display_name
        self.phone_number = refreshed.phone_number
        return self

    def refresh(self) -> BusinessAccount:
        return self.reload()

    def to_dict(self) -> dict:
        return self._raw

    def _messages_resource(self):
        return self._client.business_messages(self.id)
