use super::common_key_events;
use crate::core::app::{AlbumTableContext, App, RecommendationsContext};
use crate::infra::network::IoEvent;
use crate::tui::event::Key;

pub fn handler(key: Key, app: &mut App) {
  match key {
    k if common_key_events::left_event(k, &app.user_config.keys) => {
      common_key_events::handle_left_event(app)
    }
    k if common_key_events::down_event(k, &app.user_config.keys) => match app.album_table_context {
      AlbumTableContext::Full => {
        if let Some(selected_album) = &app.selected_album_full {
          let next_index = common_key_events::on_down_press_handler(
            &selected_album.album.tracks,
            Some(app.saved_album_tracks_index),
          );
          app.saved_album_tracks_index = next_index;
        };
      }
      AlbumTableContext::Simplified => {
        if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
          let next_index = common_key_events::on_down_press_handler(
            &selected_album_simplified.tracks.items,
            Some(selected_album_simplified.selected_index),
          );
          selected_album_simplified.selected_index = next_index;
        }
      }
    },
    k if common_key_events::up_event(k, &app.user_config.keys) => match app.album_table_context {
      AlbumTableContext::Full => {
        if let Some(selected_album) = &app.selected_album_full {
          let next_index = common_key_events::on_up_press_handler(
            &selected_album.album.tracks,
            Some(app.saved_album_tracks_index),
          );
          app.saved_album_tracks_index = next_index;
        };
      }
      AlbumTableContext::Simplified => {
        if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
          let next_index = common_key_events::on_up_press_handler(
            &selected_album_simplified.tracks.items,
            Some(selected_album_simplified.selected_index),
          );
          selected_album_simplified.selected_index = next_index;
        }
      }
    },
    k if common_key_events::high_event(k) => handle_high_event(app),
    k if common_key_events::middle_event(k) => handle_middle_event(app),
    k if common_key_events::low_event(k) => handle_low_event(app),
    Key::Char('s') => handle_save_event(app),
    Key::Char('w') => handle_save_album_event(app),
    Key::Enter => match app.album_table_context {
      AlbumTableContext::Full => {
        if let Some(selected_album) = app.selected_album_full.clone() {
          app.dispatch(IoEvent::StartPlayback(
            selected_album.album.uri.clone(),
            None,
            Some(app.saved_album_tracks_index),
          ));
        };
      }
      AlbumTableContext::Simplified => {
        if let Some(selected_album_simplified) = &app.selected_album_simplified.clone() {
          app.dispatch(IoEvent::StartPlayback(
            selected_album_simplified.album.uri.clone(),
            None,
            Some(selected_album_simplified.selected_index),
          ));
        };
      }
    },
    //recommended playlist based on selected track
    Key::Char('r') => {
      handle_recommended_tracks(app);
    }
    _ if key == app.user_config.keys.add_item_to_queue => {
      let track = match app.album_table_context {
        AlbumTableContext::Full => app
          .selected_album_full
          .as_ref()
          .and_then(|a| a.album.tracks.get(app.saved_album_tracks_index).cloned()),
        AlbumTableContext::Simplified => app
          .selected_album_simplified
          .as_ref()
          .and_then(|a| a.tracks.items.get(a.selected_index).cloned()),
      };
      if let Some(track) = track {
        app.add_track_to_native_queue(track);
      }
    }
    _ => {}
  };
}

fn handle_high_event(app: &mut App) {
  match app.album_table_context {
    AlbumTableContext::Full => {
      let next_index = common_key_events::on_high_press_handler();
      app.saved_album_tracks_index = next_index;
    }
    AlbumTableContext::Simplified => {
      if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
        let next_index = common_key_events::on_high_press_handler();
        selected_album_simplified.selected_index = next_index;
      }
    }
  }
}

fn handle_middle_event(app: &mut App) {
  match app.album_table_context {
    AlbumTableContext::Full => {
      if let Some(selected_album) = &app.selected_album_full {
        let next_index = common_key_events::on_middle_press_handler(&selected_album.album.tracks);
        app.saved_album_tracks_index = next_index;
      };
    }
    AlbumTableContext::Simplified => {
      if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
        let next_index =
          common_key_events::on_middle_press_handler(&selected_album_simplified.tracks.items);
        selected_album_simplified.selected_index = next_index;
      }
    }
  }
}

