'use client'

import React, { useEffect, useRef, useState } from 'react';



import service from '@/lib/http/service';
import toast from 'react-hot-toast';
import { Button } from '../ui/button';
import { useRouter } from 'next/navigation';
import { Loading, LoadingView } from '../ui/loading';
import { Pagination } from 'antd';
// import Pagination from './ui/pagination';



import { Card, QACard, TagsViews } from './card';
import { FadeIn } from '../landing/fade-in';
import { AnimatedList, ArticleList } from '../landing/animated-list';
import { useTranslation } from 'react-i18next';

const PageSize = 12

interface DataItem {
  image: string;
  title: string;
  time: string;
  summary: string;
  category: string;
}


export interface TagItem {
  name: string;
  value: string;
}


export interface ArticleData {
  id: number;
  org_id: number;
  spider_id: number;
  p_name: string;
  tag: string;
  category: string;
  main_title: string;
  sub_title: string;
  summary: string;
  keywords: string[] | string;
  seo_keywords: string[] | string;
  tags: string[];
  url: string;
  image_url: string;
  logo_url: string;
  content: string;
  is_hotspot: boolean;
  is_overwritten: boolean;
  is_deleted: boolean;
  is_replicate: boolean;
  is_pushed: boolean;
  created_time: string;
  updated_time: string;
  extra_data: {
    logs: any | null;
  };
}

export interface LodingInfo {
  total?: number;
  loding: boolean;
  current: number;
  pageSize: number;
}



export interface QAData {
  id: number;
  org_id: number;
  question: string;
  answer: string;
  state: number;
  is_overwritten: boolean;
  is_replicate: boolean;
  is_deleted: boolean;
  created_time: string;
  updated_time: string;
  extra_data: {
    logs: any | null;
  };
}

interface NineGridProps {
  // data: DataItem[];
  categoriesRef: React.MutableRefObject<TagItem[]>
}

