"use client";

import Link from "next/link";
import { useEffect, useRef } from "react";
import gsap from "gsap";
import { Button } from "@/components/ui/button";
import { formatDateShort, type PublicEvent } from "@/lib/client-api";

export function EventsList({ events }: { events: PublicEvent[] }) {
  const gridRef = useRef<HTMLUListElement>(null);

  useEffect(() => {
    const grid = gridRef.current;
    if (!grid) return;
    const cards = grid.querySelectorAll<HTMLElement>("[data-event-card]");
    if (cards.length === 0) return;
    gsap.fromTo(
      cards,
      { autoAlpha: 0, y: 24, scale: 0.96 },
      {
        autoAlpha: 1,
        y: 0,
        scale: 1,
        duration: 0.55,
        ease: "power3.out",
        stagger: 0.07,
      },
    );
  }, [events.length]);

  return (
    <ul
      ref={gridRef}
      className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3"
    >
      {events.map((ev, idx) => (
        <li key={ev.id} data-event-card>
          <EventCard ev={ev} hueIndex={idx} />
        </li>
      ))}
    </ul>
  );
}

const PALETTES = [
  ["#fda4af", "#f9a8d4", "#fcd34d"],
  ["#fb7185", "#a78bfa", "#60a5fa"],
  ["#f472b6", "#fb923c", "#facc15"],
  ["#f87171", "#c084fc", "#22d3ee"],
  ["#ec4899", "#f59e0b", "#10b981"],
  ["#f43f5e", "#8b5cf6", "#06b6d4"],
];

function EventCard({
  ev,
  hueIndex,
}: {
  ev: PublicEvent;
  hueIndex: number;
}) {
  const palette = PALETTES[hueIndex % PALETTES.length];
  const status = ev.status || "draft";
  const statusColor =
    status === "upcoming"
      ? "bg-emerald-100 text-emerald-700"
      : status === "completed"
        ? "bg-blue-100 text-blue-700"
        : status === "cancelled"
          ? "bg-rose-100 text-rose-700"
          : "bg-amber-100 text-amber-700";

  return (
    <div className="group flex h-full flex-col overflow-hidden rounded-2xl border border-border bg-surface shadow-sm transition-all duration-300 hover:-translate-y-1 hover:border-rose-200 hover:shadow-2xl hover:shadow-rose-500/15">
      <div
        className="relative h-32 w-full overflow-hidden"
        style={{
          background: `linear-gradient(135deg, ${palette[0]} 0%, ${palette[1]} 50%, ${palette[2]} 100%)`,
        }}
      >
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_20%_20%,rgba(255,255,255,0.45),transparent_60%)]" />
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_85%_80%,rgba(255,255,255,0.35),transparent_60%)]" />
        <div className="absolute right-4 top-4 flex flex-col items-end gap-1.5">
          <span
            className={`rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${statusColor}`}
          >
            {status}
          </span>
          <span className="rounded-full bg-white/85 px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-foreground/80 backdrop-blur">
            {ev.templateSlug ?? "custom"}
          </span>
        </div>
        <div className="absolute inset-x-0 bottom-0 p-4 text-white">
          <h3 className="line-clamp-2 text-lg font-bold drop-shadow-sm">
            {ev.title}
          </h3>
        </div>
      </div>

      <div className="flex flex-1 flex-col p-5">
        {ev.description ? (
          <p className="line-clamp-2 text-sm text-muted">{ev.description}</p>
        ) : (
          <p className="text-sm italic text-muted">No description yet.</p>
        )}

        <dl className="mt-4 space-y-1.5 text-xs text-muted">
          <div className="flex items-center gap-2">
            <CalendarIcon className="h-3.5 w-3.5 text-rose-500" />
            <span>
              {ev.eventDate ? formatDateShort(ev.eventDate) : "Date not set"}
            </span>
          </div>
          {ev.location ? (
            <div className="flex items-center gap-2">
              <PinIcon className="h-3.5 w-3.5 text-rose-500" />
              <span className="truncate">{ev.location}</span>
            </div>
          ) : (
            <div className="flex items-center gap-2 opacity-60">
              <PinIcon className="h-3.5 w-3.5" />
              <span>No location yet</span>
            </div>
          )}
        </dl>

        <div className="mt-auto flex gap-2 pt-5">
          <Link href={`/events/${ev.id}`} className="flex-1">
            <Button size="sm" className="w-full">
              Open event →
            </Button>
          </Link>
          <Link
            href={`/events/${ev.id}`}
            className="grid h-8 w-8 place-items-center rounded-lg border border-rose-200 bg-white text-rose-500 transition-colors hover:bg-rose-50"
            aria-label="Quick view"
          >
            <EyeIcon className="h-3.5 w-3.5" />
          </Link>
        </div>
      </div>
    </div>
  );
}

function CalendarIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <rect x="3" y="5" width="18" height="16" rx="2" />
      <path d="M16 3v4M8 3v4M3 11h18" />
    </svg>
  );
}
function PinIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" {...props}>
      <path d="M12 2a7 7 0 0 0-7 7c0 5.25 7 13 7 13s7-7.75 7-13a7 7 0 0 0-7-7Zm0 9.5A2.5 2.5 0 1 1 12 6.5a2.5 2.5 0 0 1 0 5Z" />
    </svg>
  );
}
function EyeIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );
}
