"use client";

import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Image from "next/image";
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@radix-ui/react-dropdown-menu";
import { useRouter } from "next/navigation";
import { baseUrl } from "@/lib/config";
import { useTranslation } from "react-i18next";
const listings = [
  {
    title: "Houses on the Hollywood",
    location: "Al Cloops",
    features: {
      beds: "3",
      baths: "6",
      area: "200 sqft",
    },
    status: "For Sale",
    price: "5,800,000 SAR",
    isFeatured: "Featured",
    slug: "houses-on-the-hollywood",
  },
  {
    title: "Houses on the Hollywood",
    location: "Al Cloops",
    features: {
      beds: "3",
      baths: "6",
      area: "200 sqft",
    },
    status: "For Sale",
    price: "5,800,000 SAR",
    isFeatured: "Featured",
    slug: "houses-on-the-hollywood",
  },
  {
    title: "Comfortable Villa Green",
    location: "Flyerin",
    features: {
      beds: "3",
      baths: "6",
      area: "200 sqft",
    },
    status: "For Sale",
    price: "4,600,000 SAR",
    isFeatured: "Featured",
    slug: "comfortable-villa-green",
  },
  {
    title: "Luxury Apartment",
    location: "Riyadh",
    features: {
      beds: "100",
      baths: "6",
      area: "200 sqft",
    },
    status: "For Sale",
    price: "3,200,000 SAR",
    slug: "luxury-apartment",
  },
  {
    title: "Houses on the Hollywood",
    location: "Al Cloops",
    features: {
      beds: "3",
      baths: "6",
      area: "200 sqft",
    },
    status: "For Sale",
    price: "5,800,000 SAR",
    isFeatured: "Featured",
    slug: "houses-on-the-hollywood",
  },
  {
    title: "Comfortable Villa Green",
    location: "Flyerin",
    features: {
      beds: "3",
      baths: "6",
      area: "200 sqft",
    },
    status: "For Sale",
    price: "4,600,000 SAR",
    isFeatured: "Featured",
    slug: "comfortable-villa-green",
  },
  {
    title: "Luxury Apartment",
    location: "Riyadh",
    features: {
      beds: "100",
      baths: "6",
      area: "200 sqft",
    },
    status: "For Sale",
    price: "3,200,000 SAR",
    slug: "luxury-apartment",
  },
];

