"use client";
import {
  ComponentSharedTagsDev,
  ProjectEntity,
  ProjectEntityResponseCollection,
} from "@/generated/types";
import { GET_PROJECT_LIST } from "@/graphql/documents/projects.graphql";
import Link from "next/link";
import { QueryResult, useQuery } from "@apollo/client";
import { useEffect, useState } from "react";
import { ProjectData } from "../../app/[lng]/achievements/page";
import Paginate from "../blog/pagination";
import styles from "./achievement.module.scss";
import { formatDate } from "../blog/services";
import { useTranslation } from "../../app/i18n";

type ProjectsProps = {
  projects: ProjectEntityResponseCollection;
  lng: string;
};

type TranslationFunction = (key: string) => string;

type RootProjectsProps = {
  params: ProjectsProps;
};

export default function Projects({
  params: { lng, projects },
}: RootProjectsProps) {
  const [projectsItem, setProjectsItem] =
    useState<ProjectEntityResponseCollection>();
  const [pageSize, setPageSize] = useState(10);
  const [isLoad, setIsLoad] = useState(true)
  const [t, setT] = useState<TranslationFunction | null>(null);
  const [i18n, setI18n] = useState(null);
  const [locale, setLocale] = useState(lng)
  const [pagination, setPagination] = useState({ page: 1, pageSize: 10 });
  const [numberPage, setNumberPage] = useState<number>(0);

  const { data, refetch }: QueryResult<ProjectData> = useQuery<ProjectData>(
    GET_PROJECT_LIST,
    {
      variables: { locale, pagination },
    }
  );

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

  useEffect(() => {
    if (projects.data.length > 0) {
      setPageSize(projects.meta.pagination.pageSize);
      setProjectsItem(projects);
      setIsLoad(false)
    }
  }, [projects.meta]);

  useEffect(() => {
    setProjectsItem(data?.projects);
    setPageSize(data?.projects?.meta.pagination.pageSize || 0);
  }, [data]);

  useEffect(() => {
    const fetchTranslate = async () => {
      const { t, i18n } = await useTranslation(lng, "second-page");
      setT(() => t);
      setI18n(i18n);
    };
    fetchTranslate();
  }, [lng]);  

  if (!t || !i18n) {
    return null;
  }

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

  return (
    <>
     {isLoad ? (
        <>
        <div
        style={{
          position: "relative",
          backgroundColor : "white",
          height: "100vh",
          width: "100%",
          top: "96px",
        }}
      ></div>
        </>
     ): (
      <>
       <div
        style={{
          position: "relative",
          backgroundImage: `linear-gradient(180deg, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url('/assets/static/images/back_1.jpg')`,
          backgroundPosition: "0px 0px, 50% 50%",
          backgroundSize: "auto, cover",
          height: "39vh",
          width: "100%",
          top: "96px",
        }}
      >
        <div
          className={`hidden sm:block absolute w-auto sm:top-56 2xl:top-72 left-16 right-16 bg-white`}
        >
          <h1
            className={`${styles.title_projectItem} sm:mx-20 my-5 mb-14 text-2xl xl:text-4xl items-center text-center text-gray-950`}
          >
            {t("achievements_list")}
          </h1>
        </div>
      </div>
      <div
        className="bg-white"
        style={{
          height: "auto",
        }}
      >
        <div className=" mx-8 mt-36 lg:mt-44 sm:mx-20 lg:mx-36 ">
          <div className="sm:hidden">
            <h1
              className={`${styles.title_projectItem} sm:mx-20 my-5 font-bold text-2xl xl:text-4xl items-center text-center text-gray-950`}
            >
              {t("achievements_list")}
            </h1>
          </div>
          <h1
            className={`${styles.project_titleItem} text-center items-center sm:text-left sm:ml-0.5`}
          >
            {t("achievements_title")}
          </h1>
          <div className="grid">
            {projectsItem &&
              projectsItem?.data.length > 0 &&
              projectsItem?.data.map(
                (projet: ProjectEntity, index: number) => {
                  const length =
                    projet?.attributes?.subDescriptions?.length ?? 0;
                  const date = projet?.attributes?.createdAt;
                  return (
                    <div
                      key={index}
                      className="flex w-full flex-col md:flex-row mb-5"
                    >
                      <div className=" w-2/3 order-2 md:order-1 md:mr-2 sm:mr-0">
                        <h1
                          className={` ${styles.date} text-sm ml-2 mt-3 text-gray-950`}
                        >
                          {formatDate(date, language)}
                        </h1>
                        <div className="flex">
                          {projet.attributes?.tags?.map(
                            (
                              tag: ComponentSharedTagsDev | null | undefined,
                              index: number
                            ) => {
                              if (tag) {
                                return (
                                  <p
                                    key={index + `${tag?.name}`}
                                    className={`${styles.date} px-4 mx-1.5 py-0.5 text-sm rounded-lg bg-gray-200 text-gray-950`}
                                  >
                                    {tag?.name}
                                  </p>
                                );
                              }
                              return null;
                            }
                          )}
                        </div>
                        <h1
                          className={` ${styles.descriptionItem} font-bold text-xl mb-5 text-gray-950`}
                        >
                          {projet?.attributes?.title}
                        </h1>
                        <h1
                          className={` ${styles.descriptionItem} text-lg my-5 text-gray-700`}
                        >
                          {length > 250
                            ? projet.attributes?.subDescriptions?.slice(
                                0,
                                250
                              ) + "..."
                            : projet.attributes?.subDescriptions}
                        </h1>
                        <div className=" w-48 mt-4 ml-1.5 inline-block">
                          <Link href={`${projet.attributes?.slugUrl}`}>
                            <p
                              className={` ${styles.button} px-4 w-auto text-center text-gray-950 hover:text-white hover:bg-gray-800 font-semibold py-1.5 border-2 border-gray-950 rounded-full`}
                            >
                              {t("read_more")}
                            </p>
                          </Link>
                        </div>
                      </div>
                      <div
                        className=" order-1 md:order-2 md:mx-10 w-36 h-36 md:w-72 md:h-64"
                        style={{
                          backgroundImage: `url(${projet.attributes?.image?.data?.attributes?.url})`,
                          backgroundSize: "100% 100%",
                        }}
                      ></div>
                    </div>
                  );
                }
              )}
          </div>
          <div className="my-4 flex flex-col items-center justify-center text-center">
            <Paginate
              nPages={projectsItem?.meta?.pagination?.pageCount || 0}
              currentPage={projectsItem?.meta?.pagination?.page || 1}
              setCurrentPage={getOtherPage}
            />
          </div>
        </div>
      </div>
      </>
     )}
    </>
  );
}
