import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import MainLayout from "../layouts/MainLayout";
import DealCardMain from "../components/Shared/DealCardMain";
import { fetchCategoryDeals } from "../api/deal/getDeal"; // Import fetchCategoryDeals
import Breadcrumb from "../components/Shared/Breadcrumbs"; // Breadcrumb component
import FilterMenu from "../components/FilterMenu"; // FilterMenu component
import { fetchCategoryDetails } from "../api/category/getCategoryDetails"; // Fetch category details API
import type { DealCard } from "../models/deal/DealCard";
import type { CategoryDetailsModel } from "../models/category/CategoryDetailsModel";
import FilterPanel from "../components/Shared/FilterPanel";
type CategoryPageProps = {};

const LIMIT = 10;

export default function CategoryPage({}: CategoryPageProps) {
  const { categorySlug } = useParams<{ categorySlug: string }>(); // Get slug from URL
  const [deals, setDeals] = useState<DealCard[]>([]); // Initialize with the correct type
  const [categoryDetails, setCategoryDetails] = useState<CategoryDetailsModel | null>(null); // Category details state
  const [breadcrumb, setBreadcrumb] = useState<any[]>([]); // Breadcrumb state
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);

  // Fetch category details and deals based on categorySlug
  useEffect(() => {
    setLoading(true);

    // Fetch category details (including breadcrumb)
    fetchCategoryDetails(categorySlug)
      .then((response) => {
        setCategoryDetails(response); // Set category details
        setBreadcrumb(response.breadcrumb); // Set breadcrumb
      })
      .catch((error) => {
        console.error("Error fetching category details:", error);
      })
      .finally(() => setLoading(false)); // Stop loading once done
  }, [categorySlug]); // Only fetch category details when categorySlug changes

  useEffect(() => {
    // Avoid fetching deals if already loading
    if (loading) return;

    setLoading(true); // Set loading true to prevent another fetch while loading

    // Fetch category deals based on page and categorySlug
    fetchCategoryDeals(categorySlug, page, LIMIT)
      .then((response) => {
        // Append new deals to existing ones
        setDeals((prevDeals) => {
          if (page === 1) {
            // If it's the first page, replace existing deals with new ones
            return response;
          } else {
            // Otherwise, append new deals
            return [...prevDeals, ...response];
          }
        });
        setHasMore(response.length === LIMIT); // If response length is equal to LIMIT, more data is available
      })
      .catch((error) => {
        console.error("Error fetching category deals:", error);
      })
      .finally(() => setLoading(false)); // Stop loading once done
  }, [categorySlug, page]); // Fetch deals when page or categorySlug changes

  const loadMoreDeals = () => {
    if (hasMore && !loading) {
      setPage((prevPage) => prevPage + 1); // Increment page number for next fetch
    }
  };

  return (
    <MainLayout>
      <div className="max-w-[1400px] mx-auto px-4 py-8 ">
        {/* 1) Breadcrumb Section */}
        <div className="mb-6">
          <Breadcrumb breadcrumb={breadcrumb} />
        </div>

        
 
<div className="w-full h-[400px] mb-8 bg-white p-12 flex items-center overflow-hidden">
  <div className="relative max-w-screen-xl mx-auto text-left text-black w-full flex items-center">
    

    <div className="flex-1">
      <h1 className="text-5xl font-bold mb-2 text-grey">{categoryDetails?.name || "Kategori Adı"}</h1>
      <p className="text-lg max-w-4xl mb-8 text-grey">
        {categoryDetails?.description || "Kategori açıklaması burada yer alacak."}
      </p>
    </div>


<div className="grid grid-cols-3 gap-3">
  {Array.from({ length: 3 }).map((_, colIndex) => {
    // Pozisyon kaydırma için her sütuna farklı bir değer veriyoruz
    const translateYValue = colIndex === 0 ? "-5%" : colIndex === 1 ? "5%" : "-5%";

    return (
      <div key={colIndex} className="grid grid-rows-3 gap-10 pl-20" style={{ transform: `translateY(${translateYValue})` }}>
        {deals.slice(colIndex * 3, (colIndex + 1) * 3).map((deal, index) => (
          <div key={index} className="w-full h-42 bg-white overflow-hidden rounded-lg shadow-2xl opacity-80 pointer-events-none user-select-none">
            <img
              src={deal.imageUrl || "/placeholder.png"}
              alt={deal.title}
              className="w-full h-full object-center rounded-lg "
            />
          </div>
        ))}
      </div>
    );
  })}
</div>



  </div>
</div>




        {/* 3) Category Content: Filters on the left and Deals on the right */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Left: Filter Menu */}
          <div className="lg:col-span-1">
            <FilterPanel/>
          </div>

          {/* Right: Deals */}
          <div className="lg:col-span-3">
            <div className="relative">
              <div
                className={`space-y-4 min-h-[60vh] transition-opacity duration-150 ${loading && deals.length > 0 ? "opacity-80" : ""}`}
              >
                {!loading && deals.length === 0 ? (
                  <div className="rounded-2xl bg-surface border border-border p-6 text-center">
                    <div className="text-sm font-semibold text-text">Henüz fırsat yok</div>
                    <div className="text-xs text-text-muted mt-1">
                      Seçili kategoride henüz paylaşım bulunmuyor.
                    </div>
                  </div>
                ) : (
                  deals.map((deal) => (
                    <DealCardMain key={deal.id} deal={deal} onRequireLogin={() => {}} />
                  ))
                )}
              </div>

              {loading && deals.length > 0 && (
                <div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-background/70 text-text">
                  <p className="text-sm font-semibold">Yükleniyor...</p>
                </div>
              )}

              {!hasMore && !loading && deals.length > 0 && (
                <p className="text-center py-4 text-muted-foreground">Tüm fırsatlar yüklendi.</p>
              )}

              {/* Load more button */}
              {hasMore && !loading && (
                <div className="text-center py-4">
                  <button onClick={loadMoreDeals} className="btn btn-primary">
                    Daha Fazla Yükle
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </MainLayout>
  );
}
