use yew::prelude::*;
use yew_router::prelude::*;

use crate::pages::blog::content::Author;
use crate::pages::blog::content::BlogEntry;
use crate::pages::blog::entrycard::EntryCard;
use crate::pages::blog::navigation::{PageQuery, Pagination};
use crate::Route;

const ITEMS_PER_PAGE: u8 = 10;
const TOTAL_PAGES: u8 = 1;

pub enum Msg {
  PageUpdated,
}

pub struct Entries {
  page: u8,
  _listener: LocationHandle,
}

fn current_page(ctx: &Context<Entries>) -> u8 {
  let location = ctx.link().location().unwrap();

  location.query::<PageQuery>().map(|it| it.page as u8).unwrap_or(1)
}

impl Component for Entries {
  type Message = Msg;
  type Properties = ();

  fn create(ctx: &Context<Self>) -> Self {
    let link = ctx.link().clone();
    let listener = ctx
      .link()
      .add_location_listener(link.callback(move |_| Msg::PageUpdated))
      .unwrap();

    Self {
      page: current_page(ctx),
      _listener: listener,
    }
  }

  fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    match msg {
      Msg::PageUpdated => self.page = current_page(ctx),
    }
    true
  }

  fn view(&self, ctx: &Context<Self>) -> Html {
    let page = self.page;

    html! {
      <div class="section container">
        <h1 class="title">{ "entries" }</h1>
        <h2 class="subtitle">{ "here are some things i yapped about" }</h2>
        { self.view_posts(ctx) }
        <Pagination
          {page}
          total_pages={TOTAL_PAGES}
          route_to_page={Route::Entries}
        />
      </div>
    }
  }
}
impl Entries {
  fn view_posts(&self, _ctx: &Context<Self>) -> Html {
    let start_seed = (self.page - 1) * ITEMS_PER_PAGE;
    let cards: Vec<_> = (0..ITEMS_PER_PAGE)
      .filter(|&seed_offset| Author::from_seed(seed_offset).seed != u8::MAX)
      .map(|seed_offset| {
        html! {
          <li class="list-item mb-5">
            <EntryCard seed={start_seed + seed_offset} />
          </li>
        }
      }).collect();
    html! {
      <div class="columns">
        <div class="column">
          <ul class="list">
            { for cards }
          </ul>
        </div>
      </div>
    }
  }
}