"use client";

import React, { useState, useCallback, useRef, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { useLocale, useTranslations } from "next-intl";
import { FaSearch } from "react-icons/fa";
import { IoClose } from "react-icons/io5";
import useHome from "@/hooks/use-home";
import { transformProduct } from "@/lib/markatty-transformer";
import { ProductsSectionBalmy } from "@/components/balmy";
import ProductCard from "@/components/ProductCard";
import Loading from "@/components/loading";
import PageWrapper from "@/components/page-wrapper";
import { useAppDispatch } from "@/store/hooks";
import { addToCart, setCartOpen } from "@/store/slices/cart-slice";
import { mapProductFromApi } from "@/lib/mappers/product-mapper";
import toast from "react-hot-toast";

export default function TabbyTamaraPage() {
    const dispatch = useAppDispatch();
    const locale = useLocale();
    const t = useTranslations("tabby-tamara");
    const { loading, data } = useHome();

    // Search state
    const [searchTerm, setSearchTerm] = useState("");
    const [searchResults, setSearchResults] = useState<any[]>([]);
    const [isSearching, setIsSearching] = useState(false);
    const [showResults, setShowResults] = useState(false);
    const searchRef = useRef<HTMLDivElement>(null);
    const debounceRef = useRef<NodeJS.Timeout | null>(null);

    // Close results when clicking outside
    useEffect(() => {
        const handleClickOutside = (e: MouseEvent) => {
            if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
                setShowResults(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    // Search API call
    const performSearch = useCallback(async (term: string) => {
        if (!term.trim()) {
            setSearchResults([]);
            setShowResults(false);
            return;
        }

        setIsSearching(true);
        setShowResults(true);

        try {
            const res = await fetch(
                `/api/search?q=${encodeURIComponent(term.trim())}&locale=${locale}`,
                { credentials: "include" }
            );
            const data = await res.json();

            // Markatty searchsuggestion returns productCollection or products array
            const products = data?.productCollection || data?.products || (Array.isArray(data) ? data : []);
            setSearchResults(products.slice(0, 8));
        } catch (error) {
            console.error("Search failed:", error);
            setSearchResults([]);
        } finally {
            setIsSearching(false);
        }
    }, []);

    // Debounced search on input change
    const handleSearchChange = (value: string) => {
        setSearchTerm(value);
        if (debounceRef.current) clearTimeout(debounceRef.current);
        debounceRef.current = setTimeout(() => performSearch(value), 400);
    };

    const clearSearch = () => {
        setSearchTerm("");
        setSearchResults([]);
        setShowResults(false);
    };

    const handleAddToCart = async (productId: number) => {
        try {
            await dispatch(addToCart({ productId, productQTY: 1 })).unwrap();
            toast.success("تمت الإضافة إلى السلة");
            dispatch(setCartOpen(true));
        } catch (error: any) {
            toast.error(error?.message || "Failed to add to cart");
            throw error;
        }
    };

    // Extract the first category section with products (best sellers)
    const homeSections = data?._raw?.homeSections || data?.homeSections || [];
    const firstCategorySection = homeSections.find(
        (section: any) => section.type === "category" && section.data?.productList?.length > 0
    );
    const bestSellerProducts = firstCategorySection?.data?.productList?.map(transformProduct) || [];

    return (
        <div className="min-h-screen bg-white font-cairo" dir="rtl">
            {/* Search Bar - Full Width matching header padding */}
            <div className="w-full max-w-[1920px] mx-auto px-4 lg:px-16 py-4" ref={searchRef}>
                <div className="relative">
                    <div className="flex items-center w-full border border-gray-300 rounded-lg px-4 py-3 focus-within:border-gray-500 transition-colors">
                        <input
                            type="text"
                            value={searchTerm}
                            placeholder={t("search-placeholder")}
                            className="flex-1 text-[14px] md:text-[16px] text-black font-cairo text-right bg-transparent outline-none placeholder:text-gray-400"
                            onChange={(e) => handleSearchChange(e.target.value)}
                            onFocus={() => { if (searchResults.length > 0) setShowResults(true); }}
                        />
                        {searchTerm ? (
                            <button onClick={clearSearch} className="text-gray-400 hover:text-gray-600 ml-2">
                                <IoClose className="text-lg" />
                            </button>
                        ) : null}
                        <FaSearch className="text-gray-400 text-sm" />
                    </div>

                    {/* Search Results Dropdown */}
                    {showResults && (
                        <div className="absolute top-full left-0 right-0 mt-2 bg-white border border-gray-200 rounded-xl shadow-lg z-50 max-h-[70vh] overflow-y-auto">
                            {isSearching ? (
                                <div className="flex items-center justify-center py-10">
                                    <Loading variant="spinner" size="md" />
                                </div>
                            ) : searchResults.length > 0 ? (
                                <div className="p-4">
                                    <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                                        {searchResults.map((rawProduct: any, index: number) => {
                                            const product = mapProductFromApi(rawProduct);
                                            return (
                                                <ProductCard
                                                    key={product?.id || index}
                                                    product={product}
                                                    onAddToCart={handleAddToCart}
                                                />
                                            );
                                        })}
                                    </div>
                                </div>
                            ) : (
                                <div className="text-center py-10 text-gray-400 font-cairo">
                                    {t("no-results")}
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </div>

            {/* Hero Banner - Full Width with same padding */}
            <div className="w-full max-w-[1920px] mx-auto px-4 lg:px-16">
                <section className="w-full bg-[#F7F7F7] py-10 md:py-14 rounded-xl">
                    <div className="px-4 md:px-8 lg:px-16 max-w-5xl mx-auto">
                        <div className="flex flex-col items-center text-center gap-6 md:gap-8">
                            {/* Logos Row */}
                            <div className="flex items-center justify-center gap-6 md:gap-10 flex-wrap">
                                {/* Tamara Logo */}
                                <Image
                                    src="/images/tamarra-removebg-preview.png"
                                    alt="Tamara"
                                    width={360}
                                    height={110}
                                    className="h-[70px] md:h-[100px] w-auto object-contain"
                                />

                                {/* Tabby Logo */}
                                <Image
                                    src="/assets/images/tabby-badge.png"
                                    alt="Tabby"
                                    width={300}
                                    height={110}
                                    className="h-[70px] md:h-[100px] w-auto object-contain"
                                />
                            </div>

                            {/* Steps Row with Dividers */}
                            <div className="flex items-stretch justify-center w-full max-w-3xl mt-2 md:mt-4">
                                {/* Step 1 (rightmost in RTL) */}
                                <div className="flex-1 flex items-center px-3 md:px-5">
                                    <p className="text-[13px] md:text-lg text-[#333] leading-relaxed text-right font-cairo">
                                        <span className="font-bold">{t("step1-title")}</span>{" "}{t("step1-desc")}{" "}{t("step3-desc")}{" "}{t("step3-extra")}
                                    </p>
                                </div>

                                {/* Vertical Divider */}
                                <div className="w-px bg-[#D0D0D0] self-stretch my-1" />

                                {/* Step 3 - اضف الطلب لسلتك */}
                                <div className="flex-1 flex items-center px-3 md:px-5">
                                    <p className="text-[13px] md:text-lg text-[#333] leading-relaxed text-right font-cairo">
                                        {t("step3-title")}
                                    </p>
                                </div>

                                {/* Vertical Divider */}
                                <div className="w-px bg-[#D0D0D0] self-stretch my-1" />

                                {/* Step 2 - اختر طريقة الدفع المفضلة لديك */}
                                <div className="flex-1 flex items-center px-3 md:px-5">
                                    <p className="text-[13px] md:text-lg text-[#333] leading-relaxed text-right font-cairo">
                                        {t("step2-title")}{" "}{t("step2-desc")}
                                    </p>
                                </div>
                            </div>

                            {/* Shop Now Button */}
                            <Link
                                href={`/${locale}/home`}
                                className="w-full max-w-xl bg-[#1A1A1A] text-white text-center py-4 rounded-[14px] text-[20px] md:text-[24px] font-bold hover:bg-[#333] transition-colors mt-2 block"
                            >
                                {t("shop-now")}
                            </Link>
                        </div>
                    </div>
                </section>
            </div>

            {/* Best Sellers Section - Full Width like home page */}
            <PageWrapper yPadding="py-2.5">
                <div className="my-8 flex flex-col gap-6 relative">
                    {/* Section Header with home link */}
                    <div className="flex items-center justify-between" dir="rtl">
                        <h2 className="text-[22px] md:text-[28px] font-bold text-black font-cairo tracking-wide">
                            {t("best-sellers")}
                        </h2>
                        <Link
                            href={`/${locale}/home`}
                            className="text-[15px] md:text-[16px] text-black hover:underline font-cairo"
                        >
                            {t("home")}
                        </Link>
                    </div>

                    {/* Products from API */}
                    {loading ? (
                        <Loading variant="spinner" size="lg" />
                    ) : bestSellerProducts.length > 0 ? (
                        <ProductsSectionBalmy
                            title=""
                            products={bestSellerProducts}
                            maxProducts={8}
                            showViewAll={false}
                        />
                    ) : (
                        <div className="text-center py-10 text-gray-400 font-cairo">
                            لا توجد منتجات متاحة حالياً
                        </div>
                    )}
                </div>
            </PageWrapper>
        </div>
    );
}