export default function PropertiesCards({ data }) {
      const { t } = useTranslation("properties"); 
  
    const [favorites, setFavorites] = useState(data);

  const [activeTab, setActiveTab] = useState("All");
  const [location, setLocation] = useState("");
  const [price, setPrice] = useState("");
  const [bedrooms, setBedrooms] = useState("");
  const [listingType, setListingType] = useState("");
  const [selected, setSelected] = useState("");
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");

  const [visibleCount, setVisibleCount] = useState(6);
  const totalAListings = favorites?.length;
  const isAllVisible = visibleCount >= totalAListings;

  const [loading, setLoading] = useState(false);
  const [added, setAdded] = useState(false);
  const options = [
    "Price (Low to High)",
    "Price (High to Low)",
    "Date (Newest First)",
    "Date (Oldest First)",
    "Popularity",
    "Featured",
  ];
  const resetFilters = () => {
    setActiveTab("All");
    setLocation("");
    setPrice("");
    setBedrooms("");
    setListingType("");
  };
  //   const filteredListings = data.filter((item) => {
  //     const matchesTab =
  //       activeTab === "All" ||
  //       item.status.toLowerCase() === activeTab.toLowerCase();
  //     const matchesLocation =
  //       !location || item.location.toLowerCase().includes(location.toLowerCase());
  //     const matchesPrice = !price || item.price.includes(price);
  //     const matchesBedrooms =
  //       !bedrooms || item.features.beds.toString() === bedrooms.toString();
  //     const matchesListingType =
  //       !listingType || item.status.toLowerCase() === listingType.toLowerCase();

  //     return (
  //       matchesTab &&
  //       matchesLocation &&
  //       matchesPrice &&
  //       matchesBedrooms &&
  //       matchesListingType
  //     );
  //   });

  // const filteredListings = data.filter((item) => {
  //   const tabStatusMap = {
  //     "For Sale": "sale",
  //     "For Rent": "rent",
  //   };

  //   const matchesTab =
  //     activeTab === "All" ||
  //     item.status.toLowerCase() === tabStatusMap[activeTab]?.toLowerCase();

  //   const matchesLocation =
  //     !location || item.location.toLowerCase().includes(location.toLowerCase());

  //   const matchesPrice = !price || item.price.includes(price);

  //   const matchesBedrooms =
  //     !bedrooms || item.features.beds.toString() === bedrooms.toString();

  //   const matchesListingType =
  //     !listingType || item.status.toLowerCase() === listingType.toLowerCase();

  //   return (
  //     matchesTab &&
  //     matchesLocation &&
  //     matchesPrice &&
  //     matchesBedrooms &&
  //     matchesListingType
  //   );
  // });
console.log('qwert',favorites) // true

    const filteredListings = favorites?.filter((item) => {
      const tabStatusMap = {
        "For Sale": "sale",
        "For Rent": "rent",
      };

      const matchesTab =
        activeTab === "All" ||
        item.status.toLowerCase() === tabStatusMap[activeTab]?.toLowerCase();

      const matchesSearch =
        !searchTerm ||
        item.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.date?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.location?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.type?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.status?.toLowerCase().includes(searchTerm.toLowerCase());

      const matchesLocation =
        !location || item.location.toLowerCase().includes(location.toLowerCase());

      const matchesPrice = !price || item.price.includes(price);

      const matchesBedrooms =
        !bedrooms || item.features.beds.toString() === bedrooms.toString();

      const matchesListingType =
        !listingType || item.status.toLowerCase() === listingType.toLowerCase();

        
      return (
        matchesTab &&
        matchesSearch &&
        matchesLocation &&
        matchesPrice &&
        matchesBedrooms &&
        matchesListingType
      );
    });

    const handleToggle = () => {
      if (isAllVisible) {
        setVisibleCount(6); // Reset to initial
      } else {
        setVisibleCount((prev) => prev + 6); // Load more
      }
    };


     const getFavourites = async () => {
    const token = localStorage.getItem("sadu_auth_token");
    if (!token) return;

    const res = await fetch(`${baseUrl}/api/properties`, {
      headers: { Authorization: `Bearer ${token}` },
      cache: "no-store",
    });

    if (res.ok) {
   setFavorites(await res.json())
      // setFavorites(dataUpdated?.data);
    }
  };

  async function handleAddToFavorites(propertyId) {
    try {
      setLoading(true);
      const token = localStorage.getItem("sadu_auth_token");
      if (!token) {
        alert("Please log in to add to favorites.");
        return;
      }

      const res = await fetch(`${baseUrl}/api/favorites/${propertyId}`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      });

      if (!res.ok) throw new Error("Failed to add to favorites");

      getFavourites();
    } catch (err) {
      console.error("Error adding favorite:", err);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <div className="text-center pb-4  px-5 ">
        <div className=" text-primary lg:mb-2 font-semibold">{t("LISTING")}</div>
        <h2 className="text-[30px] md:text-[35px] lg:text-[40px] font-semibold mb-0">
          {t("Explore Our")} <span className="text-primary">{t("Listings")}</span>
        </h2>
        <p className="sm:px-15 md:px-19 mx-auto mb-5 md:mb-9 text-[#808080] w-full sm:max-w-[67%]">
         {t("listDesc")}
        </p>
      </div>

      <div className="bg-ligbg py-[22px] px-5 md:px-[50px] lg:px-[96px]">
        <div className=" flex items-center justify-end gap-2">
          <div className="flex items-center gap-3 bg-white px-4 rounded-xl">
            <Image
              src="/icons/searchIcon.png"
              width={18}
              height={18}
              alt="twitter"
            />
            <Input
              placeholder={t("Search")}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="bg-white border-0 ps-0 py-0 h-[48px] shadow-none focus-visible:outline-0 focus-visible:border-0 focus-visible:shadow-none text-[14px] sm:text-[16px] max-w-[450px] "
            />
          </div>
          {/* <Button className="bg-primary hover:bg-primary text-white text-[16px] h-12 flex items-center gap-2 px-6">
              <Image
                src="/icons/sortIcon.png"
                width={14}
                height={16}
                alt="twitter"
              />{" "}
              Sort
            </Button> */}
          <DropdownMenu className="h-[48px]">
            <DropdownMenuTrigger asChild className="focus-visible:ring-0">
              <Button className="bg-primary hover:bg-primary text-white text-[16px] md:h-[48px] flex items-center gap-2 px-6">
                <Image
                  src="/icons/sortIcon.png"
                  width={14}
                  height={16}
                  alt="sort icon"
                />
                {t("Sort")}
              </Button>
            </DropdownMenuTrigger>

            <DropdownMenuContent className="w-[220px] mt-2 bg-white rounded-lg p-3">
              {options.map((option, index) => (
                <DropdownMenuItem
                  key={index}
                  onClick={() => setSelected(option)}
                  className={`cursor-pointer focus:outline-0 my-1 px-2 rounded ${
                    selected === option ? "bg-primary text-white" : ""
                  }`}
                >
                  {option}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>
      <div className="bg-primary h-9 mb-5"></div>

      <div className="px-5 md:px-[50px] lg:px-[96px] pb-6 sm:pb-8 md:pb-12">
        <div className="flex gap-6 pt-1 border-b bg-ligbg rounded-t-lg w-fit px-4">
          {[t("All"), t("For Sale"), t("For Rent")].map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-3 py-2 rounded-t-lg text-sm font-medium border-b-2 transition-all duration-200 ${
                activeTab === tab
                  ? "border-black text-black"
                  : "border-transparent text-gray-500"
              }`}
            >
              {tab}
            </button>
          ))}
        </div>

        <div className="flex flex-wrap gap-4 rounded-tr-lg rounded-b-lg rounded-tl-0 items-center bg-ligbg p-4 mb-7 justify-between">
          <div className="flex flex-wrap gap-4  ms:gap-6 lg:gap-8">
            <Input
              placeholder={t("Location")}
              value={location}
              onChange={(e) => setLocation(e.target.value)}
              className="w-[200px] bg-white h-12 lg:h-[55px]"
            />
            <Input
              placeholder={t("price")}
              value={price}
              onChange={(e) => setPrice(e.target.value)}
              className="w-[200px] bg-white h-12 lg:h-[55px]"
            />
            <Input
              placeholder={t("bedrooms")}
              value={bedrooms}
              onChange={(e) => setBedrooms(e.target.value)}
              className="w-[200px] bg-white text-[16px] h-12 lg:h-[55px]"
            />
            <Select className="bg-white h-12 lg:h-[55px]">
              <SelectTrigger className="w-[200px] bg-white h-12 lg:h-[55px]">
                <SelectValue placeholder={t("Listing type")} className="" />
              </SelectTrigger>
              <SelectContent className="bg-white rounded-lg z-50">
                <SelectGroup>
                  <SelectLabel>{t("Listing type")}</SelectLabel>
                  <SelectItem value="apple">1</SelectItem>
                  <SelectItem value="banana">2</SelectItem>
                  <SelectItem value="blueberry">3</SelectItem>
                  <SelectItem value="grapes">4</SelectItem>
                  <SelectItem value="pineapple">5</SelectItem>
                </SelectGroup>
              </SelectContent>
            </Select>
          </div>

          <Button
            onClick={resetFilters}
            className="bg-primary px-8 text-white md:h-12 lg:h-[55px]"
          >
            {t("Reset")}
          </Button>
        </div>

        {/* //cards */}

        <div className="grid sm:grid-cols-2 md:grid-cols-3 gap-[20px]  lg:gap-[30px] text-start ">
          {filteredListings.slice(0, visibleCount).map((listing, index) => (
            <Card
              key={index}
              className="h-full py-0 rounded-t-xl gap-2  lg:gap-5"
            >
              <div
                onClick={() => {
                  if (typeof window !== "undefined" && listing?.slug) {
                    window.open(`/property/${listing.slug}`, "_blank");
                  }
                }}
                className="h-[200px] lg:h-[240px] cursor-pointer w-full relative"
              >
                {listing?.isFeatured && listing?.isFeatured !== "Normal" ? (
                  <div className="bg-primary absolute top-4 left-4 z-10 min-w-[80px] px-1 h-[30px] rounded">
                    <div className="flex items-center gap-2 text-white h-full justify-center">
                      <Image
                        width={13}
                        height={14}
                        src="/icons/listingCardIcons/Vector (2).png"
                        alt="featured"
                      />
                      <p className="text-[11px] font-semibold">
                        {listing?.isFeatured}
                      </p>
                    </div>
                  </div>
                ) : null}
                {listing?.type ? (
                  <div className="bg-secordary opacity-85 absolute top-4 right-4 z-10 w-[80px] h-[30px] px-2 rounded">
                    <div className="flex items-center gap-2 text-white h-full justify-center">
                      {/* <Image
                        width={13}
                        height={14}
                        src="/icons/listingCardIcons/Vector (2).png"
                        alt="featured"
                      /> */}
                      <p className="text-[10px] font-semibold">
                        {listing?.type}
                      </p>
                    </div>
                  </div>
                ) : null}

                <div className="bg-white absolute bottom-4 left-4 z-10 px-3 h-[30px] rounded">
                  <div className="flex items-center h-full justify-center">
                    <p className="text-[12px] font-semibold">
                      {listing?.price}
                    </p>
                  </div>
                </div>
              {listing?.media?.media_url && (
  <Image
    src={listing.media.media_url}
    fill
    alt="sadu-logo"
    className="cursor-pointer rounded-t-xl"
  />
)}
              </div>
              <CardHeader
                onClick={() => {
                  if (typeof window !== "undefined" && listing?.slug) {
                    window.open(`/property/${listing.slug}`, "_blank");
                  }
                }}
                className="ps-3 lg:ps-5 cursor-pointer"
              >
                <h3 className="font-semibold text-[13px]  lg:text-[15px]">
                  {listing.title}
                </h3>
                <p className="text-[12px] lg:text-[14px] text-gray-500">
                  {listing.location}
                </p>
              </CardHeader>
              <CardContent
                onClick={() => {
                  if (typeof window !== "undefined" && listing?.slug) {
                    window.open(`/property/${listing.slug}`, "_blank");
                  }
                }}
                className="px-3 lg:px-6 cursor-pointer"
              >
               <div className="flex items-center gap-5 border-b pb-4">
  {listing?.features?.beds && (
    <div className="flex items-center gap-1">
      <Image
        width={20}
        height={18}
        src="/icons/listingCardIcons/Vector (3).png"
        alt="beds"
      />
      <p className="pt-1">{listing.features.beds}</p>
    </div>
  )}

  {listing?.features?.baths && (
    <div className="flex items-center gap-1">
      <Image
        width={20}
        height={18}
        src="/icons/listingCardIcons/Vector (4).png"
        alt="baths"
      />
      <p className="pt-1">{listing.features.baths}</p>
    </div>
  )}

  {listing?.features?.area && (
    <div className="flex items-center gap-1">
      <Image
        width={20}
        height={18}
        src="/icons/listingCardIcons/Vector (5).png"
        alt="area"
      />
      <p className="pt-1">{listing.features.area}</p>
    </div>
  )}
</div>

              </CardContent>
              <CardFooter className="flex items-center justify-between px-3 lg:px-6">
                <h4 className="self-start text-[13px] font-bold text-primary">
                  {listing.status.charAt(0).toUpperCase() +
                    listing.status.slice(1)}
                </h4>
                <div className="flex items-center gap-4 pb-5">
                  <Image
                    onClick={() => router.push(`/property/${listing?.slug}`)}
                    width={19}
                    height={19}
                    src="/icons/listingCardIcons/Vector (6).png"
                    alt="featured"
                    className="cursor-pointer"
                  />
                  {listing?.isFavorite === true ? (
                    <Image
                      width={21}
                      height={18}
                      src="/icons/listingCardIcons/heart.png"
                      alt="featured"
                      onClick={() => handleAddToFavorites(listing?.id)}
                    />
                  ) : (
                    <Image
                      width={21}
                      height={18}
                      src="/icons/listingCardIcons/Vector (7).png"
                      alt="featured"
                      onClick={() => handleAddToFavorites(listing?.id)}
                    />
                  )}

                  <Image
                    width={19}
                    height={19}
                    src="/icons/listingCardIcons/Vector (8).png"
                    alt="featured"
                  />
                </div>
              </CardFooter>
            </Card>
          ))}
        </div>
        <div className="flex items-center justify-center">
          {/* <Button className="bg-primary mx-auto mt-10 text-white h-[50px] text-[16px] font-normal">
          Load More Listing
        </Button> */}
          {totalAListings > 6 && (
            <Button
              onClick={handleToggle}
              className="bg-primary mx-auto mt-2 lg:mt-4 text-white text-[16px] font-normal flex items-center"
            >
              {isAllVisible ? t("Show Less") : t("Load More Listing")}
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
