import { Metadata } from 'next';
import Image from 'next/image';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { ArrowLeft, Clock, Users, ChefHat } from 'lucide-react';
import { RECIPES, RecipesProps, RecipeSection } from '../data';
import { RecipeDetailClient } from './RecipeDetailClient';

// ==========================================
// METADATA (UNTUK PREVIEW SOCMED)
// ==========================================
export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string }>;
}): Promise<Metadata> {
  const { id } = await params;
  const recipe = RECIPES.find((r) => r.id === Number(id));

  if (!recipe) {
    return {
      title: 'Resep Tidak Ditemukan | Garam Cap Kapal',
    };
  }

  return {
    title: recipe.title,
    description: recipe.description,
    openGraph: {
      title: `${recipe.title} | Resep Garam Cap Kapal`,
      description: recipe.description,
      url: `/recipes/${id}`,
      type: 'article',
      images: [
        {
          url: recipe.imageBanner,
          width: 1200,
          height: 630,
          alt: `Resep ${recipe.title}`,
        },
      ],
    },
    twitter: {
      card: 'summary_large_image',
      title: `${recipe.title} | Resep Garam Cap Kapal`,
      description: recipe.description,
      images: [recipe.imageBanner],
    },
  };
}

// ==========================================
// KUMPULAN SUB-KOMPONEN
// ==========================================

const BackButton = () => (
  <Link
    href="/recipes"
    className="inline-flex items-center gap-1.5 px-3 py-2 md:px-4 md:py-2 rounded-full bg-white/80 backdrop-blur-md border border-white/50 text-[10px] md:text-xs font-bold text-gray-600 hover:bg-white hover:text-gray-900 transition-all mb-4 md:mb-6 group shadow-sm w-fit"
  >
    <ArrowLeft className="w-3 h-3 md:w-3.5 md:h-3.5 group-hover:-translate-x-1 transition-transform" />
    Kembali ke Resep
  </Link>
);

const RecipeHeader = ({ recipe }: { recipe: RecipesProps }) => (
  <header className="bg-white/80 backdrop-blur-xl border border-white/50 rounded-3xl p-4 md:p-6 shadow-sm w-full flex flex-col justify-center h-fit relative overflow-hidden group">
    {/* Latar Belakang Halus */}
    <div className="absolute -right-20 -bottom-20 opacity-[0.03] group-hover:opacity-10 transition-opacity pointer-events-none duration-700">
      <Image
        src="/mascots/saltu-happy.avif"
        alt="Mascot Background"
        width={300}
        height={300}
        className="object-contain"
      />
    </div>

    <div className="relative z-10 w-full flex flex-col h-fit justify-between gap-1">
      <div>
        <div className="mb-3 md:mb-4">
          <span className="bg-[#FFD738] text-yellow-950 px-2 py-1 rounded-full font-bold uppercase tracking-wider text-[8px] shadow-sm">
            {recipe.category}
          </span>
        </div>

        <h1 className="text-2xl md:text-3xl lg:text-4xl font-black text-gray-900 tracking-tight leading-tight mb-3">
          {recipe.title}
        </h1>

        <p className="text-xs md:text-sm text-gray-600 leading-relaxed font-medium mb-4">
          {recipe.description}
        </p>

        {/* Meta Stats */}
        <div className="flex flex-wrap items-center gap-2 md:gap-3 mb-4">
          <RecipeStat
            icon={<Clock className="w-3.5 h-3.5 md:w-4 md:h-4" />}
            label="Waktu"
            value={recipe.time}
            color="yellow"
          />
          <RecipeStat
            icon={<Users className="w-3.5 h-3.5 md:w-4 md:h-4" />}
            label="Porsi"
            value={recipe.serving || '-'}
            color="yellow"
          />
        </div>
      </div>

      {/* Info Kreator (Author) */}
      <div className="flex items-center gap-3 bg-gray-50/80 backdrop-blur-sm p-2.5 pr-4 rounded-xl border border-gray-200/60 w-fit shadow-sm">
        <div className="w-10 h-10 md:w-12 md:h-12 rounded-full border-2 border-yellow-200 bg-yellow-50 overflow-hidden shrink-0 relative shadow-inner">
          <Image
            src="/mascots/saltu-cooking-pose.avif"
            alt="Chef Mascot"
            fill
            className="object-cover"
          />
        </div>
        <div>
          <p className="text-[8px] md:text-[10px] font-bold text-gray-500 uppercase tracking-wider mb-0.5">
            Resep Oleh
          </p>
          <p className="text-xs md:text-sm font-black text-gray-900 flex items-center gap-1.5">
            <ChefHat className="w-3 h-3 md:w-3.5 md:h-3.5 text-yellow-600" />
            {recipe.author}
          </p>
        </div>
      </div>
    </div>
  </header>
);

