import { CalendarDays, MapPin, MoveRight } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { directoriesApi } from "../shared/api/endpoints";
import { queryKeys } from "../shared/api/queryKeys";
import { 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 normalizeEvent(event) {
  const rawDate = event.date ?? event.startsAt ?? event.publishedAt ?? "";
  const parsedDate = rawDate ? new Date(rawDate) : null;
  const day = parsedDate && !Number.isNaN(parsedDate.getTime())
    ? parsedDate.toLocaleDateString("ru-RU", { day: "numeric" })
    : String(rawDate).split(" ")[0] ?? "--";
  const month = parsedDate && !Number.isNaN(parsedDate.getTime())
    ? parsedDate.toLocaleDateString("ru-RU", { month: "short" })
    : String(rawDate).split(" ")[1] ?? "";

  return {
    ...event,
    day,
    month,
    description: event.description ?? event.lead ?? event.body ?? "Описание события появится после загрузки данных.",
    time: event.time ?? event.startsAt ?? "Время уточняется",
    place: event.place ?? event.location ?? "Место уточняется",
  };
}

export function EventsPage() {
  const { data: eventsPayload, isLoading, isError, refetch } = useQuery({
    queryKey: queryKeys.events(),
    queryFn: directoriesApi.events,
  });
  const pageEvents = toList(eventsPayload).map(normalizeEvent);

  return (
    <div className="page-shell py-10">
      <div className="grid gap-8 border-b border-line pb-10 md:grid-cols-2">
        <div>
          <p className="text-xs font-bold uppercase tracking-widest text-accent">Афиша ДГТУ</p>
          <h1 className="mt-3 font-serif text-5xl">События</h1>
        </div>
        <p className="self-end text-lg leading-8 text-muted">
          Открытые лекции, фестивали, выставки и встречи. Всё, что помогает университету
          разговаривать с городом.
        </p>
      </div>

      <div className="mt-8 flex gap-2 overflow-x-auto pb-2">
        {["Все события", "Лекции", "Фестивали", "Экскурсии", "Выставки"].map(
          (item, index) => (
            <Button key={item} variant={index === 0 ? "primary" : "secondary"} size="sm">
              {item}
            </Button>
          ),
        )}
      </div>

      <div className="mt-8 divide-y divide-line border-y border-line">
        {isLoading ? (
          [1, 2, 3].map((item) => <Skeleton key={item} className="my-6 h-28 w-full" />)
        ) : isError ? (
          <div className="py-8">
            <ErrorState retry={refetch} />
          </div>
        ) : pageEvents.length ? (
          pageEvents.map((event, index) => (
          <article
            key={event.id}
            className="group grid gap-5 py-8 md:grid-cols-[minmax(7rem,1fr)_minmax(0,5fr)_auto] md:items-center"
          >
            <div className="flex items-baseline gap-2 md:block">
               <span className="font-serif text-5xl text-primary">{event.day}</span>
               <span className="text-sm uppercase tracking-widest text-muted">
                 {event.month}
               </span>
            </div>
            <div>
              <Badge tone={index === 0 ? "accent" : "neutral"}>{event.category}</Badge>
              <h2 className="mt-3 font-serif text-2xl transition group-hover:text-primary sm:text-3xl">
                {event.title}
              </h2>
              <p className="mt-3 max-w-2xl leading-7 text-muted">{event.description}</p>
              <div className="mt-4 flex flex-wrap gap-4 text-sm text-muted">
                <span className="flex items-center gap-1.5">
                  <CalendarDays className="size-4" /> {event.time}
                </span>
                <span className="flex items-center gap-1.5">
                  <MapPin className="size-4" /> {event.place}
                </span>
              </div>
            </div>
            <Button className="md:justify-self-end" variant="secondary" icon={<MoveRight className="size-4" />}>
              Подробнее
            </Button>
          </article>
          ))
        ) : (
          <div className="py-8">
            <EmptyState title="Событий нет" text="Backend пока не вернул события." />
          </div>
        )}
      </div>
    </div>
  );
}
