import React from "react";
import "../styles.css";
import { Button, Card, Spin } from "antd";
import { News, useGetNewsQuery, useTapNewsMutation } from "../../slice/NewsApi";
import { ClockCircleOutlined, FireOutlined } from "@ant-design/icons";

const formatTime = (s: string) => {
  const d = new Date(s + "Z");
  return d.toLocaleString();
};

const NewsListCard = (): JSX.Element => {
  const { data, refetch, isLoading } = useGetNewsQuery({});
  const [tapNews] = useTapNewsMutation();
  return (
    <div className="card">
      <Spin spinning={isLoading}>
        {data &&
          data.map((news: News) => (
            <Card
              title={news.title}
              key={news.id}
              style={{ width: "100%", marginBottom: "1rem" }}
              bordered={false}
            >
              <p
                style={{
                  textAlign: "left",
                  whiteSpace: "break-spaces",
                }}
              >
                {news.content}
              </p>
              <br />
              <div
                className="news-footer"
                style={{
                  width: "100%",
                  display: "flex",
                  justifyContent: "space-between",
                }}
              >
                <div
                  style={{
                    display: "flex",
                    flexDirection: "row",
                  }}
                >
                  <ClockCircleOutlined />
                  <br />
                  <p style={{ marginLeft: "1rem" }}>
                    {formatTime(news.created)}
                  </p>
                </div>
                <div
                  style={{
                    height: "100% !important",
                    display: "flex",
                    flexFlow: "column",
                    justifyContent: "center",
                  }}
                >
                  <Button
                    icon={<FireOutlined />}
                    onClick={() => {
                      tapNews(news.id);
                      refetch();
                    }}
                  >{` ${news.taps}`}</Button>
                </div>
              </div>
            </Card>
          ))}
      </Spin>
    </div>
  );
};
export default NewsListCard;