const RecipeStat = ({
  icon,
  label,
  value,
  color,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  color: 'yellow' | 'yellow';
}) => {
  const bgColors =
    color === 'yellow'
      ? 'bg-yellow-100 text-yellow-600'
      : 'bg-yellow-100 text-yellow-600';
  return (
    <div className="flex items-center gap-2 bg-white shadow-sm px-3 md:px-4 py-2 md:py-2.5 rounded-xl border border-gray-100 flex-1 min-w-[100px]">
      <div
        className={`w-6 h-6 md:w-8 md:h-8 rounded-full flex items-center justify-center shrink-0 ${bgColors}`}
      >
        {icon}
      </div>
      <div>
        <p className="text-[8px] md:text-[9px] font-bold text-gray-500 uppercase tracking-widest">
          {label}
        </p>
        <p className="text-xs md:text-sm font-black text-gray-900">{value}</p>
      </div>
    </div>
  );
};

const RecipeMainImage = ({ src, title }: { src: string; title: string }) => (
  <div className="w-full h-[200px] sm:h-[300px] md:h-[400px] lg:h-[500px] relative rounded-2xl md:rounded-[32px] overflow-hidden shadow-xl border-[4px] md:border-[6px] border-white/80 bg-white lg:col-span-2 group flex items-center justify-center">
    <Image
      src={src}
      alt={`Ilustrasi Utama ${title}`}
      fill
      className="object-contain transition-transform duration-700 group-hover:scale-[1.02] p-2 md:p-3"
      sizes="(max-width: 1024px) 100vw, 1200px"
      priority
    />
    {/* Gradasi lembut agar gambar tidak terlalu flat */}
    <div className="absolute inset-0 bg-linear-to-t from-black/5 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none" />
  </div>
);

