"use client";

import { useState, useMemo } from "react";
import Link from "next/link";
import Image from "next/image";
import cloudinaryLoader from "@/lib/cloudinaryLoader";
import { MagnifyingGlass, BookOpen, X, ListBullets, Timer, CaretLeft, CaretRight } from "@phosphor-icons/react";
import { useLanguage } from "@/lib/i18n/context";

interface Recette {
  id:           number;
  title:        string;
  description:  string;
  image_url:    string;
  ingredients:  string[];
  steps:        string[];
  product_name: string | null;
  created_at:   string;
}

const PAGE_SIZE = 7; // 1 featured + up to 6 grid

export default function RecettesClient({ recettes }: { recettes: Recette[] }) {
  const { t, locale } = useLanguage();
  const isRTL = locale === "ar";
  const [search, setSearch] = useState("");
  const [page,   setPage]   = useState(0);

  const filtered = useMemo(() => {
    setPage(0);
    const q = search.toLowerCase().trim();
    if (!q) return recettes;
    return recettes.filter((r) =>
      r.title.toLowerCase().includes(q) ||
      r.description.toLowerCase().includes(q)
    );
  }, [recettes, search]);

  const totalPages  = Math.ceil(filtered.length / PAGE_SIZE);
  const paged       = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
  const [featured, ...rest] = paged;

  return (
    <section className="bg-brand-sand-light min-h-screen pt-28 pb-16 px-6">
      <div className="max-w-5xl mx-auto">

        {/* ── Top bar ── */}
        <div className="flex items-center justify-between gap-4 mb-8 border-b border-brand-dark/10 pb-5">
          <div>
            <h1 className="text-2xl font-black text-brand-dark" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
              {t.recettes.title}
            </h1>
            <p className="text-brand-dark/40 text-xs font-medium mt-0.5">
              {recettes.length} {recettes.length !== 1 ? t.recettes.counts : t.recettes.count}
            </p>
          </div>
          <div className="relative">
            <MagnifyingGlass size={14} weight="bold" className={`absolute ${isRTL ? "right-3.5" : "left-3.5"} top-1/2 -translate-y-1/2 text-brand-dark/40 pointer-events-none`} />
            <input
              type="search"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={t.recettes.searchPlaceholder}
              className={`${isRTL ? "pr-9 pl-8" : "pl-9 pr-8"} py-2.5 rounded-xl bg-brand-sand-light border border-brand-dark/12 text-sm text-brand-dark placeholder:text-brand-dark/40 focus:outline-none focus:border-brand-yellow focus:ring-2 focus:ring-brand-yellow/20 transition-all w-56`}
            />
            {search && (
              <button onClick={() => setSearch("")} className={`absolute ${isRTL ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-brand-dark/40 hover:text-brand-dark transition-colors`}>
                <X size={12} weight="bold" />
              </button>
            )}
          </div>
        </div>

        {/* ── Cards ── */}
        {filtered.length === 0 ? (
          <div className="text-center py-24 bg-brand-sand-light rounded-3xl border border-brand-dark/8">
            <BookOpen size={44} weight="light" className="text-brand-dark/20 mx-auto mb-4" />
            <p className="text-brand-dark/40 text-sm font-semibold">{t.recettes.notFound}</p>
            <button onClick={() => setSearch("")} className="mt-3 text-xs text-brand-dark/40 hover:text-brand-dark underline underline-offset-2 transition-colors">
              {t.recettes.reset}
            </button>
          </div>
        ) : (
          <div className="space-y-4">

            {/* Featured first card — full width */}
            {featured && (
              <Link
                href={`/recettes/${featured.id}`}
                className="group relative block w-full h-72 sm:h-96 rounded-3xl overflow-hidden"
              >
                {featured.image_url ? (
                  <Image
                    loader={cloudinaryLoader}
                    src={featured.image_url}
                    alt={featured.title}
                    fill
                    sizes="(max-width: 640px) 100vw, 800px"
                    className="object-cover group-hover:scale-105 transition-transform duration-700"
                    priority
                  />
                ) : (
                  <div className="w-full h-full bg-brand-peach flex items-center justify-center">
                    <BookOpen size={56} weight="light" className="text-brand-dark/30" />
                  </div>
                )}
                <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />
                <div className="absolute bottom-0 left-0 right-0 p-6 sm:p-8">
                  <div className="flex items-end justify-between gap-4">
                    <div className="flex-1 min-w-0">
                      <h2
                        className="text-white font-black text-2xl sm:text-3xl leading-tight mb-2"
                        style={{ fontFamily: "var(--font-space, sans-serif)" }}
                      >
                        {featured.title}
                      </h2>
                      {featured.description && (
                        <p className="text-white/70 text-sm leading-relaxed line-clamp-2 max-w-xl">
                          {featured.description}
                        </p>
                      )}
                      <div className="flex items-center gap-4 mt-3">
                        <span className="flex items-center gap-1.5 text-white/60 text-xs font-semibold">
                          <ListBullets size={13} weight="bold" /> {featured.ingredients?.length ?? 0} {t.recettes.ingredients}
                        </span>
                        <span className="flex items-center gap-1.5 text-white/60 text-xs font-semibold">
                          <Timer size={13} weight="bold" /> {featured.steps?.length ?? 0} {t.recettes.steps}
                        </span>
                      </div>
                    </div>
                    <div className="flex-shrink-0 w-10 h-10 rounded-full bg-brand-yellow flex items-center justify-center group-hover:scale-110 transition-transform duration-300">
                      <span className="text-brand-dark font-black text-sm">{isRTL ? "←" : "→"}</span>
                    </div>
                  </div>
                </div>
              </Link>
            )}

            {/* Rest — 2 or 3 col grid */}
            {rest.length > 0 && (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                {rest.map((r) => (
                  <Link
                    key={r.id}
                    href={`/recettes/${r.id}`}
                    className="group relative block h-60 sm:h-64 rounded-2xl overflow-hidden"
                  >
                    {r.image_url ? (
                      <Image
                        loader={cloudinaryLoader}
                        src={r.image_url}
                        alt={r.title}
                        fill
                        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
                        className="object-cover group-hover:scale-105 transition-transform duration-700"
                      />
                    ) : (
                      <div className="w-full h-full bg-brand-peach flex items-center justify-center">
                        <BookOpen size={40} weight="light" className="text-brand-dark/30" />
                      </div>
                    )}
                    <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/10 to-transparent" />
                    <div className="absolute bottom-0 left-0 right-0 p-4">
                      <h2
                        className="text-white font-black text-base leading-snug mb-1"
                        style={{ fontFamily: "var(--font-space, sans-serif)" }}
                      >
                        {r.title}
                      </h2>
                      <div className="flex items-center gap-3">
                        <span className="text-white/55 text-xs font-semibold">{r.ingredients?.length ?? 0} {t.recettes.ingr}</span>
                        <span className="text-white/55 text-xs font-semibold">{r.steps?.length ?? 0} {t.recettes.steps}</span>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            )}

          </div>
        )}

        {/* ── Pagination ── */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between mt-10 pt-6 border-t border-brand-dark/8">
            <button
              onClick={() => { setPage(p => Math.max(0, p - 1)); window.scrollTo({ top: 0, behavior: "smooth" }); }}
              disabled={page === 0}
              className="flex items-center gap-2 text-sm font-bold text-brand-dark/40 hover:text-brand-dark disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
            >
              {isRTL ? <CaretRight size={13} weight="bold" /> : <CaretLeft size={13} weight="bold" />} {t.recettes.previous}
            </button>

            <div className="flex items-center gap-1.5">
              {Array.from({ length: totalPages }, (_, i) => (
                <button
                  key={i}
                  onClick={() => { setPage(i); window.scrollTo({ top: 0, behavior: "smooth" }); }}
                  className={`w-8 h-8 rounded-full text-xs font-black transition-all ${
                    i === page
                      ? "bg-brand-yellow text-brand-dark"
                      : "text-brand-dark/35 hover:text-brand-dark hover:bg-brand-dark/5"
                  }`}
                >
                  {i + 1}
                </button>
              ))}
            </div>

            <button
              onClick={() => { setPage(p => Math.min(totalPages - 1, p + 1)); window.scrollTo({ top: 0, behavior: "smooth" }); }}
              disabled={page === totalPages - 1}
              className="flex items-center gap-2 text-sm font-bold text-brand-dark/40 hover:text-brand-dark disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
            >
              {t.recettes.next} {isRTL ? <CaretLeft size={13} weight="bold" /> : <CaretRight size={13} weight="bold" />}
            </button>
          </div>
        )}

      </div>
    </section>
  );
}
