import Suggestions from "../../../renderer/containers/suggestions";
import { useStore } from "../../../renderer/stores/global-stores";
import React, { useEffect, useState } from "react";
import Suggestion from "../../../renderer/components/suggestion";
import { OMSExtension } from "@common/types/OMSExtension";
import useSWR from "swr";

export default function ViewHackerNews() {
  const [currentRoute, routes, omsInputValue] = useStore((states) => [
    states.currentRoute,
    states.routes,
    states.omsInputValue,
  ]);
  console.info("[read-hacker-news] route", currentRoute());

  const isFrontPage = currentRoute() === "read-hacker-news-front-page";
  const { data, error } = useSWR(
    isFrontPage
      ? "https://api.hackerwebapp.com/news"
      : "https://hn.algolia.com/api/v1/search_by_date?tags=show_hn",
    () => {
      if (isFrontPage) {
        return fetchHN();
      }
      return fetchShowHN();
    }
  );
  if (error) {
    <Suggestions>
      <Suggestion
        suggestion={{ id: "error", type: "no-op", title: "Error..." }}
      />
    </Suggestions>;
  }
  if (!data) {
    <Suggestions>
      <Suggestion
        suggestion={{ id: "loading", type: "no-op", title: "Loading..." }}
      />
    </Suggestions>;
  }
  return (
    <Suggestions>
      {data?.map((article) => (
        <Suggestion suggestion={article} />
      ))}
    </Suggestions>
  );
}
interface HackerNewArticle {
  id: number;
  title?: string;
  points?: number;
  user?: string;
  time?: number;
  time_ago?: string;
  comments_count?: number;
  type?: string;
  url?: string;
  domain?: string;
}

async function fetchHN(): Promise<OMSExtension[]> {
  try {
    const response: HackerNewArticle[] = await fetch(
      `https://api.hackerwebapp.com/news`
    ).then((data) => data.json());
    return response.map((article) => ({
      id: `hn-${article.id}`,
      title: article.title || article.domain || "",
      type: "url",
      url: article.url,
      secondLineTitle: `👍  ${article.points} points by ${article.user} ${article.time_ago} | 💬  ${article.comments_count}`,
      subTitle: article.domain,
    }));
  } catch (error) {
    console.error("[read-hacker-news]", error);
    return Promise.resolve([]);
  }
}

async function fetchShowHN(): Promise<OMSExtension[]> {
  try {
    const response: HackerNewsAlgoliaResponse = await fetch(
      "https://hn.algolia.com/api/v1/search_by_date?tags=show_hn"
    ).then((data) => data.json());
    return response.hits.map((hit) => ({
      id: `hn-${hit.objectID}`,
      title: hit.title,
      type: "url",
      url: hit.url,
      secondLineTitle: `👍  ${hit.points} points by ${hit.author} | 💬  ${hit.num_comments}`,
    }));
  } catch (error) {
    console.error("[read-hacker-news]", error);
    return Promise.resolve([]);
  }
}

interface HackerNewsAlgoliaResponse {
  hits: Hit[];
  // nbHits: number;
  // page: number;
  // nbPages: number;
  // hitsPerPage: number;
  // exhaustiveNbHits: boolean;
  // exhaustiveTypo: boolean;
  // query: string;
  // params: string;
  // processingTimeMS: number;
}

export interface Hit {
  created_at: string;
  title: string;
  url?: string;
  author: string;
  points: number;
  story_text?: string;
  comment_text: any;
  num_comments: number;
  parent_id: any;
  created_at_i: number;
  _tags: string[];
  objectID: string;
  _highlightResult: HighlightResult;
}

export interface HighlightResult {
  title: Title;
  url?: Url;
  author: Author;
  story_text?: StoryText;
}

export interface Title {
  value: string;
  matchLevel: string;
  matchedWords: any[];
}

export interface Url {
  value: string;
  matchLevel: string;
  matchedWords: any[];
}

export interface Author {
  value: string;
  matchLevel: string;
  matchedWords: any[];
}

export interface StoryText {
  value: string;
  matchLevel: string;
  matchedWords: any[];
}
