"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { ArrowLeft, ArrowRight, ForkKnife, ListBullets, CheckCircle, ShoppingCart, Confetti, Lock, Lightbulb, SealCheck } from "@phosphor-icons/react";
import { useCart } from "@/lib/cartStore";
import { useLanguage } from "@/lib/i18n/context";

interface Props {
  title:                     string;
  description:               string;
  image_url:                 string;
  ingredients:               string[];
  steps:                     string[];
  astuces:                   string[];
  bien_fait:                 string[];
  product_id?:               number;
  product_name?:             string;
  product_price?:            number;
  product_image_url?:        string;
  product_sizes?:            string[];
  product_ingredient_index?: number | null;
  isLoggedIn:                boolean;
}

export default function RecetteDetail({
  title, description, image_url, ingredients, steps, astuces, bien_fait,
  product_id, product_name, product_price, product_image_url, product_sizes,
  product_ingredient_index, isLoggedIn,
}: Props) {
  const [checked,      setChecked]      = useState<Set<number>>(new Set());
  const [doneSteps,    setDoneSteps]    = useState<Set<number>>(new Set());
  const [selectedSize, setSelectedSize] = useState<string>(product_sizes?.[0] ?? "");

  const { t, locale } = useLanguage();
  const isRTL = locale === "ar";
  const { addItem, openCart, items } = useCart();

  const cartKey    = `${product_id}-${selectedSize}`;
  const cartItem   = items.find(i => `${i.id}-${i.size ?? ""}` === cartKey);
  const inCart     = !!cartItem;

  const toggleIngr = (i: number) => setChecked(s  => { const n = new Set(s); n.has(i) ? n.delete(i) : n.add(i); return n; });
  const toggleStep = (i: number) => setDoneSteps(s => { const n = new Set(s); n.has(i) ? n.delete(i) : n.add(i); return n; });

  const isProductIngr = (i: number) =>
    product_ingredient_index != null && product_ingredient_index === i && !!product_id;

  const handleAddToCart = () => {
    if (!product_id || !product_name || product_price == null) return;
    addItem({
      id:        product_id,
      name:      product_name,
      price:     product_price,
      image_url: product_image_url ?? "",
      size:      selectedSize || undefined,
    });
    openCart();
  };

  return (
    <section className="bg-brand-sand-light pt-28 pb-10 px-4 sm:px-6">
      <div className="max-w-5xl mx-auto">

        <Link href="/recettes" className="inline-flex items-center gap-2 text-brand-dark/50 hover:text-brand-dark text-xs font-bold tracking-wide transition-colors mb-8">
          {isRTL ? <ArrowRight size={13} weight="bold" /> : <ArrowLeft size={13} weight="bold" />} {t.recettes.detail.allRecipes}
        </Link>

        <div className="grid grid-cols-1 lg:grid-cols-[1fr_1.4fr] gap-8 lg:gap-12 items-start">

          {/* ── LEFT: sticky ── */}
          <div className="lg:sticky lg:top-24 space-y-6">

            {image_url && (
              <div className="relative w-full h-64 sm:h-80 lg:h-72 rounded-3xl overflow-hidden shadow-lg">
                <Image src={image_url} alt={title} fill className="object-cover" priority />
              </div>
            )}

            <div>
              <span className="inline-block bg-brand-yellow text-brand-dark text-[10px] font-black px-3 py-1 rounded-full tracking-widest uppercase mb-3">
                {t.recettes.detail.badge}
              </span>
              <h1 className="text-2xl sm:text-3xl font-black text-brand-dark leading-tight" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                {title}
              </h1>
              {description && (
                <p className={`text-brand-dark/55 text-sm leading-relaxed mt-2 border-brand-yellow ${isRTL ? "border-r-[3px] pr-3" : "border-l-[3px] pl-3"}`}>
                  {description}
                </p>
              )}
            </div>

            {/* Stats pills */}
            <div className="flex gap-3 flex-wrap">
              <div className="flex items-center gap-2 bg-white border border-brand-dark/8 rounded-full px-4 py-2">
                <ForkKnife size={13} weight="bold" className="text-brand-section" />
                <span className="text-brand-dark text-xs font-bold">{ingredients.length} {t.recettes.ingr}</span>
              </div>
              <div className="flex items-center gap-2 bg-white border border-brand-dark/8 rounded-full px-4 py-2">
                <ListBullets size={13} weight="bold" className="text-brand-section" />
                <span className="text-brand-dark text-xs font-bold">{steps.length} {t.recettes.steps}</span>
              </div>
              {checked.size > 0 && (
                <div className="flex items-center gap-2 bg-brand-yellow/20 border border-brand-yellow/40 rounded-full px-4 py-2">
                  <CheckCircle size={13} weight="bold" className="text-brand-section" />
                  <span className="text-brand-dark text-xs font-bold">{checked.size}/{ingredients.length}</span>
                </div>
              )}
            </div>

            {/* Ingredients checklist */}
            {ingredients.length > 0 && (
              <div className="bg-white border border-brand-dark/8 rounded-3xl p-5">
                <h2 className="text-base font-black text-brand-dark mb-4 flex items-center gap-2" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                  <ForkKnife size={15} weight="bold" className="text-brand-section" />
                  {t.recettes.detail.ingredients}
                </h2>
                <ul className="space-y-2">
                  {ingredients.map((ing, i) => {
                    const isProduct = isProductIngr(i);
                    return (
                      <li key={i}>
                        {isProduct ? (
                          /* ── Product ingredient ── */
                          <div className={`flex items-center gap-3 px-3 py-2.5 rounded-2xl border transition-all duration-200 ${
                            checked.has(i) ? "border-green-200/60 bg-green-50" : "border-brand-yellow/40 bg-brand-yellow/6"
                          }`}>
                            {/* Checkbox */}
                            <button onClick={() => toggleIngr(i)} className="flex-shrink-0">
                              <span className={`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-all ${
                                checked.has(i) ? "bg-green-400 border-green-400" : "border-brand-dark/20"
                              }`}>
                                {checked.has(i) && <span className="text-white text-[10px] font-black">✓</span>}
                              </span>
                            </button>
                            {/* Text */}
                            <span className={`flex-1 text-sm font-bold transition-all ${
                              checked.has(i) ? "line-through text-brand-dark/35" : "text-brand-dark"
                            }`}>
                              {ing}
                            </span>
                            {/* Right: size + add to cart */}
                            {!checked.has(i) && (
                              <div className="flex items-center gap-2 flex-shrink-0">
                                {product_sizes && product_sizes.length > 1 && (
                                  <select
                                    value={selectedSize}
                                    onChange={e => setSelectedSize(e.target.value)}
                                    className="text-xs font-semibold text-brand-dark border border-brand-dark/15 rounded-lg px-2 py-1.5 bg-white focus:outline-none focus:border-brand-yellow transition-colors"
                                  >
                                    {product_sizes.map(s => (
                                      <option key={s} value={s}>{s}</option>
                                    ))}
                                  </select>
                                )}
                                {!isLoggedIn ? (
                                  <Link
                                    href="/login"
                                    title={t.products.loginToOrder}
                                    className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-brand-dark text-brand-yellow hover:scale-[1.02] transition-all duration-200"
                                  >
                                    <ShoppingCart size={12} weight="bold" />
                                    <Lock size={10} weight="bold" />
                                  </Link>
                                ) : inCart ? (
                                  <button
                                    onClick={openCart}
                                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-black bg-green-500 text-white hover:bg-green-600 transition-all duration-200"
                                  >
                                    <ShoppingCart size={12} weight="bold" />
                                    {cartItem!.quantity > 1 ? `×${cartItem!.quantity} ${t.recettes.detail.inCartQty}` : t.recettes.detail.inCart}
                                  </button>
                                ) : (
                                  <button
                                    onClick={handleAddToCart}
                                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-black bg-brand-peach text-brand-dark hover:scale-[1.02] transition-all duration-200"
                                  >
                                    <ShoppingCart size={12} weight="bold" />
                                    {t.recettes.detail.add}
                                  </button>
                                )}
                              </div>
                            )}
                          </div>
                        ) : (
                          /* ── Regular ingredient ── */
                          <button
                            onClick={() => toggleIngr(i)}
                            className={`w-full flex items-center gap-3 text-left px-3 py-2.5 rounded-xl transition-all duration-200 ${
                              checked.has(i) ? "bg-green-50 border border-green-200/60" : "hover:bg-brand-dark/4 border border-transparent"
                            }`}
                          >
                            <span className={`w-5 h-5 rounded-full border-2 flex-shrink-0 flex items-center justify-center transition-all ${
                              checked.has(i) ? "bg-green-400 border-green-400" : "border-brand-dark/20"
                            }`}>
                              {checked.has(i) && <span className="text-white text-[10px] font-black">✓</span>}
                            </span>
                            <span className={`text-sm font-semibold transition-all ${
                              checked.has(i) ? "line-through text-brand-dark/35" : "text-brand-dark"
                            }`}>
                              {ing}
                            </span>
                          </button>
                        )}
                      </li>
                    );
                  })}
                </ul>
                {checked.size > 0 && (
                  <button onClick={() => setChecked(new Set())} className="mt-3 text-[11px] text-brand-dark/30 hover:text-brand-dark transition-colors underline underline-offset-2">
                    {t.recettes.detail.uncheckAll}
                  </button>
                )}
              </div>
            )}
          </div>

          {/* ── RIGHT: steps ── */}
          {steps.length > 0 && (
            <div className="space-y-4">
              <h2 className="text-base font-black text-brand-dark flex items-center gap-2" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                <ListBullets size={15} weight="bold" className="text-brand-section" />
                {t.recettes.detail.preparation}
              </h2>

              {steps.map((step, i) => (
                <button
                  key={i}
                  onClick={() => toggleStep(i)}
                  className={`w-full text-left flex gap-4 p-5 rounded-2xl border transition-all duration-200 ${
                    doneSteps.has(i)
                      ? "bg-green-50 border-green-200/60 opacity-60"
                      : "bg-white border-brand-dark/8 hover:border-brand-section/40 hover:shadow-sm"
                  }`}
                >
                  <span
                    className={`w-10 h-10 rounded-xl flex-shrink-0 flex items-center justify-center text-base font-black transition-all ${
                      doneSteps.has(i) ? "bg-green-400 text-white" : "bg-brand-section text-white"
                    }`}
                    style={{ fontFamily: "var(--font-space, sans-serif)" }}
                  >
                    {doneSteps.has(i) ? "✓" : i + 1}
                  </span>
                  <p className={`text-base leading-relaxed pt-1.5 font-medium transition-all ${
                    doneSteps.has(i) ? "line-through text-brand-dark/35" : "text-brand-dark"
                  }`}>
                    {step}
                  </p>
                </button>
              ))}

              {doneSteps.size === steps.length && steps.length > 0 && (
                <div className="bg-green-50 border border-green-200/60 rounded-2xl p-5 text-center">
                  <p className="text-green-600 font-black text-lg" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                    <Confetti size={22} weight="bold" className="inline-block mr-2 align-middle" />{t.recettes.detail.enjoy}
                  </p>
                </div>
              )}

              <button
                onClick={() => setDoneSteps(new Set())}
                className={`text-[11px] text-brand-dark/30 hover:text-brand-dark transition-colors underline underline-offset-2 ${doneSteps.size === 0 ? "invisible" : ""}`}
              >
                {t.recettes.detail.restart}
              </button>

              {/* Astuces */}
              {astuces.length > 0 && (
                <div className="bg-brand-yellow/10 border border-brand-yellow/30 rounded-3xl p-5 space-y-3">
                  <h2 className="text-base font-black text-brand-dark flex items-center gap-2" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                    <Lightbulb size={15} weight="fill" className="text-brand-yellow" />
                    Astuces
                  </h2>
                  <ul className="space-y-2">
                    {astuces.map((tip, i) => (
                      <li key={i} className="flex items-start gap-3 text-sm text-brand-dark/80 leading-relaxed">
                        <span className="w-5 h-5 rounded-full bg-brand-yellow/40 text-brand-dark text-[10px] font-black flex items-center justify-center flex-shrink-0 mt-0.5">{i + 1}</span>
                        {tip}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Bien fait */}
              {bien_fait.length > 0 && (
                <div className="bg-green-50 border border-green-200/60 rounded-3xl p-5 space-y-3">
                  <h2 className="text-base font-black text-brand-dark flex items-center gap-2" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                    <SealCheck size={15} weight="fill" className="text-green-500" />
                    Comment savoir si c'est bien fait ?
                  </h2>
                  <ul className="space-y-2">
                    {bien_fait.map((tip, i) => (
                      <li key={i} className="flex items-start gap-3 text-sm text-brand-dark/80 leading-relaxed">
                        <span className="w-5 h-5 rounded-full bg-green-200 flex items-center justify-center flex-shrink-0 mt-0.5">
                          <span className="text-green-700 text-[10px] font-black">✓</span>
                        </span>
                        {tip}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          )}

        </div>
      </div>
    </section>
  );
}
