"use client";

import React, { useState, useEffect } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import Nav from "@/components/Nav";
import Footer from "@/components/Footer";
import styles from "./insightList.module.scss";
import { fetchArticleList, buyArticle } from "@/lib/cmsForPayment";

interface ArticleType {
  id: number;
  title?: string | null;
  digest?: string | null;
  author?: string | null;
  type?: string | null;
  content?: string | null;
  cover: string;
  payed: boolean;
  order?: number | null;
  status?: string | null;
  createTime?: Date | null;
  updateTime?: Date | null;
}

const InsightList: React.FC = () => {
  const router = useRouter();
  const [insightList, setInsightList] = useState<ArticleType[] | null>(null);
  useEffect(() => {
    fetchArticleList(999, 1, 100).then(({ data: list }) => {
      const records = [...list?.records];
      setInsightList(records);
    });
  }, []);

  const buy = (event: React.MouseEvent, id: number) => {
    event.preventDefault();
    buyArticle(id).then((data) => {
      if (data.code == 200) {
        const newWindow = window.open("", "_self");
        newWindow?.document.write(data.data);
        newWindow?.focus();
      } else if (data.code == 3008) {
        router.push("/user/login");
      }
    });
    return false;
  };

  return (
    <>
      <div className={styles.container}>
        <Nav title={"行业洞察"} />
        <div className={styles.content}>
          <div className={styles.articleList}>
            {insightList?.map((item: ArticleType, index: number) => {
              return (
                <a href={`/insightDetail/${item.id}.html`} key={index}>
                  <div className={styles.articleItem}>
                    <Image alt="pic" width={315} height={212} className={styles.articleImg} src={item?.cover} />

                    <div className={styles.articleText}>
                      <div className={styles.articleTitle}>
                        {item?.title}
                        {!item?.payed && (
                          <span className={styles.payment} onClick={(event) => buy(event, item?.id)}>
                            付费：1元
                          </span>
                        )}
                        {item?.payed && <span className={styles.payed}>已付费</span>}
                      </div>
                      <div className={styles.articleContent}>{item?.digest}</div>
                    </div>
                  </div>
                </a>
              );
            })}
          </div>
        </div>
        <Footer />
      </div>
    </>
  );
};
export default InsightList;