const NineGrid: React.FC<NineGridProps> = ({
  categoriesRef
}) => {

  const { t, i18n } = useTranslation()

  const language = i18n.language

  const [selectedCategory, setSelectedCategory] = useState(categoriesRef.current[0].value);

  const [articleDataList, setArticleDataList] = useState([]);
  const [currentPage, setCurrentPage] = React.useState(0);

  const [isQA, setIsQA] = useState(false);
  const [qaData, setQaData] = useState([]);
  // const [totalPages, setTotalPages] = useState(0);
  // const [totalPagesQA, setTotalPagesQA] = useState(0);
  const [currentPageQA, setCurrentPageQA] = React.useState(0);

  const [initLoading, setInitLoading] = useState<boolean>(false);

  const [paginationConfig, setPaginationConfig] = useState({
    pageSize: PageSize, // Number of items per page
    current: 1,   // Current page number
    total: 0, // Total number of items

    // Optional: You can customize other pagination options as needed
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '30', '40'],
  })

  const [paginationConfigQA, setPaginationConfigQA] = useState({
    pageSize: PageSize, // Number of items per page
    current: 1,   // Current page number
    total: 0, // Total number of items

    // Optional: You can customize other pagination options as needed
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '30', '40'],
  })

  // const [lodingInfos, setLodingInfos] = useState<LodingInfo[]>([
  //   { total: 0, loding: true, current: 1, pageSize: 10 },
  //   { total: 0, loding: true, current: 1, pageSize: 10 },
  //   { total: 0, loding: true, current: 1, pageSize: 10 },
  // ]);

  const getQAList = async (current: number) => {

    if (initLoading) return


    setInitLoading(true);
    await service.post('/api/v1/qa/list', {
      language,
      "page_no": current - 1,
      "page_size": PageSize
    }, {
      headers: {
        // 'Authorization': token
      }
    }).then(function (result: any) {
      setInitLoading(false);
      console.log("result:", result)

      if (result && result.header.code != 0) {

        toast.error(result.header.message)
        return
      }

      setQaData(result.data.list);
      // setTotalPagesQA(result.header.total)

      setPaginationConfigQA((prevConfig) => ({
        ...prevConfig,

        // pageSize: 10,
        current: current,
        total: result.header.total,
      }));

    }).catch((err) => {
      setInitLoading(false);
      console.log(err);
      // if (err.errors[0].code === "form_identifier_not_found") {
      //   props.setAccountNotFound(true);
      //   props.email(email);
      // } else {
      //   props.setError("Sorry, We couldn't sign you in. Please try again later");
      // }
    });
  };

  async function getNewListFunc(tag: string, current: number) {


    if (initLoading) return

    setInitLoading(true);

    tag = tag == categoriesRef.current[0].value ? "" : tag


    await service.post('/api/v1/news/list', {
      "id": 0,
      language,
      // "tag": selectedCategory == categories[0] ? "" : selectedCategory, // #Blockchain
      "tag": tag,
      "page_no": current - 1,
      "page_size": PageSize
    }, {
      headers: {
        // 'Authorization': token
      }
    }).then(function (result: any) {


      // if (isMounted) {
      console.log("result:", result)

      if (result && result.header.code != 0) {

        toast.error(result.header.message)
        return
      }

      setArticleDataList(result.data.list);
      // setTotalPages(result.header.total)

      setPaginationConfig((prevConfig) => ({
        ...prevConfig,

        // pageSize: 10,
        current: current,
        total: result.header.total,
      }));

      setInitLoading(false);
      // }


    }).catch((err) => {
      setInitLoading(false);
      console.log(err);
      // if (err.errors[0].code === "form_identifier_not_found") {
      //   props.setAccountNotFound(true);
      //   props.email(email);
      // } else {
      //   props.setError("Sorry, We couldn't sign you in. Please try again later");
      // }
    });
  }

  useEffect(() => {
    let isMounted = true

    getNewListFunc("", 1)


    return () => {
      isMounted = false
    }
  }, [currentPage, selectedCategory])


  useEffect(() => {
    let isMounted = true

    getQAList(1)


    return () => {
      isMounted = false
    }
  }, [currentPageQA])

  const handlePageChange = (pageNumber: number) => {
    console.log("handlePageChange", pageNumber)
    setCurrentPage(pageNumber);
  };

  const handlePageChangeQA = (pageNumber: number) => {
    console.log("handlePageChangeQA", pageNumber)
    setCurrentPageQA(pageNumber);
  };

  return (
    <div style={{
      // width: '70%', 
      // margin: '0 auto' 
    }}
      className='w-[80%] m-auto'
    >
      <TagsViews
        categoriesRef={categoriesRef}
        isQA={isQA}
        selectedCategory={selectedCategory}
        onChange={(category) => {
          setIsQA(false)
          setCurrentPage(0);
          setSelectedCategory(category)

          console.log("===onChange===", category)

          getNewListFunc(category, 1)
        }}

        onClickQA={() => {
          setIsQA(true)
          getQAList(1)

        }}

      />

      {
        !initLoading ? (!isQA ?
          <div className=' lg:p-[0rem]'>
            <div
              // style={{
              //   display: 'grid',
              //   gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
              //   gap: '16px',
              // }}
              className='p-[1rem] mb-[6rem] grid grid-cols-1 gap-8 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-3'
            >
              {articleDataList.map((item: ArticleData, index) => {
                return <ArticleList key={index} className="">
                  <Card {...item} />
                </ArticleList>
              })}

            </div>


            <div
              className=' flex items-center  justify-center lg:justify-center'
              style={{
                // display: "flex",
                // alignItems: "center",
                // justifyContent: "right",
                // padding: "40px 0"
              }}
            >
              <Pagination
                current={paginationConfig.current}
                pageSize={paginationConfig.pageSize}
                showSizeChanger={false}
                showTotal={(total, range) => t("show_total", { total })}
                // pageSizeOptions={[10, 20, 50, 100]}
                // onShowSizeChange={(current, size) => {
                //   console.log("onShowSizeChange: ", current, size)

                //   setTimeout(() => {
                //     setLodingInfos(prevState => {
                //       const newState = [...prevState];
                //       // newState[index].loding = true;
                //       paginationConfig.current = 1;
                //       paginationConfig.pageSize = size;
                //       return newState;
                //     });
                //   }, 0)



                // }}
                total={paginationConfig.total}

                // showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`}

                onChange={(page) => {
                  console.log("onChange page:", page);


                  setPaginationConfig(prevConfig => ({
                    ...prevConfig,
                    current: page,
                    // pageSize: pageSize
                  }));

                  getNewListFunc(selectedCategory, page)


                }}
                defaultPageSize={10}
                defaultCurrent={1}
              />
            </div>


          </div>

          : <div className=' lg:p-[0rem] '>
            <div
              style={{

                // display: 'grid',
                // gridTemplateColumns: 'repeat(auto-fill, minmax(450px, 1fr))',
                // gap: '16px',
              }}

              className='p-[1rem] lg:p-[1.5rem] lg:mb-[10rem] grid grid-cols-1 gap-8 lg:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-3 '
            >
              {qaData.map((qa: QAData, index) => {
                return <AnimatedList key={index}>
                  <QACard  {...qa} />
                </AnimatedList>
              })}

            </div>
            <div
              className=' flex items-center justify-center lg:justify-center'
              style={{
                // display: "flex",
                // alignItems: "center",
                // justifyContent: "right",
                // padding: "40px 0"
              }}
            >
              <Pagination
                current={paginationConfigQA.current}
                pageSize={paginationConfigQA.pageSize}
                showSizeChanger={false}
                showTotal={(total, range) => t("show_total", { total })}
                // pageSizeOptions={[10, 20, 50, 100]}
                // onShowSizeChange={(current, size) => {
                //   console.log("onShowSizeChange: ", current, size)

                //   setTimeout(() => {
                //     setLodingInfos(prevState => {
                //       const newState = [...prevState];
                //       // newState[index].loding = true;
                //       paginationConfig.current = 1;
                //       paginationConfig.pageSize = size;
                //       return newState;
                //     });
                //   }, 0)



                // }}
                total={paginationConfigQA.total}

                // showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`}

                onChange={(page) => {
                  console.log("onChange page:", page);

                  setPaginationConfigQA(prevConfig => ({
                    ...prevConfig,
                    current: page,
                    // pageSize: pageSize
                  }));

                  getQAList(page)


                }}
                defaultPageSize={10}
                defaultCurrent={1}
              />
            </div>
          </div>) : <LoadingView />
      }

    </div>
  );
};

