"use client";

import React, { useState } from "react";
import Link from "next/link";
import { BusinessSubCategory } from "@/types/category";
import { Vendor } from "@/types/vendor";
import { RiStore2Line, RiFilter3Line, RiRestaurantLine, RiArrowRightSLine } from "react-icons/ri";

interface FoodCategorySectionProps {
    categoryId: string;
    subcategories: BusinessSubCategory[];
    vendors: Vendor[];
    isLoadingSubcategories: boolean;
    isLoadingVendors: boolean;
    searchQuery: string;
}

export default function FoodCategorySection({
    categoryId,
    subcategories,
    vendors,
    isLoadingSubcategories,
    isLoadingVendors,
    searchQuery,
}: FoodCategorySectionProps) {
    const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<string>("all");

    // Default fallback image for restaurants
    const defaultRestaurantImg = "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=500&auto=format&fit=crop&q=60";
    // Default fallback image for subcategories
    const defaultSubCategoryImg = "https://images.unsplash.com/photo-1504674900247-0877df9cc836?w=500&auto=format&fit=crop&q=60";

    // Filter subcategories by search query
    const filteredSubcategories = subcategories.filter((sub) =>
        sub.name.toLowerCase().includes(searchQuery.toLowerCase())
    );

    // Filter vendors by search query
    const filteredVendors = vendors.filter((vendor) => {
        const matchesName = vendor.business_name.toLowerCase().includes(searchQuery.toLowerCase());
        const matchesSubName = vendor.sub_category?.name?.toLowerCase().includes(searchQuery.toLowerCase());
        return matchesName || matchesSubName;
    });

    // Helper to get vendors for a specific subcategory
    const getVendorsForSubcategory = (subId: string) => {
        return filteredVendors.filter(
            (v) =>
                v.business_sub_category_id === subId ||
                v.sub_category?.id === subId ||
                (v.sub_category &&
                    subcategories.find((s) => s.id === subId)?.name.toLowerCase() ===
                        v.sub_category.name.toLowerCase())
        );
    };

    // Calculate count of restaurants for a subcategory
    const getVendorCountForSubcategory = (subId: string) => {
        return getVendorsForSubcategory(subId).length;
    };

    const isSearching = searchQuery.trim().length > 0;

    return (
        <div className="space-y-6 pb-6">
            {/* SUBCATEGORY SELECTION GRID (SAME AS OTHER CATEGORIES) */}
            <section className="px-4 pt-4">
                <div className="flex items-center justify-between mb-3">
                    <h2 className="text-sm font-bold text-gray-900 uppercase tracking-wide flex items-center gap-1.5">
                        <RiRestaurantLine className="text-purple-600" size={18} />
                        Food & Beverage Subcategories
                    </h2>
                    {selectedSubCategoryId !== "all" && (
                        <button
                            onClick={() => setSelectedSubCategoryId("all")}
                            className="text-xs font-semibold text-purple-600 hover:text-purple-800 transition cursor-pointer"
                        >
                            Show All
                        </button>
                    )}
                </div>

                {isLoadingSubcategories ? (
                    <div className="grid grid-cols-2 gap-4">
                        {[1, 2, 3, 4].map((n) => (
                            <div key={n} className="h-36 sm:h-40 bg-zinc-200 rounded-2xl animate-pulse" />
                        ))}
                    </div>
                ) : filteredSubcategories.length === 0 ? (
                    <div className="p-4 border border-dashed border-gray-200 rounded-xl text-center text-xs text-gray-500">
                        No food subcategories found.
                    </div>
                ) : (
                    <div className="grid grid-cols-2 gap-4">
                        {filteredSubcategories.map((sub) => {
                            const isSelected = selectedSubCategoryId === sub.id;
                            const count = getVendorCountForSubcategory(sub.id);
                            const imgUrl = sub.image || defaultSubCategoryImg;

                            return (
                                <div
                                    key={sub.id}
                                    onClick={() => setSelectedSubCategoryId(isSelected ? "all" : sub.id)}
                                    className={`group relative block h-36 sm:h-40 overflow-hidden rounded-2xl cursor-pointer border-2 transition duration-300 ${
                                        isSelected
                                            ? "border-purple-600 ring-2 ring-purple-500/30 scale-[1.02]"
                                            : "border-transparent"
                                    }`}
                                >
                                    <img
                                        src={imgUrl}
                                        alt={sub.name}
                                        className="w-full h-full object-cover transition duration-500 group-hover:scale-110"
                                    />

                                    <span className="absolute top-2.5 right-2.5 bg-black/60 backdrop-blur-xs text-white text-[10px] font-bold px-2 py-0.5 rounded-full">
                                        {count} {count === 1 ? "Store" : "Stores"}
                                    </span>

                                    <div className="absolute bottom-3 left-3 right-3 text-left">
                                        <h3 className="text-base font-bold text-white leading-tight">
                                            {sub.name}
                                        </h3>
                                        <p className="text-[11px] text-purple-200 font-medium flex items-center gap-1 mt-0.5">
                                            {isSelected ? "Selected (Tap to reset)" : "Explore restaurants →"}
                                        </p>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </section>

            {/* RESTAURANTS FOR YOU (POPULAR SLIDER - ONLY WHEN "ALL" IS SELECTED AND NOT SEARCHING) */}
            {selectedSubCategoryId === "all" && !isSearching && filteredVendors.length > 0 && (
                <section className="px-4 bg-slate-100 py-4">
                    <div className="flex justify-between items-center mb-3">
                        <h3 className="font-bold text-gray-900 text-sm tracking-wide text-left">
                            Top Restaurants For You
                        </h3>
                        <span className="text-xs text-gray-500 font-medium">Handpicked</span>
                    </div>
                    <div className="flex gap-4 no-scrollbar overflow-x-auto">
                        {isLoadingVendors ? (
                            [1, 2, 3, 4].map((n) => (
                                <div key={n} className="min-w-[130px] animate-pulse">
                                    <div className="w-[130px] h-[85px] bg-zinc-200 rounded-xl" />
                                    <div className="h-3 bg-zinc-200 rounded mt-2 w-3/4 mx-auto" />
                                </div>
                            ))
                        ) : (
                            filteredVendors.slice(0, 6).map((vendor) => {
                                const shopPhoto = vendor.kycdetail?.shop_photo?.url || defaultRestaurantImg;
                                return (
                                    <Link
                                        key={`top-${vendor.id}`}
                                        href={`/category/${categoryId}/subcategory/${vendor.business_sub_category_id}?vendorId=${vendor.id}`}
                                        className="min-w-[130px] max-w-[130px] block active:scale-[0.98] transition text-center group"
                                    >
                                        <div className="relative overflow-hidden rounded-xl shadow-sm">
                                            <img
                                                src={shopPhoto}
                                                alt={vendor.business_name}
                                                className="w-[130px] h-[85px] object-cover group-hover:scale-105 transition duration-300"
                                            />
                                            {vendor.sub_category?.name && (
                                                <span className="absolute bottom-1 left-1 bg-black/60 backdrop-blur-xs text-white text-[9px] px-1.5 py-0.5 rounded font-medium truncate max-w-[120px]">
                                                    {vendor.sub_category.name}
                                                </span>
                                            )}
                                        </div>
                                        <p className="text-[13px] mt-1.5 px-1 truncate font-semibold text-gray-800 text-center group-hover:text-purple-700 transition">
                                            {vendor.business_name}
                                        </p>
                                    </Link>
                                );
                            })
                        )}
                    </div>
                </section>
            )}

            {/* RESTAURANTS GROUPED BY SUBCATEGORY (OR FILTERED SUBCATEGORY VIEW) */}
            <section className="px-4 space-y-6">
                {isLoadingVendors ? (
                    <div className="space-y-4">
                        {[1, 2].map((n) => (
                            <div key={n} className="space-y-3 animate-pulse">
                                <div className="h-5 bg-zinc-200 rounded w-1/3" />
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div className="h-44 bg-zinc-200 rounded-xl" />
                                    <div className="h-44 bg-zinc-200 rounded-xl" />
                                </div>
                            </div>
                        ))}
                    </div>
                ) : selectedSubCategoryId !== "all" ? (
                    /* SINGLE SELECTED SUBCATEGORY VIEW */
                    (() => {
                        const activeSub = subcategories.find((s) => s.id === selectedSubCategoryId);
                        const subVendors = getVendorsForSubcategory(selectedSubCategoryId);

                        return (
                            <div className="space-y-4">
                                <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                                    <div>
                                        <h3 className="text-base font-bold text-gray-900">
                                            {activeSub?.name || "Subcategory Restaurants"}
                                        </h3>
                                        <p className="text-xs text-gray-500">
                                            Showing {subVendors.length} {subVendors.length === 1 ? "restaurant" : "restaurants"}
                                        </p>
                                    </div>
                                    <button
                                        onClick={() => setSelectedSubCategoryId("all")}
                                        className="text-xs font-semibold text-purple-600 bg-purple-50 px-3 py-1.5 rounded-full hover:bg-purple-100 transition flex items-center gap-1 cursor-pointer"
                                    >
                                        <RiFilter3Line size={14} /> Reset Filter
                                    </button>
                                </div>

                                {subVendors.length === 0 ? (
                                    <div className="py-12 border border-dashed border-gray-200 rounded-2xl text-center space-y-2">
                                        <RiStore2Line size={36} className="mx-auto text-gray-400" />
                                        <p className="text-sm text-gray-600 font-medium">
                                            No restaurants currently registered in this subcategory.
                                        </p>
                                        <button
                                            onClick={() => setSelectedSubCategoryId("all")}
                                            className="text-xs text-purple-600 font-semibold underline"
                                        >
                                            View all food categories
                                        </button>
                                    </div>
                                ) : (
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        {subVendors.map((vendor) => (
                                            <RestaurantCard
                                                key={vendor.id}
                                                vendor={vendor}
                                                categoryId={categoryId}
                                                defaultImg={defaultRestaurantImg}
                                            />
                                        ))}
                                    </div>
                                )}
                            </div>
                        );
                    })()
                ) : (
                    /* ALL SUBCATEGORIES GROUPED VIEW */
                    (() => {
                        // Gather subcategories that have vendors
                        const activeSubcategories = filteredSubcategories.filter(
                            (sub) => getVendorCountForSubcategory(sub.id) > 0
                        );

                        // Find vendors that might not match any listed subcategory
                        const uncategorizedVendors = filteredVendors.filter(
                            (v) =>
                                !subcategories.some(
                                    (sub) =>
                                        v.business_sub_category_id === sub.id ||
                                        v.sub_category?.id === sub.id
                                )
                        );

                        if (activeSubcategories.length === 0 && uncategorizedVendors.length === 0) {
                            return (
                                <div className="py-12 border border-dashed border-gray-200 rounded-2xl text-center space-y-2">
                                    <RiStore2Line size={36} className="mx-auto text-gray-400" />
                                    <p className="text-sm text-gray-600 font-medium">
                                        No restaurants found matching "{searchQuery}"
                                    </p>
                                </div>
                            );
                        }

                        return (
                            <div className="space-y-8">
                                {activeSubcategories.map((sub) => {
                                    const subVendors = getVendorsForSubcategory(sub.id);
                                    const subImg = sub.image || defaultSubCategoryImg;

                                    return (
                                        <div key={sub.id} className="space-y-3">
                                            {/* SUBCATEGORY HEADER */}
                                            <div className="flex items-center justify-between">
                                                <div className="flex items-center gap-2.5">
                                                    <img
                                                        src={subImg}
                                                        alt={sub.name}
                                                        className="w-7 h-7 rounded-full object-cover border border-purple-200"
                                                    />
                                                    <h3 className="text-base font-bold text-gray-900 tracking-tight">
                                                        {sub.name}
                                                    </h3>
                                                    <span className="bg-purple-100 text-purple-700 text-[11px] font-bold px-2 py-0.5 rounded-full">
                                                        {subVendors.length}
                                                    </span>
                                                </div>
                                                <button
                                                    onClick={() => setSelectedSubCategoryId(sub.id)}
                                                    className="text-xs font-semibold text-purple-600 hover:text-purple-800 transition flex items-center gap-0.5 cursor-pointer"
                                                >
                                                    View All <RiArrowRightSLine size={16} />
                                                </button>
                                            </div>

                                            {/* RESTAURANTS UNDER THIS SUBCATEGORY */}
                                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                                {subVendors.map((vendor) => (
                                                    <RestaurantCard
                                                        key={vendor.id}
                                                        vendor={vendor}
                                                        categoryId={categoryId}
                                                        defaultImg={defaultRestaurantImg}
                                                    />
                                                ))}
                                            </div>
                                        </div>
                                    );
                                })}

                                {/* UNCATEGORIZED / OTHER RESTAURANTS */}
                                {uncategorizedVendors.length > 0 && (
                                    <div className="space-y-3 pt-4 border-t border-gray-100">
                                        <div className="flex items-center gap-2">
                                            <RiStore2Line className="text-purple-600" size={20} />
                                            <h3 className="text-base font-bold text-gray-900">
                                                More Places to Order
                                            </h3>
                                        </div>
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            {uncategorizedVendors.map((vendor) => (
                                                <RestaurantCard
                                                    key={vendor.id}
                                                    vendor={vendor}
                                                    categoryId={categoryId}
                                                    defaultImg={defaultRestaurantImg}
                                                />
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </div>
                        );
                    })()
                )}
            </section>
        </div>
    );
}

// SUB-COMPONENT: Individual Restaurant Card
function RestaurantCard({
    vendor,
    categoryId,
    defaultImg,
}: {
    vendor: Vendor;
    categoryId: string;
    defaultImg: string;
}) {
    const shopPhoto = vendor.kycdetail?.shop_photo?.url || defaultImg;
    const itemsCount = (vendor as any).items_count;
    const deliveryTime = (vendor as any).delivery_time || "25-35";
    const costForTwo = (vendor as any).cost_for_two || "250";
    const subCategoryName = vendor.sub_category?.name;

    return (
        <Link
            href={`/category/${categoryId}/subcategory/${vendor.business_sub_category_id}?vendorId=${vendor.id}`}
            className="block group bg-white border border-gray-150 rounded-2xl overflow-hidden hover:shadow-md transition duration-200 text-left"
        >
            <div className="relative h-44 w-full overflow-hidden bg-gray-100">
                <img
                    src={shopPhoto}
                    alt={vendor.business_name}
                    className="w-full h-full object-cover group-hover:scale-105 transition duration-300"
                />
                {subCategoryName && (
                    <span className="absolute top-2.5 left-2.5 bg-purple-700/90 text-white text-[10px] font-bold px-2 py-0.5 rounded-full backdrop-blur-xs shadow-xs">
                        {subCategoryName}
                    </span>
                )}
                <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-60" />
                <div className="absolute bottom-2.5 left-3 right-3 flex justify-between items-end text-white">
                    <span className="text-xs font-semibold bg-white/20 backdrop-blur-md px-2 py-0.5 rounded-md">
                        {deliveryTime} mins
                    </span>
                    <span className="text-xs font-semibold bg-white/20 backdrop-blur-md px-2 py-0.5 rounded-md">
                        ₹{costForTwo} for two
                    </span>
                </div>
            </div>

            <div className="p-3.5 space-y-1.5">
                <div className="flex justify-between items-start gap-2">
                    <h4 className="text-base font-bold text-gray-900 truncate group-hover:text-purple-700 transition">
                        {vendor.business_name}
                    </h4>
                </div>

                <div className="flex items-center text-xs text-gray-500 gap-2 font-medium">
                    {itemsCount && <span>{itemsCount} Items available</span>}
                    {itemsCount && <span className="w-1 h-1 bg-gray-300 rounded-full shrink-0" />}
                    <span className="text-purple-600 font-semibold">View Menu →</span>
                </div>
            </div>
        </Link>
    );
}
