"use client";
import { getToken } from "@/actions/cookies";
import fetchData from "@/api/fetch-data";
import Loading from "@/app/loading";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import AlertWarning from "../shared/AlertWarning";
import LinkButton from "./LinkButton";
import LinkInput from "./LinkInput";

export default function ChooseLink() {
  const locale = useLocale();
  const t = useTranslations("affiliate");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [error, setError] = useState(null);
  const [data, setData] = useState([]);
  const e = useTranslations();
  const [isAffiliateLoading, setIsAffiliateLoading] = useState(false);
  // const [isAffiliateError, setIsAffiliateError] = useState(null);

  useEffect(() => {
    (async () => {
      setIsAffiliateLoading(true);
      const { data, error, pagination } = await fetchData({
        endPoint: "/user/getLink?page=" + currentPage,
        locale,
      });
      if (error) {
        setIsAffiliateLoading(false);
        setError(error);
      } else {
        setIsAffiliateLoading(false);
        setData(data);
        setCurrentPage(pagination.current_page);
        setTotalPages(pagination.last_page);
      }
    })();
  }, [currentPage, locale]);

  const handlePageChange = (page) => {
    if (page > 0 && page <= totalPages) {
      setCurrentPage(page);
    }
  };
  if (isAffiliateLoading) return <Loading />;

  if (error) {
    return <AlertWarning text={"Failed to fetch data"} />;
  }
  // if (data.length == 0) return <AlertWarning text={e("nodata")} />;

  return (
    <div className=" overflow-x-auto lg:space-y-7">
      <LinkInput />
      <Table className="min-w-full">
        <TableHeader className="bg-light py-4 md:py-6 text-white">
          <TableRow className="font-extrabold">
            <TableHead className="font-bold text-base max-md:text-sm md:text-xl   text-center text-black">
              {t("id")}
            </TableHead>
            <TableHead className="font-bold text-base max-md:text-sm md:text-xl  text-center text-black">
              {t("product_name")}
            </TableHead>
            <TableHead className="font-bold text-base max-md:text-sm md:text-xl  text-center text-black">
              {t("stock")}
            </TableHead>
            <TableHead className="font-bold text-base max-md:text-sm md:text-xl  text-center text-black">
              {t("sales")}
            </TableHead>
            <TableHead className="font-bold text-base max-md:text-sm md:text-xl  text-center text-black">
              {t("link")}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody className="cursor-pointer">
          {data.map((invoice, index) => (
            <TableRow
              key={index}
              className="text-base  md:text-lg lg:shadow-lg"
            >
              <TableCell className="lg:tracking-[.25em] py-2 md:py-4 text-center">
                <h4>{invoice.id}</h4>
              </TableCell>
              <TableCell className="py-2 md:py-4 text-center">
                <span className=" mx-2 text-md">{invoice.title}</span>
              </TableCell>
              <TableCell className="lg:tracking-[.25em] py-2 md:py-4 text-center">
                <h4>{invoice.stocks}</h4>
              </TableCell>
              <TableCell className="lg:tracking-[.25em] py-2 md:py-4 text-center">
                <h4>{invoice.sales}</h4>
              </TableCell>
              <TableCell className=" md:py-4 text-center">
                <LinkButton text={t("copy-link")} link={invoice.link} />
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {/* Pagination */}
      <div className="flex justify-center mt-4">
        <button
          onClick={() => handlePageChange(currentPage - 1)}
          className="px-4 py-2 border rounded-md"
          disabled={currentPage == 1}
        >
          {t("prev")}
        </button>
        <span className="mx-4  flex items-center">
          {t("page")} {currentPage} {t("of")} {totalPages}
        </span>
        <button
          onClick={() => handlePageChange(currentPage + 1)}
          className="px-4 py-2 border rounded-md"
          disabled={currentPage == totalPages}
        >
          {t("next")}
        </button>
      </div>
    </div>
  );
}
