"use client";

import Review from "@/components/Review";
import Footer from "@/components/Footer";
import Image from "next/image";
import { useRef, useState, useEffect } from "react";
import Link from "next/link";
import api from "@/api/axios";
import { useRouter } from "next/navigation";
import {useLanguage} from "@/context/LanguageContext";
interface Product {
  id: number;
  name: string;
  short_description: string;
  description: string | null;
  slug: string;
  image: string;
  has_variation: boolean;
  price: string;
  template_type: string;
  currency: {
    id: number;
    name: string;
    symbol: string;
  };
  sort_order: number;
  variations: Array<{
    id: number;
    name: string;
    sort_order: number;
    price: number;
    currency: {
      id: number;
      name: string;
      symbol: string;
      code: string | null;
    };
  }>;
}

interface HomeBox {
  id: number;
  name: string;
  description: string;
  img: string;
  sort_order: number;
}

interface Step {
  id: number;
  name: string;
  description: string;
  sort_order: number;
}

interface FAQ {
  id: number;
  question: string;
  answer: string;
  sort_order: number;
}

interface Testimonial {
  id: number;
  name: string;
  description: string;
  rating: number;
  sort_order: number;
}

interface HomeData {
  products: Product[];
  home_boxes: HomeBox[];
  steps: Step[];
  faq: FAQ[];
  testimonials: Testimonial[];
}

