import { Bell, BookOpen, MessageSquareText, MoveRight } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { useSession } from "../../app/store/session";
import { analyticsApi, notificationsApi } from "../../shared/api/endpoints";
import { queryKeys } from "../../shared/api/queryKeys";
import { toEntity, toList } from "../../shared/api/normalize";
import { Badge } from "../../shared/ui/Badge";
import { Button } from "../../shared/ui/Button";
import { EmptyState, ErrorState, Skeleton } from "../../shared/ui/States";

function firstName(name = "") {
  return name.trim().split(/\s+/)[0] || "пользователь";
}

function formatDate(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleString("ru-RU", { day: "numeric", month: "long", hour: "2-digit", minute: "2-digit" });
}

export function CabinetHomePage() {
  const user = useSession((state) => state.user);
  const notificationsQuery = useQuery({
    queryKey: queryKeys.notifications,
    queryFn: notificationsApi.list,
  });
  const summaryQuery = useQuery({
    queryKey: queryKeys.analyticsSummary,
    queryFn: analyticsApi.summary,
  });

  const notifications = toList(notificationsQuery.data);
  const unreadCount = notifications.filter((item) => !item.read && !item.isRead).length;
  const summary = toEntity(summaryQuery.data) ?? {};
  const stats = [
    [BookOpen, summary.savedMaterials ?? summary.materials ?? 0, "Материалов"],
    [Bell, unreadCount, "Новых уведомлений"],
    [MessageSquareText, summary.comments ?? summary.commentCount ?? 0, "Комментариев"],
  ];
  const canCreate = user?.role === "editor" || user?.role === "admin";

  return (
    <div>
      <p className="text-xs font-bold uppercase tracking-widest text-accent">Личный кабинет</p>
      <h1 className="mt-2 font-serif text-4xl">Добрый день, {firstName(user?.name)}</h1>
      <p className="mt-3 text-muted">Здесь собраны ваши материалы, уведомления и быстрые действия.</p>

      <div className="mt-8 grid gap-5 md:grid-cols-3">
        {stats.map(([Icon, value, label]) => {
          const ItemIcon = Icon;
          return (
            <div key={String(label)} className="rounded-lg border border-line bg-surface p-5">
              <ItemIcon className="size-5 text-accent" />
              {summaryQuery.isLoading ? (
                <Skeleton className="mt-6 h-10 w-20" />
              ) : (
                <p className="mt-6 font-serif text-4xl">{Number(value).toLocaleString("ru-RU")}</p>
              )}
              <p className="mt-1 text-sm text-muted">{String(label)}</p>
            </div>
          );
        })}
      </div>

      <div className="mt-6 grid gap-6 lg:grid-cols-[1.2fr_0.8fr]">
        <section className="rounded-lg border border-line bg-surface p-6">
          <div className="flex items-center justify-between gap-4">
            <h2 className="font-serif text-2xl">Последние уведомления</h2>
            <Badge tone="accent">{unreadCount} новых</Badge>
          </div>
          <div className="mt-5">
            {notificationsQuery.isLoading && (
              <div className="space-y-3">
                <Skeleton className="h-20" />
                <Skeleton className="h-20" />
              </div>
            )}
            {notificationsQuery.isError && <ErrorState retry={() => notificationsQuery.refetch()} />}
            {notificationsQuery.isSuccess && notifications.length === 0 && (
              <EmptyState title="Уведомлений пока нет" text="Когда backend пришлет новые события, они появятся здесь." />
            )}
            {notificationsQuery.isSuccess && notifications.length > 0 && (
              <div className="divide-y divide-line">
                {notifications.slice(0, 5).map((item) => (
                  <article key={item.id} className="py-4 first:pt-0">
                    <div className="flex items-start gap-3">
                      <span className={`mt-1.5 size-2 rounded-full ${item.read || item.isRead ? "bg-line" : "bg-accent"}`} />
                      <div>
                        <h3 className="font-semibold">{item.title ?? "Уведомление"}</h3>
                        <p className="mt-1 text-sm text-muted">{item.text ?? item.message ?? item.description ?? item.body}</p>
                        <p className="mt-2 text-xs text-muted">{formatDate(item.createdAt ?? item.date)}</p>
                      </div>
                    </div>
                  </article>
                ))}
              </div>
            )}
          </div>
        </section>
        <section className="rounded-lg bg-primary p-6 text-white">
          <p className="text-xs font-bold uppercase tracking-widest text-white/50">Быстрое действие</p>
          <h2 className="mt-4 font-serif text-3xl">
            {canCreate ? "Подготовьте новый материал" : "Настройте свой профиль"}
          </h2>
          <p className="mt-3 text-sm leading-6 text-white/65">
            {canCreate
              ? "Создайте материал и отправьте его на обработку backend."
              : "Проверьте данные профиля, которые пришли из учетной записи."}
          </p>
          <Link to={canCreate ? "/cabinet/editor/new" : "/cabinet/profile"}>
            <Button className="mt-6 bg-white text-primary hover:bg-paper" icon={<MoveRight className="size-4" />}>
              Продолжить
            </Button>
          </Link>
        </section>
      </div>
    </div>
  );
}
