"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import SessionCoverImage from "./SessionCoverImage";
import AddressLink from "./AddressLink";
import { SESSIONS, ACTIVITY_TYPES, SESSION_TAGS, RECENT_JOINERS } from "@/config/home.config";

interface JoinStats {
  count: number;
  joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[];
}

const MOCK_JOINERS = RECENT_JOINERS.slice(0, 3);

export default function SessionCard({
  session,
  index,
}: {
  session: (typeof SESSIONS)[0];
  index: number;
}) {
  const [stats, setStats] = useState<JoinStats | null>(null);

  useEffect(() => {
    fetch("/api/join/stats")
      .then((r) => r.json())
      .then((d) => d?.stats?.[session.id] && setStats(d.stats[session.id]))
      .catch(() => {});
  }, [session.id]);

  return (
    <Link
      href={`/join?session=${encodeURIComponent(session.id)}`}
      className="group flex flex-col sm:flex-row gap-3 sm:gap-4 p-4 sm:p-5 rounded-xl sm:rounded-2xl bg-white dark:bg-stone-900/80 border border-stone-200/80 dark:border-stone-700/80 hover:border-amber-200 dark:hover:border-amber-900/50 hover:shadow-lg hover:shadow-amber-900/5 transition-all"
    >
      <div className="relative w-full sm:w-24 sm:h-24 shrink-0 aspect-[16/10] sm:aspect-square rounded-lg sm:rounded-xl overflow-hidden bg-stone-100 dark:bg-stone-800">
        {session.coverImage ? (
          <SessionCoverImage
            src={session.coverImage}
            alt={session.title}
            type={session.type}
            fill
            sizes="(max-width: 640px) 100vw, 96px"
            className="object-cover"
          />
        ) : (
          <div className="absolute inset-0 flex items-center justify-center text-2xl">
            {session.type === "skill-exchange" ? "🔄" : "☕"}
          </div>
        )}
      </div>
      <div className="min-w-0 flex-1">
        <div className="flex flex-wrap gap-1 mb-1.5">
          {session.tags?.map((tag) => (
            <span
              key={tag}
              className="inline-block text-[9px] sm:text-[10px] font-medium text-amber-600 dark:text-amber-400/90 bg-amber-50 dark:bg-amber-900/20 px-1.5 py-0.5 rounded"
            >
              {SESSION_TAGS[tag]}
            </span>
          ))}
          {index === 0 && (
            <span className="inline-block text-[9px] sm:text-[10px] font-medium text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 px-1.5 py-0.5 rounded">
              主推
            </span>
          )}
        </div>
        <span className="text-[10px] sm:text-xs text-amber-600 dark:text-amber-400/90">
          {ACTIVITY_TYPES[session.type]} · {session.city}
        </span>
        <h3 className="font-semibold text-stone-800 dark:text-stone-100 text-sm sm:text-base group-hover:text-amber-700 dark:group-hover:text-amber-400 mt-0.5">
          {session.title}
        </h3>
        <p className="text-xs sm:text-sm text-stone-500 dark:text-stone-400 mt-0.5">
          {session.date} {session.time} · <AddressLink place={session.place} city={session.city} />
        </p>
        <span className="inline-flex items-center gap-1 mt-2 sm:mt-3 text-amber-600 dark:text-amber-400 text-xs sm:text-sm font-medium">
          报名这场 →
        </span>
        <div className="mt-3 flex items-center gap-2">
          <div className="flex -space-x-2 shrink-0">
            {(stats?.joiners?.length ? stats.joiners : MOCK_JOINERS).slice(0, 5).map((j, i) => {
              const nickname = "name" in j ? (j as { name: string }).name : (j as { nickname: string }).nickname;
              const avatar = "avatar" in j ? (j as { avatar: string }).avatar : (j as { avatar?: string }).avatar;
              const xhUrl = (j as { xiaohongshu_url?: string }).xiaohongshu_url;
              const showAvatar = avatar && avatar.length > 0;
              return (
                <span
                  key={i}
                  className={`relative w-7 h-7 rounded-full overflow-hidden border-2 border-white dark:border-stone-900 ring-1 ring-stone-200/50 dark:ring-stone-700/50 shrink-0 inline-block cursor-default ${showAvatar ? "" : "bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center text-xs font-medium text-amber-700 dark:text-amber-300"}`}
                  title={nickname}
                  data-xiaohongshu-url={xhUrl}
                  onClick={(e) => e.preventDefault()}
                >
                  {showAvatar ? (
                    <Image src={avatar} alt="" fill sizes="28px" className="object-cover" unoptimized />
                  ) : (
                    <span className="flex items-center justify-center w-full h-full">{nickname.slice(0, 1) || "?"}</span>
                  )}
                </span>
              );
            })}
          </div>
          <span className="text-xs text-stone-500 dark:text-stone-400">
            {stats?.count ? `${stats.count} 人已报名` : "有人报名中"}
          </span>
        </div>
      </div>
    </Link>
  );
}
