'use client'
import { BlogEntity, BlogEntityResponseCollection, ComponentSharedTagsDev } from '@/generated/types'
import { GET_BLOGS_LIST } from '@/graphql/documents/blogs.graphql'
import styles from "./blog.module.scss";
import Link from "next/link";
import { QueryResult, useQuery } from '@apollo/client'
import { ListBulletIcon, TableCellsIcon } from "@heroicons/react/24/solid";
import { useEffect, useState } from 'react'
import { BlogsData } from '../../app/[lng]/blogs/page'
import { formatDate } from "./services";
import Paginate from './pagination'

type BlogsProps = {
  blogs: BlogEntityResponseCollection
  isLoad?: boolean
  lng: string,
}

type RootBlogsProps = {
  params: BlogsProps
}

export default function Blog({ params: { lng, blogs } }: RootBlogsProps) {
  const [isShowList, setIsShowList] = useState(false)
  const [blogsItem, setBlogsItem] = useState<BlogEntityResponseCollection>()
  const [pageSize, setPageSize] = useState(12)
  const [locale, setLocale] = useState(lng)
  const [pagination, setPagination] = useState({ page: 1, pageSize: 12 })
  const [numberPage, setNumberPage] = useState<number>(0)

  const { data, refetch }: QueryResult<BlogsData> = useQuery<BlogsData>(
    GET_BLOGS_LIST,
    {
      variables: { locale, pagination },
    },
  )

  async function getOtherPage(index: any) {
    setNumberPage(index)
    refetch({ locale: lng, pagination: { page: index, pageSize: 12 } })
  }  

  const toggleList = () => {
    setIsShowList(!isShowList);
  };

  const language = `${lng === "fr" ? lng + "-FR" : lng + "-GB"}`;

  useEffect(() => {
    if (blogs.data.length > 0) {
      setPageSize(blogs.meta.pagination.pageSize)
      setBlogsItem(blogs)
    }
  }, [blogs.meta])

  useEffect(() => {
    setBlogsItem(data?.blogs)
    setPageSize(data?.blogs?.meta.pagination.pageSize || 0)
  }, [data])

  const renderElements = () => {
    const rows = [];
    const totalRows = Math.ceil((blogsItem?.data?.length?? 0) / 3 );

    for (let i = 0; i < totalRows; i++) {
      const startIndex = i * 3;
      const row = blogsItem?.data.slice(startIndex, startIndex + 3);
      rows.push(row);
    }

    return rows.map((row, rowIndex) => (
      <div key={rowIndex + `blogs`} className="grid">
        <div className="flex">
          {row?.map((blog: BlogEntity, index: number) => (
            <Link
              className="relative w-1/3 mx-1.5 my-1.5"
              key={index + `${blog.attributes?.slugUrl}`}
              href={`${blog.attributes?.slugUrl}`}
            >
              <div
                key={index}
                className="relative h-64"
                style={{
                  position: "relative",
                  backgroundImage: `url(${blog.attributes?.image?.data?.attributes?.url})`,
                  backgroundSize: "cover",
                  backgroundPosition: "center",
                }}
              >
                <div
                  className="absolute inset-0 bg-gradient-to-b from-transparent to-gray-500"
                  style={{ opacity: 0.75 }}
                ></div>
                <div className={`absolute top-28 left-5`}>
                  <div className="flex mb-2">
                    {blog.attributes?.tags?.map(
                      (
                        tag: ComponentSharedTagsDev | null | undefined,
                        index: number
                      ) => {
                        if (tag) {
                          return (
                            <p
                              key={index + `${tag?.name}`}
                              className={`${styles.date} mx-2 px-3 py-0.5 text-sm rounded-lg text-gray-950 bg-white`}
                            >
                              {tag?.name}
                            </p>
                          );
                        }
                        return null;
                      }
                    )}
                  </div>
                  <h1
                    className={`${styles.title_blogItem} text-2xl font-bold text-white`}
                  >
                    {blog.attributes?.title}
                  </h1>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </div>
    ));
  };

  return (
    <section style={{
      position: "relative",
      backgroundPosition: "0px 0px, 50% 50%",
      backgroundSize: "auto, cover",
      height: "auto",
      width: "100%",
    }} >
      <div className="mx-10 lg:mx-20 xl:mx-36 mt-24">
        <div className="flex w-full justify-between mr-36">
          <h3
            className={`${styles.title_blogItem} text-center lg:text-left left:pl-32 pt-10 mx-5 pb-5 text-blue-400 text-3xl`}
          >
            Le Blog
          </h3>
          <button onClick={toggleList} className="lg:mr-20">
            {isShowList ? (
              <TableCellsIcon
                className="block h-8 w-8 mt-10"
                aria-hidden="true"
              />
            ) : (
              <ListBulletIcon
                className="block h-8 w-8 mt-10"
                aria-hidden="true"
              />
            )}
          </button>
        </div>
        <div className="mx-8 lg:mx-20">
          {isShowList ? (
            <div className="grid w-full">
              {blogsItem?.data &&
                blogsItem?.data?.length > 0 &&
                blogsItem?.data?.map((blog: BlogEntity, index: number) => {
                  const date = blog?.attributes?.createdAt;
                  return (
                    <Link
                      key={index + `${blog.attributes?.title}` + "index"}
                      href={`${blog.attributes?.slugUrl}`}
                    >
                      <div className=" grid mb-5 w-full sm:flex justify-between">
                        <div
                          className="sm:w-1/4 h-36"
                          style={{
                            backgroundImage: `url(${blog.attributes?.image?.data?.attributes?.url})`,
                            backgroundSize: "100% 100%",
                          }}
                        ></div>
                        <div className="sm:w-3/4 px-5 ">
                          <h1
                            className={` ${styles.date} text-sm mt-3 text-gray-950`}
                          >
                            {formatDate(date, language)}
                          </h1>
                          <div className="flex">
                            {blog.attributes?.tags?.map(
                              (
                                tag: ComponentSharedTagsDev | null | undefined,
                                index: number
                              ) => {
                                if (tag) {
                                  return (
                                    <p
                                      key={index + `${tag?.name}`}
                                      className={`${styles.date} mx-2 px-3 py-1 rounded-lg bg-gray-200 text-gray-950`}
                                    >
                                      {tag?.name}
                                    </p>
                                  );
                                }
                                return null; // Si le tag est null ou undefined, retournez null ou ne renvoyez rien
                              }
                            )}
                          </div>
                          <h1
                            className={`${styles.title_blogItem} text-gray-900 mt-1 text-2xl`}
                          >
                            {blog.attributes?.title}
                          </h1>
                        </div>
                      </div>
                    </Link>
                  );
                })}
            </div>
          ) : (
            <div>
              <div className="hidden lg:block">{renderElements()}</div>
              <div className="grid w-full lg:hidden">
                {blogsItem?.data &&
                  blogsItem?.data?.length > 0 &&
                  blogsItem?.data?.map((blog: BlogEntity, index: number) => {
                    return (
                      <Link
                        href={`${blog.attributes?.slugUrl}`}
                        key={index + `${blog.attributes?.slugUrl}`}
                      >
                        <div
                          className=" relative sm:w-full h-40 w-full mr-10 mb-4 rounded-sm"
                          style={{
                            backgroundImage: `url(${blog.attributes?.image?.data?.attributes?.url})`,
                            backgroundSize: "100% 100%",
                          }}
                        >
                          <div className="absolute top-14 left-6 flex">
                            {blog.attributes?.tags?.map(
                              (
                                tag: ComponentSharedTagsDev | null | undefined,
                                index: number
                              ) => {
                                if (tag) {
                                  return (
                                    <p
                                      key={index + `${tag?.name}`}
                                      className={`${styles.date} mx-2 px-4 py-0.5 text-sm rounded-lg text-gray-950 bg-white`}
                                    >
                                      {tag?.name}
                                    </p>
                                  );
                                }
                                return null;
                              }
                            )}
                          </div>
                          <h1
                            className={`${styles.title_blogItem} absolute left-6 top-24 text-white text-xl`}
                          >
                            {blog.attributes?.title}
                          </h1>
                        </div>
                      </Link>
                    );
                  })}
              </div>
            </div>
          )}
        </div>
        <div className="my-4 flex flex-col items-center justify-center text-center">
        <Paginate
          nPages={blogsItem?.meta.pagination.pageCount || 0}
          currentPage={blogsItem?.meta.pagination.page || 1}
          setCurrentPage={getOtherPage}
        />
        </div>
      </div>
    </section>
  )
}
