import Image from "next/image";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { getPosterUrl, getUsCertification, type TmdbMovieDetails } from "@/lib/tmdb";

export function MovieHeader({
  movie,
  onClear,
}: {
  movie: TmdbMovieDetails;
  onClear?: () => void;
}) {
  const poster = getPosterUrl(movie.poster_path, "w500");
  const year = movie.release_date?.slice(0, 4);
  const certification = getUsCertification(movie);

  return (
    <div className="space-y-6">
      {onClear ? (
        <button
          type="button"
          onClick={onClear}
          className="inline-flex w-fit items-center gap-2 text-sm text-slate-400 transition hover:text-amber-200"
        >
          <ArrowLeft className="h-4 w-4" />
          Search another movie
        </button>
      ) : (
        <Link
          href="/"
          className="inline-flex w-fit items-center gap-2 text-sm text-slate-400 transition hover:text-amber-200"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to search
        </Link>
      )}

      <div className="flex flex-col gap-6 sm:flex-row sm:items-end">
        <div className="relative mx-auto h-56 w-36 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-900 shadow-2xl sm:mx-0">
          {poster ? (
            <Image
              src={poster}
              alt={movie.title}
              fill
              className="object-cover"
              sizes="144px"
              priority
            />
          ) : (
            <div className="flex h-full items-center justify-center text-sm text-slate-500">
              No poster
            </div>
          )}
        </div>

        <div className="space-y-3 text-center sm:text-left">
          <div>
            <h1 className="text-3xl font-semibold tracking-tight text-white md:text-4xl">
              {movie.title}
            </h1>
            <p className="mt-1 text-slate-400">
              {[year, movie.runtime ? `${movie.runtime} min` : null]
                .filter(Boolean)
                .join(" · ")}
            </p>
          </div>

          <div className="flex flex-wrap justify-center gap-2 sm:justify-start">
            {certification ? (
              <span className="rounded-full border border-amber-400/30 bg-amber-400/10 px-3 py-1 text-sm font-medium text-amber-200">
                {certification}
              </span>
            ) : null}
            {movie.genres.map((genre) => (
              <span
                key={genre.id}
                className="rounded-full border border-white/10 bg-white/5 px-3 py-1 text-sm text-slate-300"
              >
                {genre.name}
              </span>
            ))}
          </div>

          {movie.overview ? (
            <p className="max-w-3xl text-sm leading-relaxed text-slate-400 md:text-base">
              {movie.overview}
            </p>
          ) : null}
        </div>
      </div>
    </div>
  );
}