"use client";

import CustomTabs from "@/components/common/CustomTabs";
import SearchFilters from "@/components/search/searchFilters";
import {
  AdvancedPropertyFilters,
  BasicPropertyFilters,
} from "@/components/search/PropertyFilters";

import { PropertyCard } from "@/components/main-page/propertyCard";
import { useState, useEffect, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import SegmentedControl from "@/components/common/SegmentedControl";
import Pagination from "@/components/common/pagination";
import { DiscoverSlides } from "@/components/main-page/discoverSlids";
import PropertyProjectSection from "@/components/main-page/propertyProjectSection";
import { PropertyProjectCard } from "@/components/main-page/propertyProjectCard";
import Link from "next/link";
import { Search } from "lucide-react";
import {
  AdvancedProjectFilters,
  BasicProjectFilters,
} from "@/components/search/ProjectFilters";
import { BasicRequestsFilters } from "@/components/search/RequestsFilter";
import { BasicMarketingFilters } from "@/components/search/MarketingFilters";
import { PropertyRequestsCard } from "@/components/main-page/propertyRequestsCard";

import PropertyRequestsSection from "@/components/main-page/propertyRequestsSection";
import MarketCard from "@/components/main-page/marketCard";

import {
  searchProperties,
  SearchFilters as SearchFiltersType,
  getPropertyRequests,
  PropertyRequestSearchItem,
  getMarketingProperties,
  getPremiumProjects,
} from "@/lib/api";

import { PropertyCard as PropertyCardType } from "@/types/property-card";

const tabs = [
  { id: "properties", label: "عقارات" },
  { id: "projects", label: "المشاريع" },
  { id: "requests", label: "الطلبات العقارية" },
  { id: "marketing", label: "تسويق عقارات الملاك" },
];

export default function SearchPage() {
  return (
    <Suspense
      fallback={
        <div className="flex justify-center items-center min-h-screen">
          جاري التحميل...
        </div>
      }
    >
      <SearchPageContent />
    </Suspense>
  );
}

function SearchPageContent() {
  const searchParams = useSearchParams();
  const router = useRouter();

  const [page, setPage] = useState(1);

  const tabParam = searchParams.get("tab");

  const initialTab =
    tabParam && tabs.some((t) => t.id === tabParam)
      ? tabParam
      : "properties";

  const [activeTab, setActiveTab] = useState<string>(initialTab);

  const queryParam = searchParams.get("q") || "";
  const cityFilter = searchParams.get("city") || "";
  const typeFilter = searchParams.get("type") || "";
  const sectionFilter = searchParams.get("section") || "";
  const roomsFilter = searchParams.get("rooms") || "";

  const [propertyFilters, setPropertyFilters] = useState<any>({
    search: queryParam,
    city_id: cityFilter,
    type: typeFilter,
    section: sectionFilter,
    rooms: roomsFilter,
  });

  useEffect(() => {
    setPropertyFilters((prev: any) => ({
      ...prev,
      search: queryParam,
      city_id: cityFilter,
      type: typeFilter,
      section: sectionFilter,
      rooms: roomsFilter,
    }));
  }, [
    queryParam,
    cityFilter,
    typeFilter,
    sectionFilter,
    roomsFilter,
  ]);

  const [properties, setProperties] = useState<PropertyCardType[]>([]);
  const [propertyRequests, setPropertyRequests] = useState<
    PropertyRequestSearchItem[]
  >([]);
  const [marketingProperties, setMarketingProperties] = useState<
    PropertyCardType[]
  >([]);
  const [projects, setProjects] = useState<any[]>([]);

  const [loading, setLoading] = useState(true);

  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);

  const pageSize = 24;

  useEffect(() => {
    if (tabParam && tabs.some((t) => t.id === tabParam)) {
      setActiveTab(tabParam);
    }
  }, [tabParam]);

  useEffect(() => {
    if (activeTab === "properties") {
      const fetchProperties = async () => {
        setLoading(true);

        try {
          const filters: SearchFiltersType = {
            page,
            per_page: pageSize,
            ...propertyFilters,
          };

          if (filters.search === "جميع المدن") {
            delete filters.search;
          }

          const result = await searchProperties(filters);

          setProperties(result.properties);
          setTotalPages(result.meta.last_page);
          setTotalCount(result.meta.total);
        } catch (error) {
          console.error("Error fetching properties:", error);
        } finally {
          setLoading(false);
        }
      };

      fetchProperties();
    }
  }, [activeTab, page, propertyFilters]);

  useEffect(() => {
    if (activeTab === "requests") {
      const fetchRequests = async () => {
        setLoading(true);

        try {
          const filters = {
            ...propertyFilters,
            per_page: pageSize,
            page,
          };

          if (filters.search === "جميع المدن") {
            delete filters.search;
          }

          const result = await getPropertyRequests(filters);

          setPropertyRequests(result.requests);
          setTotalPages(result.meta.last_page);
          setTotalCount(result.meta.total);
        } catch (error) {
          console.error("Error fetching requests:", error);
        } finally {
          setLoading(false);
        }
      };

      fetchRequests();
    }
  }, [activeTab, page, propertyFilters]);

  useEffect(() => {
    if (activeTab === "marketing") {
      const fetchMarketing = async () => {
        setLoading(true);

        try {
          const filters = {
            ...propertyFilters,
            per_page: pageSize,
            page,
          };

          if (filters.search === "جميع المدن") {
            delete filters.search;
          }

          const result = await getMarketingProperties(filters);

          setMarketingProperties(result.properties);
          setTotalPages(result.meta.last_page);
          setTotalCount(result.meta.total);
        } catch (error) {
          console.error("Error fetching marketing properties:", error);
        } finally {
          setLoading(false);
        }
      };

      fetchMarketing();
    }
  }, [activeTab, page, propertyFilters]);

  useEffect(() => {
    if (activeTab === "projects") {
      const fetchProjects = async () => {
        setLoading(true);

        try {
          const result = await getPremiumProjects();

          setProjects(result);
          setTotalCount(result.length);
          setTotalPages(1);
        } catch (error) {
          console.error("Error fetching projects:", error);

          setProjects([]);
          setTotalCount(0);
          setTotalPages(1);
        } finally {
          setLoading(false);
        }
      };

      fetchProjects();
    }
  }, [activeTab]);

  const mapSearchButton = (
    <Link
      href="/search-map"
      className="flex justify-center items-center gap-2 bg-[#0719381A] text-[#4F5874] text-sm md:text-base font-medium px-3 py-2 md:px-4 rounded-full whitespace-nowrap"
    >
      <Search size="16" />
      بحث الخريطة
    </Link>
  );

  const tabTitles: Record<string, string> = {
    properties: "ابحث عن عقارك",
    projects: "ابحث عن مشروعك",
    requests: "ابحث في الطلبات",
    marketing: "ابحث في التسويق",
  };

  const currentTitle = tabTitles[activeTab] ?? "ابحث";

  return (
  <div className="mt-2 lg:pt-[70px] md:w-[92%] px-2 mx-auto">
    
          <CustomTabs
        title={currentTitle}
        subtitle="اكتشف أحدث العقارات والمشاريع."
        tabs={tabs}
        defaultValue="properties"
        value={activeTab}
        onValueChange={(v) => {
          setActiveTab(v);
          setPage(1);

          const params = new URLSearchParams(
            searchParams.toString()
          );

          params.set("tab", v);
          params.set("page", "1");

          router.push(`/search?${params.toString()}`);
        }}
        tabFilters={[
          {
            value: "properties",
            content: (
              <SearchFilters
                children={
                  <BasicPropertyFilters
                    filters={propertyFilters}
                    onFilterChange={setPropertyFilters}
                  />
                }
                advancedChildren={
                  <AdvancedPropertyFilters
                    filters={propertyFilters}
                    onFilterChange={setPropertyFilters}
                  />
                }
                extraSearchButton={mapSearchButton}
              />
            ),
          },

          {
            value: "projects",
            content: (
              <SearchFilters
                children={<BasicProjectFilters />}
                advancedChildren={<AdvancedProjectFilters />}
                extraSearchButton={mapSearchButton}
              />
            ),
          },

          {
            value: "requests",
            content: (
              <SearchFilters
                children={
                  <BasicRequestsFilters
                    filters={propertyFilters}
                    onFilterChange={setPropertyFilters}
                  />
                }
                showSerachButton={false}
              />
            ),
          },

          {
            value: "marketing",
            content: (
              <SearchFilters
                children={
                  <BasicMarketingFilters
                    filters={propertyFilters}
                    onFilterChange={setPropertyFilters}
                  />
                }
                showSerachButton={false}
              />
            ),
          },
        ]}
      >
        {activeTab === "properties" && (
          <div className="w-full px-4">
            {loading && (
              <div className="flex justify-center items-center py-20">
                <div className="text-lg text-gray-500">
                  جاري تحميل العقارات...
                </div>
              </div>
            )}

            {!loading && properties.length === 0 && (
<div className="flex flex-wrap gap-4 justify-center">
                  <div className="text-lg text-gray-500 mb-2">
                  لا توجد عقارات
                </div>

                <div className="text-sm text-gray-400">
                  جرب تغيير معايير البحث
                </div>
              </div>
            )}

            {!loading && properties.length > 0 && (
<div className="mt-4 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 w-full">
  
                  {properties.map((item) => (
                  <PropertyCard
                    key={item.id}
                    {...item}
                    classNames="max-w-[unset]"
                  />
                ))}
              </div>
            )}
          </div>
        )}

        {activeTab === "projects" && (
          <div className="container mx-auto">

           <div className="flex items-center justify-center mb-5">
  <div className="flex bg-[#F1F5F9] rounded-full p-1 gap-1 border border-slate-200">
    
    <button className="px-5 py-2 rounded-full bg-[#032B44] text-white text-sm font-medium">
      الكل
    </button>

    <button className="px-5 py-2 rounded-full text-[#64748B] text-sm font-medium hover:bg-white transition">
      بيع
    </button>

    <button className="px-5 py-2 rounded-full text-[#64748B] text-sm font-medium hover:bg-white transition">
      إيجار
    </button>

  </div>
</div>

            {loading && (
              <div className="flex justify-center items-center py-20">
                <div className="text-lg text-gray-500">
                  جاري تحميل المشاريع...
                </div>
              </div>
            )}

            {!loading && projects.length === 0 && (
<div className="flex flex-wrap gap-4 justify-center">
                  <div className="text-lg text-gray-500 mb-2">
                  لا توجد مشاريع
                </div>

                <div className="text-sm text-gray-400">
                  جرب تغيير معايير البحث
                </div>
              </div>
            )}

            {!loading && projects.length > 0 && (
              <>
                <div className="mt-4 grid gap-5 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 justify-items-center">
                  {projects.map((item) => (
                    <PropertyProjectCard
                      key={item.id}
                      {...item}
                    />
                  ))}
                </div>

                <div className="mt-8 text-center text-gray-500 text-sm">
                  عرض {projects.length} من {totalCount} مشروع
                </div>
              </>
            )}
          </div>
        )}

        {activeTab === "requests" && (
          <div className="container mx-auto">
           <div className="flex items-center justify-center mb-5">
  <div className="flex bg-[#F1F5F9] rounded-full p-1 gap-1 border border-slate-200">
    
    <button className="px-5 py-2 rounded-full bg-[#032B44] text-white text-sm font-medium">
      الكل
    </button>

    <button className="px-5 py-2 rounded-full text-[#64748B] text-sm font-medium hover:bg-white transition">
      بيع
    </button>

    <button className="px-5 py-2 rounded-full text-[#64748B] text-sm font-medium hover:bg-white transition">
      إيجار
    </button>

  </div>
</div>

            {!loading && propertyRequests.length > 0 && (
              <PropertyRequestsSection more={false}>
                {propertyRequests.map((item) => (
                  <PropertyRequestsCard
                    key={item.id}
                    title={item.title}
                    subtitle={item.subtitle}
                    badge={item.badge}
                    price={item.price}
                    company={item.company}
                    companyLogo={item.companyLogo}
                    daysLeft={item.daysLeft}
                    area={item.area}
                    bedrooms={item.bedrooms}
                    bathrooms={item.bathrooms}
                    propertyType={item.propertyType}
                  />
                ))}
              </PropertyRequestsSection>
            )}
          </div>
        )}

        {activeTab === "marketing" && (
          <div className="container mx-auto">
          <div className="flex items-center justify-center mb-5">
  <div className="flex bg-[#F1F5F9] rounded-full p-1 gap-1 border border-slate-200">
    
    <button className="px-5 py-2 rounded-full bg-[#032B44] text-white text-sm font-medium">
      الكل
    </button>

    <button className="px-5 py-2 rounded-full text-[#64748B] text-sm font-medium hover:bg-white transition">
      بيع
    </button>

    <button className="px-5 py-2 rounded-full text-[#64748B] text-sm font-medium hover:bg-white transition">
      إيجار
    </button>

  </div>
</div>

            {!loading && marketingProperties.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-2 w-full max-w-[1900px] mx-auto">

                        {marketingProperties.map((card) => (
                  <MarketCard
                    key={card.id}
                    title={card.title}
                    subtitle={card.subtitle}
                    image={card.image}
                    price={card.price}
                    area={card.area}
                    bedrooms={card.bedrooms}
                    bathrooms={card.bathrooms}
                    floors={card.floors}
                  />
                ))}
              </div>
            )}
          </div>
        )}
      </CustomTabs>

      <Pagination
        currentPage={page}
        totalPages={totalPages}
        pageSize={pageSize}
        totalCount={totalCount}
        itemLabel={
          activeTab === "projects"
            ? "مشروع"
            : activeTab === "requests"
            ? "طلب"
            : activeTab === "marketing"
            ? "عقار"
            : "عقار"
        }
        onPageChange={setPage}
      />
    </div>
  );
}