from __future__ import annotations

from textual import events
from textual.app import ComposeResult
from textual.widgets import ListItem, Static

from crypto_utils import fmt_time


class SidebarResizeHandle(Static):
    def __init__(self):
        super().__init__("", id="sidebar_handle")
        self.dragging = False
        self.start_x = 0
        self.start_w = 0

    def on_mouse_down(self, event: events.MouseDown) -> None:
        self.dragging = True
        self.capture_mouse()
        self.start_x = event.screen_x
        self.start_w = self.app.sidebar_width

    def on_mouse_move(self, event: events.MouseMove) -> None:
        if not self.dragging:
            return
        dx = event.screen_x - self.start_x
        self.app.set_sidebar_width(self.start_w + dx)

    def on_mouse_up(self, event: events.MouseUp) -> None:
        if self.dragging:
            self.dragging = False
            self.release_mouse()


class ChatItem(ListItem):
    def __init__(
        self,
        peer_alias: str,
        title: str | None = None,
        subtitle: str = "",
        unread: int = 0,
        locked: bool = False,
        online: bool = False,
        active_call: int = 0,
    ):
        super().__init__()
        self.peer_alias = peer_alias
        self.title = title if title is not None else peer_alias
        self.subtitle = subtitle
        self.unread = unread
        self.locked = locked
        self.online = online
        self.active_call = active_call

    def compose(self) -> ComposeResult:
        status = "●" if self.online else " "
        lock = "🔒" if self.locked else " "
        badge = f"  {self.unread}" if self.unread > 0 else ""
        call_indicator = f" 📞{self.active_call}" if self.active_call > 0 else ""
        yield Static(f"{status} {lock} {self.title}{badge}{call_indicator}", classes="chat_item_title")
        if self.subtitle:
            yield Static(self.subtitle, classes="chat_item_sub")


class RequestInItem(ListItem):
    def __init__(self, req_id: int, peer_alias: str, peer_fp: str, received_at: int):
        super().__init__()
        self.req_id = req_id
        self.peer_alias = peer_alias
        self.peer_fp = peer_fp
        self.received_at = received_at

    def compose(self) -> ComposeResult:
        yield Static(f"IN  {self.peer_alias}", classes="req_item_title")
        yield Static(f"{self.peer_fp} • {fmt_time(self.received_at)}", classes="req_item_sub")


class RequestOutItem(ListItem):
    def __init__(self, req_id: int, peer_alias: str, state: str, created_at: int, updated_at: int):
        super().__init__()
        self.req_id = req_id
        self.peer_alias = peer_alias
        self.state = state
        self.created_at = created_at
        self.updated_at = updated_at

    def compose(self) -> ComposeResult:
        st = self.state.upper()
        yield Static(f"OUT {self.peer_alias}  [{st}]", classes="req_item_title")
        yield Static(self.app.t("req_created_updated", c=fmt_time(self.created_at), u=fmt_time(self.updated_at)), classes="req_item_sub")


class UserItem(ListItem):
    def __init__(self, alias: str, status: str = "offline", status_msg: str = ""):
        super().__init__()
        self.alias = alias
        self.status = status
        self.status_msg = status_msg

    def compose(self) -> ComposeResult:

        status_char = "●"
        status_class = f"status_{self.status}"

        yield Static(f"{status_char} {self.alias}", classes=f"user_item_title {status_class}")
        if self.status_msg:
            msg = self.status_msg
            if len(msg) > 50:
                msg = msg[:50] + "…"
            yield Static(msg, classes="user_item_sub")


class GroupInviteInItem(ListItem):
    def __init__(self, req_id: int, from_alias: str, group_id: str, group_name: str, received_at: int):
        super().__init__()
        self.req_id = req_id
        self.from_alias = from_alias
        self.group_id = group_id
        self.group_name = group_name
        self.received_at = received_at

    def compose(self) -> ComposeResult:
        yield Static(f"GROUP  {self.group_name}", classes="req_item_title")
        yield Static(f"From {self.from_alias} • {fmt_time(self.received_at)}", classes="req_item_sub")