export default function HomePage() {
  const [homeData, setHomeData] = useState<HomeData | null>(null);
  const [loading, setLoading] = useState(true);
  const [currentIndex, setCurrentIndex] = useState(1);
  const [showUpload, setShowUpload] = useState(false);
  const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
  const router = useRouter();
  const { lang, changeLang, t } = useLanguage();

  useEffect(() => {
    fetchHomeData();
  }, [lang]);
  const fetchHomeData = async () => {
    try {
      setLoading(true);
      setHomeData(null); // مهم حتى لا يبقى المحتوى القديم ظاهر

      const response = await api.get("/home", {
        headers: {
          "Accept-Language": lang,
        },
      });

      if (response.data.success) {
        setHomeData(response.data.data);
      }
    } catch (error) {
      console.error("Error fetching home data:", error);
    } finally {
      setLoading(false);
    }
  };


  const scrollToIndex = (idx: number) => {
    const node = itemRefs.current[idx];
    if (node) {
      node.scrollIntoView({
        behavior: "smooth",
        inline: "center",
        block: "nearest",
      });
      setCurrentIndex(idx);
    }
  };

  const prev = () => {
    if (!homeData?.testimonials) return;
    const nextIdx =
      currentIndex === 0 ? homeData.testimonials.length - 1 : currentIndex - 1;
    scrollToIndex(nextIdx);
  };

  const next = () => {
    if (!homeData?.testimonials) return;
    const nextIdx =
      currentIndex === homeData.testimonials.length - 1 ? 0 : currentIndex + 1;
    scrollToIndex(nextIdx);
  };

  const showUploadModal = () => {
    setShowUpload(true);
  };

  const ProductUploadModal = () => {
    if (!showUpload || !homeData?.products) return null;

    return (
      <div
        onClick={() => setShowUpload(false)}
        className="fixed inset-0 bg-black/60 z-50 flex items-end justify-center"
      >
        <div
          onClick={(e) => e.stopPropagation()}
          className="bg-white rounded-t-3xl p-6 w-full max-w-md shadow-2xl animate-slide-up"
        >
          <div className="grid grid-cols-2 gap-4">
            {homeData.products.map((product: any) => (
              <Link key={product.id} href={`/products/${product.id}/${product.slug}`}>
                <div className="cursor-pointer">
                  {/* Image Container */}
                  <div
                    className="
                    relative 
                    w-full h-[120px] md:h-[140px]
                    lg:h-[140px]
                    rounded-[10px] 
                    overflow-hidden"
                  >
                    <img
                      src={product.image}
                      alt={product.name}
                      className="w-full h-full object-cover"
                    />

                    {/* Product Name Overlay */}
                    <div
                      className="
            absolute bottom-0 left-0 w-full
            px-2 py-2
            text-white text-[12px] font-semibold
            text-center
          "
                      style={{
                        background:
                          "linear-gradient(180deg, #10141800 0%, #3D3D3D8C 55%, #787878 100%)",
                      }}
                    >
                      {product.name}
                    </div>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </div>
    );
  };

  if (loading || !homeData) {
    return (
        <div className="min-h-screen flex items-center justify-center bg-white text-primary">
          <div className="flex flex-col items-center gap-4">
            <div className="w-10 h-10 border-4 border-pink-200 border-t-primary rounded-full animate-spin" />
            <p className="text-sm font-medium">
              {lang === "ar" ? "جاري تحميل المحتوى..." : "Loading content..."}
            </p>
          </div>
        </div>
    );
  }
  return (
    <div className="text-white relative overflow-hidden">
      {/* ===== خلفية الفيديو ===== */}
      <div className="relative h-[600px] overflow-hidden">
        <video
          autoPlay
          loop
          muted
          playsInline
          className="absolute top-0 left-0 w-full h-full object-cover"
        >
          <source src="/images/YallaCheese.mp4" type="video/mp4" />
        </video>
        <div className="absolute inset-0 bg-black/30" />

        <section className="relative z-10 flex flex-col items-center justify-center h-full text-center text-white px-4">
          <h1 className="text-3xl md:text-5xl font-bold mb-4">
            {t("slider_desc")}
          </h1>
          <p className="max-w-xl mx-auto mb-6 text-style">
            {t("slider_second_desc")}
          </p>
          <button
              className="cursor-pointer blur-btn-style bg-white/20 border border-white/30 hover:bg-white/30 transition px-6 py-3 rounded-lg"
              onClick={showUploadModal}
          >
            {t("start_your_journey")}
          </button>
        </section>
      </div>

      {/* ===== قسم اللوحات ===== */}
      <section className="bg-white py-5 text-center text-gray-800 relative z-20">
        <h2 className="text-xl md:text-3xl text-secondary font-semibold flex justify-center items-center">
          {t("start_with_stoy")} <span className="text-primary mr-2"> &nbsp;{t("now")}!</span>
          <img
            src="/icons/letter.svg"
            alt=""
            className="mb-12 relative left-2"
          />
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-6 px-8 max-w-6xl mx-auto">
          {homeData?.products.map((product, i) => (
            <Link
              href={`/products/${product.id}/${product.slug}`}
              key={product.id}
              className="bg-white photos-cards-style overflow-hidden hover:shadow-xl transition transform hover:-translate-y-1 block"
            >
              <img
                src={product.image}
                alt={product.name}
                className="w-full h-48 p-3 rounded-[6px] object-cover"
              />
              <div className="p-4 text-center">
                <h3 className="card-title mb-2">{product.name}</h3>
                <p className="card-description">{product.short_description}</p>
              </div>
            </Link>
          ))}
        </div>
      </section>

      {/* ===== قسم الخدمات ===== */}
      <section className="bg-white py-10 text-center text-gray-800 relative z-20 mb-10">
        <h2 className="text-xl md:text-3xl text-secondary font-semibold mb-10 flex justify-center items-center">
          {t("we_are_here")}
          <span className="text-primary flex mr-2"> &nbsp;{t("your_needs")}</span>
          <img
            src="/icons/letter.svg"
            alt=""
            className="mb-12 relative left-2"
          />
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6 px-8 max-w-6xl mx-auto">
          {homeData?.home_boxes.map((card, i) => (
            <div
              key={card.id}
              className="bg-white services-cards-style overflow-hidden hover:shadow-xl transition transform hover:-translate-y-1"
            >
              <img
                src={card.img}
                alt={card.name}
                className="w-full h-48 p-3 rounded-[6px] object-cover"
              />
              <div className="p-4 text-center">
                <h3 className="card-title mb-2">{card.name}</h3>
                <p className="card-description">{card.description}</p>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* ===== قسم الخطوات ===== */}
      <section className="bg-steps py-10 text-center text-gray-800 relative z-20 mb-10">
        <h2 className="text-lg md:text-3xl text-secondary font-semibold mb-16 flex justify-center items-center">
          {t("memories")}&nbsp;
          <span className="text-primary mr-2">{t("touched")}!</span>
          <img
            src="/icons/letter.svg"
            alt=""
            className="mb-12 relative left-2"
          />
        </h2>

        <div className="relative max-w-5xl mx-auto px-6">
          <img
            src="/svg/stepsGroup.svg"
            alt="steps line"
            className="absolute top-0 left-1/2 transform -translate-x-1/2 h-full hidden md:block"
          />

          <div className="flex flex-col gap-20 relative">
            {homeData?.steps.map((step, index) => (
              <div
                key={step.id}
                className={`flex flex-col md:flex-row items-center justify-between ${index % 2 === 1 ? "md:flex-row-reverse" : ""
                  }`}
              >
                <div
                  className={`w-full md:w-1/2 ${index % 2 === 0 ? "order-1 md:order-2" : "order-1"
                    } flex justify-center mb-8 md:mb-0`}
                >
                  <img
                    src={`/svg/step${index + 1}.svg`}
                    alt={`step ${index + 1}`}
                    className="w-60 md:w-72"
                  />
                </div>
                <div
                    className={`w-full md:w-1/2 ${
                        index % 2 === 0
                            ? `order-2 md:order-1 ${lang === "ar" ? "text-right pl-10" : "text-left pr-10"}`
                            : `${lang === "ar" ? "text-right pr-[70px]" : "text-left pl-[70px]"}`
                    }`}
                >
                  <h4 className="text-xl text-primary font-bold mb-3">
                    {step.name}
                  </h4>
                  <p className="text-gray-600 whitespace-pre-line">
                    {step.description}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* كل صورة حكاية Section */}
      <section className="relative bg-white py-10 overflow-hidden mb-10">
        <div className="w-full hidden md:block">
          {/* --- TOP ROW (5 صور) --- */}
          <div className="flex items-center justify-between gap-4 mb-6">
            <div className="w-1/5 overflow-hidden rounded-2xl">
              <img
                src="/images/photo1.png"
                alt=""
                className="w-full h-40 object-cover object-left-top"
              />
            </div>

            <div className="w-1/5 overflow-hidden rounded-2xl">
              <img
                src="/images/photo2.png"
                alt=""
                className="w-full h-40 object-cover object-center"
              />
            </div>

            <div className="w-1/5 flex items-center justify-center relative">
              <h3 className="text-6xl md:text-8xl font-extrabold text-primary pointer-events-none">
                {t("each")}
              </h3>
            </div>

            <div className="w-1/5 overflow-hidden rounded-2xl">
              <img
                src="/images/photo3.png"
                alt=""
                className="w-full h-40 object-cover object-center"
              />
            </div>

            <div className="w-1/5 overflow-hidden rounded-2xl">
              <img
                src="/images/photo4.png"
                alt=""
                className="w-full h-40 object-cover object-right-top"
              />
            </div>
          </div>

          {/* --- MIDDLE ROW (3 صور) --- */}
          <div className="flex items-center justify-between gap-4 mb-6">
            <div className="overflow-hidden rounded-2xl h-40">
              <img
                src="/images/photo7.png"
                alt=""
                className="w-full h-full object-cover"
              />
            </div>
            <div>
              <h3 className="md:text-7xl font-bold text-primary pointer-events-none">
                {t("picture")}
              </h3>
            </div>
            <div className="w-1/2 flex items-center justify-center relative">
              <div className="grid grid-cols-2 gap-4">
                <div className="overflow-hidden rounded-2xl">
                  <img
                    src="/images/photo6.png"
                    alt=""
                    className="w-full h-full object-cover"
                  />
                </div>
                <div className="w-full overflow-hidden rounded-2xl">
                  <img
                    src="/images/photo5.png"
                    alt=""
                    className="w-full h-40 object-cover object-right"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* --- BOTTOM ROW (3 صور) --- */}
          <div className="flex items-center justify-between gap-4 mt-6">
            <div className="w-full overflow-hidden rounded-2xl">
              <img
                src="/images/photo8.png"
                alt=""
                className="w-full h-40 object-cover object-right"
              />
            </div>
            <h3 className="text-5xl md:text-7xl font-extrabold text-primary pointer-events-none">
                {t("story")}
            </h3>
            <div className="w-full overflow-hidden rounded-2xl">
              <img
                src="/images/photo9.png"
                alt=""
                className="w-full h-40 object-cover object-left"
              />
            </div>
            <div className="flex gap-3">
              <div className="overflow-hidden rounded-2xl w-36 h-40">
                <img
                  src="/images/photo10.png"
                  alt=""
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="overflow-hidden rounded-2xl w-36 h-40">
                <img
                  src="/images/photo11.png"
                  alt=""
                  className="w-full h-full object-cover"
                />
              </div>
            </div>
          </div>
        </div>
        <div className="mobile-grid md:hidden">
          <img src="/images/photo1.png" alt="" />
          <img src="/images/photo2.png" alt="" />
          <h3>كل</h3>
          <img src="/images/photo3.png" alt="" />
          <img src="/images/photo4.png" alt="" />
          <img src="/images/photo5.png" alt="" />
          <h3>صورة</h3>
          <img src="/images/photo6.png" alt="" />
          <img src="/images/photo7.png" alt="" />
          <img src="/images/photo8.png" alt="" />
          <h3>حكاية</h3>
          <img src="/images/photo10.png" alt="" />
          <img src="/images/photo11.png" alt="" />
        </div>
      </section>

      {/* ===== قسم كل ما تحتاج لمعرفته قبل الطلب ===== */}
      <section className="bg-[#FBFBFB] py-10 text-gray-800 relative z-20 mb-10">
        <div className="max-w-5xl mx-auto px-6 mb-10">
          <h2 className="text-xl md:text-3xl text-secondary font-semibold text-center mb-12 flex justify-center items-center">
            {t("anythings_before_sale")} <span className="text-primary">&nbsp;{t("the_order")}.</span>
            <img
              src="/icons/letter.svg"
              alt=""
              className="mb-12 relative left-2"
            />
          </h2>

          <div className="space-y-0">
            {homeData?.faq.slice(0, 3).map((faq, index) => (
              <details
                key={faq.id}
                className={`group ${index === 0
                  ? "shipping-qus-section border border-[#F1F2F9] hover:bg-pink-100"
                  : "bg-white border border-[#F1F2F9] hover:bg-gray-50"
                  } transition cursor-pointer`}
              >
                <summary className="flex justify-between items-center p-9 text-lg font-semibold headers">
                  <div className="flex items-center gap-3">
                    <img
                      src={
                        index === 0 ? "/icons/worldwide.svg" : "/icons/user.svg"
                      }
                      alt="icon"
                      className="w-8 h-8"
                    />
                    <span>{faq.question}</span>
                  </div>
                  <span className="transition-transform duration-300 group-open:rotate-180">
                    <Image
                      src={`/icons/arrow${index === 0 ? "1" : "2"}.svg`}
                      alt="arrow"
                      width={20}
                      height={20}
                      className="transition-transform duration-300"
                    />
                  </span>
                </summary>
                <div className="px-12 pb-4 text-[#6F6C8F]">
                  {faq.answer || "لا توجد تفاصيل إضافية متاحة."}
                </div>
              </details>
            ))}
          </div>
        </div>
      </section>

      {/* اراء صادقة */}
      <section className="bg-white py-10 text-gray-800 mb-10  overflow-hidden">
        <div className="w-full">
          <h2 className="text-xl md:text-3xl font-semibold text-center text-secondary mb-12 flex justify-center items-center">
            {t("honest_reviews_from")}&nbsp;
            <span className={`text-primary ${lang === "ar" ? "mr-2" : "ml-2"}`}>
        {t("happy_customers")} !
      </span>
            <Image
                src="/icons/letter.svg"
                alt=""
                width={28}
                height={28}
                className={`mb-12 relative ${lang === "ar" ? "left-2" : "right-2"}`}
            />
          </h2>

          <div className="relative">
            <div
                className="overflow-x-auto no-scrollbar"
                style={{
                  scrollSnapType: "x mandatory",
                  scrollPadding: "0",
                }}
                role="region"
                aria-label={lang === "ar" ? "شهادات العملاء" : "Customer testimonials"}
            >
              <div
                  className="flex items-center justify-center gap-6 px-[60px]"
                  style={{
                    gap: "24px",
                    padding: "0",
                    margin: "0",
                  }}
              >
                {homeData?.testimonials.map((item, i) => (
                    <div
                        key={item.id}
                        ref={(el) => {
                          itemRefs.current[i] = el;
                        }}
                        className={`flex-shrink-0 transition-transform duration-300 snap-center ${
                            i === currentIndex ? "scale-100" : "scale-95 opacity-80"
                        }`}
                    >
                      <Review
                          name={item.name}
                          description={item.description}
                          rating={item.rating}
                      />
                    </div>
                ))}
              </div>
            </div>

            <div
                className={`flex items-center justify-center  gap-4 mt-6`}
            >
              <button
                  onClick={prev}
                  aria-label={lang === "ar" ? "السابق" : "Previous"}
                  className="cursor-pointer"
              >
                <Image
                    src={lang === "ar" ? "/icons/arrow3.svg" : "/icons/arrow4.svg"}
                    alt=""
                    width={20}
                    height={20}
                />
              </button>

              <button
                  onClick={next}
                  aria-label={lang === "ar" ? "التالي" : "Next"}
                  className="cursor-pointer"
              >
                <Image
                    src={lang === "ar" ? "/icons/arrow4.svg" : "/icons/arrow3.svg"}
                    alt=""
                    width={20}
                    height={20}
                />
              </button>
            </div>
          </div>
        </div>

        <style jsx>{`
    .no-scrollbar::-webkit-scrollbar {
      display: none;
    }
    .no-scrollbar {
      -ms-overflow-style: none;
      scrollbar-width: none;
    }
  `}</style>
      </section>

      <section className="relative py-10 flex justify-center bg-white mb-10">
        <div className="relative w-full max-w-5xl rounded-[45px] px-8 py-8 text-center text-white overflow-hidden ready-section">
          <h2 className="text-[86px] font-bold">{t("are_you_ready")}</h2>
          <p className="mb-8 text-base max-w-2xl mx-auto">
            {t("home_desc")}
          </p>
          <div className="mx-auto w-max cursor-pointer">
            <div className="mx-auto flex justify-center">
              <div className="relative w-[250px] h-[86px] rounded-full bg-white/80 shadow-[0_8px_25px_rgba(0,0,0,0.28)] select-none pointer-events-none overflow-visible">
                {/* النص */}
                <span
                    className={`absolute top-1/2 -translate-y-1/2 text-primary text-[38px] font-bold ${
                        lang === "ar" ? "left-[55px]" : "left-[50px]"
                    }`}
                >
      {lang === "ar" ? "نعم" : "Yes"}
    </span>

                {/* الدائرة */}
                <div className="absolute right-[-2px] top-1/2 -translate-y-1/2 w-[96px] h-[96px] rounded-full bg-[#E9ECF3] border-[6px] border-white shadow-[0_7px_14px_rgba(0,0,0,0.25)]" />
              </div>
            </div>
          </div>
        </div>
      </section>
      <Footer />
      <ProductUploadModal />
      <button
        onClick={showUploadModal}
        className="fixed bottom-2 left-1/2 transform -translate-x-1/2 block login-btn transition mt-8 cursor-pointer md:hidden bg-primary text-white px-6 w-[343px] h-[48px] py-3 rounded-full z-20">
        ابدأ الآن
      </button>
    </div>
  );
}
