from collections import defaultdict
from collections.abc import Iterable

from ..models import LogEntry

TEMPLATE_HTML = """\
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>BragLog</title>
    {style}
</head>
<body>
    <button class="toggle-button" onclick="toggleDarkMode()" id="modeToggle">🌙</button>
    <div class='main-content'>
    {content}
    </div>
    {script}
    <footer>Proudly generated by BragLog&#8482;</footer>
</body>
</html>"""

TEMPLATE_SECTION = """\
    <!-- {year} -->
    <div class="section">
      <div class="collapsible" onclick="toggleContent('year{year}', this)">
        <span class="arrow">&#9654;</span>
        <h2>{year}</h2>
      </div>
      <div id="year{year}" class="content">
      {months}
      </div>
    </div>
    """
MONTHLY_BLOCK = """\
        <div class="month">
          <div class="collapsible" onclick="toggleContent('{month}{year}', this)">
            <span class="arrow">&#9654;</span>
            <h3>{month}</h3>
          </div>
          <div id="{month}{year}" class="content">
            <ul>
              {achievements}
            </ul>
          </div>
        </div>
    """

SCRIPT = """\
  <script>
    function toggleContent(id, el) {
      const content = document.getElementById(id);
      const arrow = el.querySelector('.arrow');
      const isOpen = content.style.display === 'block';

      content.style.display = isOpen ? 'none' : 'block';
      arrow.classList.toggle('open', !isOpen);
    }

    function toggleDarkMode() {
      const body = document.body;
      const button = document.getElementById("modeToggle");

      body.classList.toggle("dark-mode");

      const isDark = body.classList.contains("dark-mode");
      button.textContent = isDark ? "🌞" : "🌙";
    }
  </script>"""

STYLE = """\
<style>
    :root {
      --bg-color: #f9f9f9;
      --text-color: #333;
      --card-bg: #fff;
      --border-color: #ddd;
      --hover-bg: #f0f0f0;
      --shadow: rgba(0, 0, 0, 0.04);
    }

    body.dark-mode {
      --bg-color: #1e1e1e;
      --text-color: #eee;
      --card-bg: #2a2a2a;
      --border-color: #444;
      --hover-bg: #333;
      --shadow: rgba(0, 0, 0, 0.3);
    }

    body {
      font-family: "Segoe UI", sans-serif;
      background-color: var(--bg-color);
      color: var(--text-color);
      padding: 30px;
      line-height: 1.6;
      transition: background-color 0.3s, color 0.3s;
    }

    .main-content {
      padding-top: 20px;
      padding-right: 70px;
    }

    .toggle-button {
      position: fixed;
      top: 20px;
      right: 20px;
      background: var(--card-bg);
      color: var(--text-color);
      border: 1px solid var(--border-color);
      font-size: 20px;
      padding: 6px 10px;
      border-radius: 50%;
      cursor: pointer;
      z-index: 1000;
      transition: background-color 0.3s, color 0.3s;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }

    .toggle-button:hover {
      background-color: var(--hover-bg);
    }

    .section,
    .month {
      border: 1px solid var(--border-color);
      background-color: var(--card-bg);
      border-radius: 6px;
      margin-bottom: 15px;
      box-shadow: 0 2px 4px var(--shadow);
      overflow: hidden;
      transition: background-color 0.3s, border-color 0.3s;
    }

    .collapsible {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      cursor: pointer;
      transition: background-color 0.2s;
    }

    .collapsible:hover {
      background-color: var(--hover-bg);
    }

    .arrow {
      margin-right: 12px;
      font-size: 14px;
      transition: transform 0.2s ease;
    }

    .arrow.open {
      transform: rotate(90deg);
    }

    h2,
    h3 {
      margin: 0;
      font-weight: 500;
    }

    .content {
      padding: 0 16px 10px 40px;
      display: none;
      animation: fadeIn 0.3s ease;
    }

    ul {
      padding-left: 20px;
      margin: 6px 0;
    }

    li {
      margin-bottom: 6px;
    }

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(-4px);
      }

      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    footer {
      text-align: center;
      padding: 2rem 0;
      color: #6a737d;
      font-size: 0.9rem;
    }
  </style>
"""  # noqa: E501


class FodableHTMLFormatter:
    def __init__(self, entries: Iterable[LogEntry]) -> None:
        self.entries = entries

    def _get_entries_by_date(self) -> dict[int, dict[str, list[str]]]:
        entries_by_date = defaultdict(lambda: defaultdict(list))
        for entry in self.entries:
            year = entry.log_date.year
            month = entry.log_date.strftime("%B")

            entries_by_date[year][month].append(entry.message)
        return entries_by_date

    def _render_section(self, messages: list[str]) -> str:
        return "\n".join(f"<li>{msg}</li>" for msg in messages)

    def __str__(self) -> str:
        entries_by_date = self._get_entries_by_date()

        years = []
        for year, month_msgs in entries_by_date.items():
            months: list[str] = []
            for month, messages in month_msgs.items():
                achievements = self._render_section(messages)
                months.append(
                    MONTHLY_BLOCK.format(
                        year=year,
                        month=month,
                        achievements=achievements,
                    )
                )
            years.append(TEMPLATE_SECTION.format(year=year, months="\n".join(months)))
        content = "\n".join(years)

        return TEMPLATE_HTML.format(
            style=STYLE,
            content=content,
            script=SCRIPT,
        )
