"use client";

import { useEffect, useState } from "react";
import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import Link from "next/link";
import { useTranslation } from "react-i18next";

type CommentedCourse = {
  _id: string;
  comment?: string;
  course_id?: { _id: string; cuorse_name?: string } | null;
};

function AcademyCommentsPage() {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [items, setItems] = useState<CommentedCourse[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    request<{ data: { comments: CommentedCourse[] } }>(
      "GET",
      "/academy/user/comments?page=1&limit=50",
      null,
      { noToast: true }
    )
      .then((res) => setItems(res?.data?.comments || []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, [request]);

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.activity.items.academyComments")}</PageTitle>
        <div className="my-6">
          {loading ? (
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <div
                  key={i}
                  className="h-14 animate-pulse rounded-xl bg-neutral-200 dark:bg-neutral-800"
                />
              ))}
            </div>
          ) : items.length === 0 ? (
            <p className="py-10 text-center text-sm text-neutral-500">
              {t("models.nothingFound")}
            </p>
          ) : (
            <ul className="space-y-1">
              {items
                .filter((item) => item.course_id)
                .map((item) => (
                  <li key={item._id}>
                    <Link
                      href={`/explore/${item.course_id?._id}`}
                      className="block rounded-xl px-2 py-3 hover:bg-neutral-100 dark:hover:bg-neutral-800"
                    >
                      <p className="truncate text-sm font-bold">
                        {item.course_id?.cuorse_name}
                      </p>
                      {item.comment ? (
                        <p className="mt-0.5 truncate text-xs text-neutral-500">
                          {item.comment}
                        </p>
                      ) : null}
                    </Link>
                  </li>
                ))}
            </ul>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default AcademyCommentsPage;
