"use client";

import React, { useEffect, useMemo, useState } from "react";
import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import VisitorRow, { type ProfileVisitor } from "@/components/settings/VisitorRow";
import ListDateSeparator from "@/components/settings/ListDateSeparator";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import { groupItemsByDate } from "@/lib/groupItemsByDate";
import { useTranslation } from "react-i18next";

export default function ProfileVisitorsPage() {
  const { t, i18n } = useTranslation("common");
  const listLang = i18n.language === "en" ? "en" : "fa";
  const { request } = useAxios();
  const [visitors, setVisitors] = useState<ProfileVisitor[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const res = await request<{ visitors: ProfileVisitor[] }>(
          "GET",
          "/account/visitors?limit=50",
          null,
          { noToast: true }
        );
        const list = (res?.visitors || []).filter((v) => v.user_name?.trim());
        setVisitors(list);
      } catch {
        setError(t("settings.visitor.fetchError"));
      } finally {
        setLoading(false);
      }
    })();
  }, [request, t]);

  const groupedVisitors = useMemo(
    () =>
      groupItemsByDate(
        visitors,
        (visitor) => visitor.visited_at,
        (visitor) => `${visitor._id}-${visitor.visited_at ?? ""}`,
        listLang
      ),
    [visitors, listLang]
  );

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.profileVisitors")}</PageTitle>
        <div className="text-xs md:text-sm">
          {loading ? (
            <p className="py-8 text-center text-sm text-neutral-500">
              {t("common.loading")}
            </p>
          ) : error ? (
            <p className="py-8 text-center text-sm text-red-500">{error}</p>
          ) : visitors.length === 0 ? (
            <p className="py-8 text-center text-sm text-neutral-500">
              {t("settings.visitor.empty")}
            </p>
          ) : (
            <div className="mt-2 font-semibold">
              {groupedVisitors.map((entry) =>
                entry.type === "date" ? (
                  <ListDateSeparator key={entry.key} label={entry.label} />
                ) : (
                  <VisitorRow key={entry.key} visitor={entry.item} />
                )
              )}
            </div>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}
