from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING, ClassVar

from textual.containers import Horizontal, Vertical
from textual.screen import ModalScreen
from textual.widgets import Button, Input, Label

if TYPE_CHECKING:
    from textual.app import ComposeResult
    from textual.binding import BindingType


@dataclass
class TransactionData:
    name: str
    amount: str
    date: str


class AddTransactionModal(ModalScreen[TransactionData | None]):
    BINDINGS: ClassVar[list[BindingType]] = [
        ("down", "focus_next", "Next field"),
        ("up", "focus_previous", "Previous field"),
        ("escape", "cancel", "Cancel"),
    ]

    def compose(self) -> ComposeResult:
        with Vertical(id="modal-dialog"):
            yield Label("[#3b82f6]Add Transaction[/]", id="modal-title")
            yield Label("Name:", classes="modal-label")
            yield Input(
                placeholder="e.g. Rent, Salary",
                id="transaction-name-input",
            )
            yield Label(
                "Amount (negative = expense, positive = income):", classes="modal-label"
            )
            yield Input(
                placeholder="e.g. -150.50 or 3000",
                id="transaction-amount-input",
            )
            yield Label("Date (optional, YYYY-MM-DD):", classes="modal-label")
            yield Input(
                placeholder="Leave blank for today",
                id="transaction-date-input",
            )
            with Horizontal(id="modal-buttons"):
                yield Button("Add", id="modal-confirm", variant="primary")
                yield Button("Cancel", id="modal-cancel", variant="default")

    def on_mount(self) -> None:
        self.query_one("#transaction-name-input", Input).focus()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "modal-confirm":
            self._submit()
        else:
            self.dismiss(None)

    def on_input_submitted(self, _event: Input.Submitted) -> None:
        self.focus_next()

    def action_cancel(self) -> None:
        self.dismiss(None)

    def _submit(self) -> None:
        name = self.query_one("#transaction-name-input", Input).value.strip()
        amount = self.query_one("#transaction-amount-input", Input).value.strip()
        date_str = self.query_one("#transaction-date-input", Input).value.strip()

        if not name:
            self.notify("Transaction name cannot be empty.", severity="error")
            return

        if not amount:
            self.notify("Amount cannot be empty.", severity="error")
            return

        try:
            value = float(amount)
        except ValueError:
            self.notify("Amount must be a valid number.", severity="error")
            return

        if value == 0:
            self.notify("Amount cannot be zero.", severity="error")
            return

        if date_str:
            try:
                datetime.fromisoformat(date_str)
            except ValueError:
                self.notify(
                    "Invalid date format (expected YYYY-MM-DD).", severity="error"
                )
                return

        self.dismiss(TransactionData(name=name, amount=amount, date=date_str or ""))
