import { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
import MainLayout from "../layouts/MainLayout";
import DealCardMain from "../components/Shared/DealCardMain";
import DealsPresetTabs from "../components/Shared/DealsPresetTabs";
import { fetchPresetDeals } from "../api/deal/getDeal";
import type { DealPreset } from "../api/deal/getDeal";
import type { DealCard } from "../models/deal/DealCard";
import HotDealsSidebar from "../components/Sidebar/HotDealsSidebar";
import FilterMenu from "../components/FilterMenu";

type HomeProps = {
  onRequireLogin: () => void;
};

const LIMIT = 10;

function getPresetFromQuery(value: string | null): DealPreset {
  if (value === "hot" || value === "trending") return value;
  return "new";
}

export default function HomePage({ onRequireLogin }: HomeProps) {
  const [searchParams, setSearchParams] = useSearchParams();
  const currentPreset = useMemo(
    () => getPresetFromQuery(searchParams.get("tab")),
    [searchParams]
  );

  const [deals, setDeals] = useState<DealCard[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loadedOnce, setLoadedOnce] = useState(false);

  const observerRef = useRef<HTMLDivElement | null>(null);

  const handlePresetChange = (next: DealPreset) => {
    if (next === currentPreset) return;
    const params = new URLSearchParams(searchParams);
    params.set("tab", next);
    setSearchParams(params, { replace: true });
  };

  useEffect(() => {
    setPage(1);
    setHasMore(true);
    setError(null);
    setLoadedOnce(false);
  }, [currentPreset]);

  useEffect(() => {
    let canceled = false;

    const loadDeals = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await fetchPresetDeals(currentPreset, page, LIMIT);
        if (canceled) return;

        setDeals((prev) => (page === 1 ? response : [...prev, ...response]));
        setHasMore(response.length === LIMIT);
        setLoadedOnce(true);
      } catch (err: any) {
        if (!canceled) setError(err?.message ?? "Bir hata oluştu");
      } finally {
        if (!canceled) setLoading(false);
      }
    };

    loadDeals();

    return () => {
      canceled = true;
    };
  }, [currentPreset, page]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        const hit = entries[0]?.isIntersecting;
        if (!hit) return;

        if (!loadedOnce) return;
        if (loading) return;
        if (!hasMore) return;
        if (deals.length === 0) return;

        setPage((p) => p + 1);
      },
      { threshold: 1 }
    );

    const el = observerRef.current;
    if (el) observer.observe(el);
    return () => observer.disconnect();
  }, [loadedOnce, loading, hasMore, deals.length]);

  if (error) {
    return <p className="p-4 text-red-600">{error}</p>;
  }

  return (
    <MainLayout>
      <div className="max-w-[1400px] mx-auto px-4 py-8">


       <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
<div className="lg:col-span-3 flex justify-between mb-3">
  {/* Sol tarafta DealsPresetTabs */}
  <div className="flex items-center">
    <DealsPresetTabs currentPreset={currentPreset} onSelect={handlePresetChange} />
  </div>

  {/* Sağ tarafta FilterMenu */}
  <div className="flex justify-end items-center">
    <FilterMenu onFilterChange={(filters) => console.log(filters)} />
  </div>
</div>

       
          <aside className="hidden lg:block rounded-lg ">
          
          </aside>
       </div>


        {/* 2) Deals ve Sidebar */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          <div className="lg:col-span-3">
            <div className="relative">
              <div
                className={`space-y-2 min-h-[60vh] transition-opacity duration-150 ${
                  loading && deals.length > 0 ? "opacity-80" : ""
                }`}
              >
                {!loadedOnce && loading && deals.length === 0 ? (
                  <div className="grid gap-4">
                    {Array.from({ length: 3 }).map((_, idx) => (
                      <div
                        key={idx}
                        className="h-32 rounded-2xl border border-border bg-surface-2 animate-pulse"
                      />
                    ))}
                  </div>
                ) : deals.length === 0 && loadedOnce && !loading ? (
                  <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 sekmede henüz paylaşım bulunmuyor.
                    </div>
                  </div>
                ) : (
                  deals.map((deal) => (
                    <DealCardMain key={deal.id} deal={deal} onRequireLogin={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>
              )}

              <div ref={observerRef} className="h-8" />
            </div>
          </div>

          <aside className="hidden lg:block rounded-lg ">
            <HotDealsSidebar />
          </aside>
        </div>
      </div>
    </MainLayout>
  );
}