const Article = () => {
  const { t, i18n } = useTranslation()

  console.log("-----i18n-----", i18n.language)

  const language = i18n.language

  // const defCategories: TagItem[] = [
  //   { name: t("article.all"), value: "" }
  // ]

  const defCategories: TagItem[] = [
  ]

  const categoriesRef = useRef(defCategories);

  const [initLoading, setInitLoading] = useState<boolean>(false);
  const [initTags, setInitTags] = useState<boolean>(false);

  useEffect(() => {
    let isMounted = true

    async function initFunc() {
      await service.post('/api/v1/tag/list', {
      }, {
        headers: {
          // 'Authorization': token
        }
      }).then(function (result: any) {


        console.log("result:", result)

        if (result && result.header.code != 0) {

          toast.error(result.header.message)
          return
        }

        // categoriesRef.current.values


        const tags = result.data.list

        // getNewListFunc(1)

        let listTmp = defCategories

        for (let index = 0; index < tags.length; index++) {
          const element = tags[index];

          console.log(element)

          // categoriesRef.current = [...categoriesRef.current, element.name];
          if (language == 'en') {
            listTmp = [...listTmp, {
              name: element.name,
              value: element.name,
            }];
          } else if (language == 'zh-CN') {
            listTmp = [...listTmp, {
              name: element.name_cn,
              value: element.name,
            }];
          } else {
            listTmp = [...listTmp, {
              name: element.name,
              value: element.name,
            }];
          }


        }

        categoriesRef.current = listTmp


        setInitTags(true)



      }).catch((err) => {
        setInitLoading(false);
        console.log(err);

      });
    }

    initFunc()

    return () => {
      isMounted = false
    }
  }, [])

  return (
    <div className='min-h-[25rem] w-full'>
      <FadeIn >
        <h3 className='text-center text-[1.25rem] lg:text-[2.25rem] font-bold py-8'>{t("article.hot_hrends")}</h3>
      </FadeIn>

      {
        initTags && <NineGrid
          categoriesRef={categoriesRef}
        />
      }
    </div>
  )

};

export default Article;