const RecipeIngredients = ({
  ingredients,
}: {
  ingredients: RecipeSection[];
}) => (
  <aside className="lg:col-span-4 relative">
    {/* Menggunakan Sticky agar bahan tetap terlihat saat men-scroll langkah pembuatan */}
    <div className="bg-white/90 backdrop-blur-xl border border-white/50 rounded-2xl md:rounded-3xl p-4 md:p-5 lg:p-6 shadow-sm sticky top-24 overflow-hidden group">
      <div className="absolute -right-10 -bottom-10 opacity-[0.03] group-hover:opacity-15 transition-opacity duration-700 pointer-events-none">
        <Image
          src="/mascots/salta-happy.avif"
          alt="Mascot Salta"
          width={200}
          height={200}
          className="object-contain"
        />
      </div>
      <h2 className="text-lg md:text-xl font-black text-gray-900 mb-4 flex items-center gap-2 relative z-10">
        <div className="w-1 h-5 md:h-6 bg-[#FFD738] rounded-full" />
        Bahan-Bahan
      </h2>
      <div className="space-y-5 md:space-y-6 relative z-10">
        {ingredients.map((section, idx) => (
          <div key={idx}>
            <h3 className="text-[10px] md:text-[11px] font-bold text-gray-400 tracking-widest uppercase mb-3 border-b border-gray-100 pb-1.5">
              {section.title}
            </h3>
            <ul className="space-y-2">
              {section.items.map((item, itemIdx) => (
                <li key={itemIdx} className="flex items-start gap-2.5">
                  <span className="w-1.5 h-1.5 bg-[#FFD738] rounded-full mt-1.5 shrink-0" />
                  <span className="text-xs md:text-sm text-gray-700 font-medium leading-relaxed">
                    {item}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  </aside>
);

const RecipeInstructions = ({
  instructions,
}: {
  instructions: RecipeSection[];
}) => (
  <section className="lg:col-span-8 bg-white/90 backdrop-blur-xl border border-white/50 rounded-2xl md:rounded-3xl p-5 md:p-6 lg:p-8 shadow-sm h-fit">
    <h2 className="text-lg md:text-xl font-black text-gray-900 mb-5 md:mb-6 flex items-center gap-2">
      <div className="w-1 h-5 md:h-6 bg-yellow-400 rounded-full" />
      Langkah Pembuatan
    </h2>

    <div className="space-y-2 md:space-y-4">
      {instructions.map((section, idx) => (
        <div key={idx}>
          {section.title !== 'CARA MEMBUAT' && (
            <h3 className="text-sm md:text-base font-black text-gray-800 mb-4 inline-block border-b-2 border-yellow-200 pb-1">
              {section.title}
            </h3>
          )}
          <div className="space-y-0.5 md:space-y-1">
            {section.items.map((item, itemIdx) => (
              <div key={itemIdx} className="flex gap-3 md:gap-4 group">
                <div className="shrink-0 pt-0.5 md:pt-1">
                  <span className="w-6 h-6 md:w-8 md:h-8 bg-yellow-50 text-yellow-600 rounded-lg md:rounded-xl flex items-center justify-center font-black text-[10px] md:text-xs group-hover:bg-yellow-600 group-hover:text-white transition-colors shadow-sm">
                    {itemIdx + 1}
                  </span>
                </div>
                {/* Desain garis bawah tipis untuk memisahkan setiap langkah agar mudah dipindai mata */}
                <div className="pb-1 md:pb-2 border-b border-gray-100 last:border-0 w-full pt-1">
                  <p className="text-xs md:text-sm text-gray-700 font-medium leading-relaxed">
                    {item}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  </section>
);

// ==========================================
// KOMPONEN HALAMAN UTAMA
// ==========================================

export default async function RecipeDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const recipe = RECIPES.find((r) => r.id === Number(id));

  if (!recipe) {
    notFound();
  }

  return (
    <RecipeDetailClient>
      <main className="min-h-screen bg-slate-50 text-gray-900 relative overflow-hidden pb-16 md:pb-40 lg:pb-60">
        {/* Ornamen Background */}
        <div className="fixed inset-0 z-[-1]" aria-hidden="true">
          <div className="absolute top-0 right-0 w-[600px] h-[600px] bg-yellow-300/20 rounded-full blur-[100px] -translate-y-1/3 translate-x-1/3 opacity-60" />
          <div className="absolute bottom-[-10%] left-[-10%] w-[500px] h-[500px] bg-yellow-300/20 rounded-full blur-[100px] opacity-60" />
        </div>

        <div className="relative z-10 pt-20 md:pt-24 px-4 sm:px-6">
          <div className="max-w-6xl mx-auto flex flex-col items-start w-full">
            <BackButton />

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-3 lg:gap-4 w-full">
              <RecipeHeader recipe={recipe} />
              <RecipeMainImage
                src={recipe.imageTextBook}
                title={recipe.title}
              />
            </div>
            {/* Grid Layout Baru: Kiri Bahan (4 Kolom), Kanan Cara Pembuatan (8 Kolom) */}
            <article className="mt-4 md:mt-6 w-full grid grid-cols-1 lg:grid-cols-12 gap-4 md:gap-6 items-start">
              <RecipeIngredients ingredients={recipe.ingredients} />
              <RecipeInstructions instructions={recipe.instructions} />
            </article>
          </div>
        </div>
      </main>
    </RecipeDetailClient>
  );
}