fn handle_low_event(app: &mut App) {
  match app.album_table_context {
    AlbumTableContext::Full => {
      if let Some(selected_album) = &app.selected_album_full {
        let next_index = common_key_events::on_low_press_handler(&selected_album.album.tracks);
        app.saved_album_tracks_index = next_index;
      };
    }
    AlbumTableContext::Simplified => {
      if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
        let next_index =
          common_key_events::on_low_press_handler(&selected_album_simplified.tracks.items);
        selected_album_simplified.selected_index = next_index;
      }
    }
  }
}

fn handle_recommended_tracks(app: &mut App) {
  match app.album_table_context {
    AlbumTableContext::Full => {
      if let Some(selected_album) = &app.selected_album_full.clone() {
        if let Some(track) = selected_album
          .album
          .tracks
          .get(app.saved_album_tracks_index)
        {
          if let Some(id) = &track.id {
            app.recommendations_context = Some(RecommendationsContext::Song);
            app.recommendations_seed = track.name.clone();
            app.get_recommendations_for_track_id(id.clone());
          }
        }
      }
    }
    AlbumTableContext::Simplified => {
      if let Some(selected_album_simplified) = &app.selected_album_simplified.clone() {
        if let Some(track) = selected_album_simplified
          .tracks
          .items
          .get(selected_album_simplified.selected_index)
        {
          if let Some(id) = &track.id {
            app.recommendations_context = Some(RecommendationsContext::Song);
            app.recommendations_seed = track.name.clone();
            app.get_recommendations_for_track_id(id.clone());
          }
        }
      };
    }
  }
}

fn handle_save_event(app: &mut App) {
  match app.album_table_context {
    AlbumTableContext::Full => {
      if let Some(selected_album) = app.selected_album_full.clone() {
        if let Some(selected_track) = selected_album
          .album
          .tracks
          .get(app.saved_album_tracks_index)
        {
          if let Some(track_id_str) = &selected_track.id {
            app.dispatch(IoEvent::ToggleSaveTrack(track_id_str.clone()));
          };
        };
      };
    }
    AlbumTableContext::Simplified => {
      if let Some(selected_album_simplified) = app.selected_album_simplified.clone() {
        if let Some(selected_track) = selected_album_simplified
          .tracks
          .items
          .get(selected_album_simplified.selected_index)
        {
          if let Some(track_id_str) = &selected_track.id {
            app.dispatch(IoEvent::ToggleSaveTrack(track_id_str.clone()));
          };
        };
      };
    }
  }
}

fn handle_save_album_event(app: &mut App) {
  match app.album_table_context {
    AlbumTableContext::Full => {
      if let Some(selected_album) = app.selected_album_full.clone() {
        if let Some(album_id_str) = &selected_album.album.id {
          app.dispatch(IoEvent::CurrentUserSavedAlbumAdd(album_id_str.clone()));
        }
      };
    }
    AlbumTableContext::Simplified => {
      if let Some(selected_album_simplified) = app.selected_album_simplified.clone() {
        if let Some(album_id_str) = &selected_album_simplified.album.id {
          app.dispatch(IoEvent::CurrentUserSavedAlbumAdd(album_id_str.clone()));
        };
      };
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::core::app::ActiveBlock;

  #[test]
  fn on_left_press() {
    let mut app = App::default();
    app.set_current_route_state(
      Some(ActiveBlock::AlbumTracks),
      Some(ActiveBlock::AlbumTracks),
    );

    handler(Key::Left, &mut app);
    let current_route = app.get_current_route();
    assert_eq!(current_route.active_block, ActiveBlock::Empty);
    assert_eq!(current_route.hovered_block, ActiveBlock::Library);
  }

  #[test]
  fn on_esc() {
    let mut app = App::default();

    handler(Key::Esc, &mut app);

    let current_route = app.get_current_route();
    assert_eq!(current_route.active_block, ActiveBlock::Empty);
  }
}
