"use client";

import { useState } from "react";
import { getTMDBImageUrl, TMDB_GENRE_MAP } from "@/types/tmdb";
import type { TMDBMovie } from "@/types/tmdb";
import { MoreInfoModal } from "./more-info-modal";

interface TeaserCardProps {
  movie: TMDBMovie;
}

export function TeaserCard({ movie }: TeaserCardProps) {
  const [modalOpen, setModalOpen] = useState(false);
  const posterUrl = getTMDBImageUrl(movie.poster_path, "grid");
  const genres = movie.genre_ids
    .map((id) => TMDB_GENRE_MAP[id])
    .filter(Boolean)
    .slice(0, 3);
  const year = movie.release_date ? movie.release_date.slice(0, 4) : "";

  return (
    <>
      <div className="flex w-40 flex-col items-center rounded-xl bg-background/95 p-3 shadow-2xl ring-1 ring-foreground/10 backdrop-blur">
        {posterUrl ? (
          /* eslint-disable-next-line @next/next/no-img-element */
          <img
            src={posterUrl}
            alt={`Movie poster for ${movie.title}`}
            loading="lazy"
            className="h-auto w-36 rounded-lg"
          />
        ) : (
          <div className="flex h-52 w-36 items-center justify-center rounded-lg bg-foreground/10 text-xs text-foreground/40">
            No poster
          </div>
        )}
        <h3 className="mt-2 text-center text-sm font-semibold leading-tight line-clamp-2">
          {movie.title}
          {year && <span className="ml-1 text-xs font-normal text-foreground/50">({year})</span>}
        </h3>
        <button
          onClick={() => setModalOpen(true)}
          aria-label={`More info about ${movie.title}`}
          className="mt-1.5 flex h-6 w-6 items-center justify-center rounded-full border border-foreground/30 text-xs font-serif italic text-foreground/70 transition-colors hover:bg-foreground/5 hover:text-foreground"
        >
          i
        </button>
        {genres.length > 0 && (
          <div className="mt-1.5 flex flex-wrap justify-center gap-1">
            {genres.slice(0, 2).map((genre) => (
              <span
                key={genre}
                className="rounded-full bg-foreground/10 px-2 py-0.5 text-[10px] text-foreground/70"
              >
                {genre}
              </span>
            ))}
          </div>
        )}
      </div>
      {modalOpen && <MoreInfoModal movie={movie} onClose={() => setModalOpen(false)} />}
    </>
  );
}
