use std::rc::Rc;

use yew::prelude::*;
use yew_router::components::Link;

use crate::pages::blog::content::BlogEntry;
use crate::pages::blog::content::PostMeta;

use crate::Route;

#[derive(Clone, Debug, PartialEq, Eq, Properties)]
pub struct PropsEntryCard {
  pub seed: u8,
}

#[derive(PartialEq, Eq, Debug)]
pub struct PostMetaState {
  inner: PostMeta,
}

impl Reducible for PostMetaState {
  type Action = u8;

  fn reduce(self: Rc<Self>, action: u8) -> Rc<Self> {
    Self { inner: PostMeta::from_seed(action.into()), }.into()
  }
}

#[function_component]
pub fn EntryCard(props: &PropsEntryCard) -> Html {
  let seed = props.seed;

  let post = use_reducer_eq(|| PostMetaState {
    inner: PostMeta::from_seed(seed.into()),
  });

  {
    let post_dispatcher = post.dispatcher();
    use_effect_with(seed, move |seed| {
      post_dispatcher.dispatch(*seed);

      || {}
    });
  }

  let post = &post.inner;

  html! {
    <div class="card" style="height: 300px !important; max-height: 300px !important;">
      <img loading="eager" class="card-image image is-2by1" src={post.image_url.clone()} alt="blog image" style="
        object-fit: cover !important;
        width: 100% !important;
        max-width: 100% !important;
        height: 200px !important;
        max-height: 200px !important;
        filter: blur(6px) !important;
      " />
      <div class="card-content" style="height: fit-content !important; width: fit-content !important;">
        <Link<Route> classes={classes!("title", "is-block")} to={Route::Entry { id: post.seed }}>
          { &post.title }
        </Link<Route>>
        <Link<Route> classes={classes!("subtitle", "is-block")} to={Route::Author { id: post.author.seed }}>
          { &post.author.name }
        </Link<Route>>
      </div>
    </div>
  }
}
