import Footer from "@/app/components/Footer";
import AgentContactInfo from "@/app/components/listingDetailPage/AgentContactInfo";
import Gallery from "@/app/components/listingDetailPage/Gallery";
import Location from "@/app/components/listingDetailPage/Location";
import { PropertyListingsRelated } from "@/app/components/listingDetailPage/PropertyListingsRelated";
import Navbar from "@/app/components/Navbar/Navbar";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { baseUrl } from "@/lib/config";
import { CheckCircle2 } from "lucide-react";
import Image from "next/image";
import React from "react";
async function getProperty(slug) {
  const res = await fetch(`${baseUrl}/api/property/${slug}`, {
    cache: "no-store", // SSR without caching (like getServerSideProps)
  });

  if (!res.ok) {
    if (res.status === 404) {
      return <div>Page not found</div>;
    }
    throw new Error("Failed to fetch blog");
  }

  return res.json();
}

async function getRelatedProperties(id) {
  try {
    const res = await fetch(`${baseUrl}/api/related-properties/${id}`, {
      cache: "no-store",
    });
    if (!res.ok) {
      if (res.status === 404) {
        return []; // return empty array instead of JSX
      }
      throw new Error("Failed to fetch related properties");
    }
    return res.json();
  } catch (err) {
    console.error("getRelatedProperties error:", err);
    return []; // safe fallback
  }
}

const propertyData = {
  slug: "luxury-villa-dubai",
  title: "Luxury Villa in Dubai",
  description:
    "<p>This is a <strong>beautiful</strong> villa located in the heart of Dubai, featuring modern architecture and premium amenities.</p>", // rich text HTML
  price: 2500000,
  location: "Dubai, UAE",
  type: "Villa",
  features: {
    beds: "9 beds",
    baths: "6 baths",
    area: "12000 sqft",
  },
  gallery: [
    "/images/galleryImages/p1.jpg",
    "/images/galleryImages/p2.jpg",
    "/images/galleryImages/p3.jpg",
    "/images/galleryImages/p4.jpg",
    "/images/galleryImages/p1.jpg",
    "/images/galleryImages/p2.jpg",
    "/images/galleryImages/p3.jpg",
    "/images/galleryImages/p4.jpg",
  ],
  mainGalleryLayout: {
    main: "/images/galleryImages/p1.jpg",
    sideImages: [
      "/images/galleryImages/p4.jpg",
      "/images/galleryImages/p1.jpg",
      "/images/galleryImages/p2.jpg",
      "/images/galleryImages/p3.jpg",
    ],
  },
};

export default async function PropertyDetailPage({ params }) {
  const { slug } = params;
  // const blog = articles.find((s) => s.slug === slug);
  const fullProperty = await getProperty(slug);
  console.log("ffffffff", fullProperty);
  const property = fullProperty?.data;
  if (!property) {
    return <div>Property not found</div>;
  }
  const relatedProperties = await getRelatedProperties(property?.id);

  console.log("property", property);
  console.log("relatedProperties", relatedProperties);

  return (
    <div>
      <Navbar />
      <div className="mx-5 md:mx-[50px] lg:mx-[96px]">
        <div className="bg-ligbg px-3 sm:px-5 lg:px-7 mt-8 rounded-xl py-2 sm:py-3 lg:py-4 ">
          <div className="flex flex-row justify-center items-center gap-4 ">
            <div className="flex-1">
              <div className="">
                <div className="flex items-center justify-between">
                  <h1 className="text-primary font-medium text-lg md:text-xl lg:text-xl whitespace-nowrap">
                    {property?.price} SAR
                  </h1>
                  {property?.purpose ? (
                    <div className="bg-secordary z-10 w-[80px] h-[30px] px-2 rounded">
                      <div className="flex items-center gap-2 text-white h-full justify-center">
                        <p className="text-[10px] font-semibold">
                          {property?.purpose}
                        </p>
                      </div>
                    </div>
                  ) : null}
                </div>
                <h1 className="font-medium  text-lg sm:text-xl lg:text-2xl max-w-full ">
                  {property?.name}
                </h1>
                <div className="flex items-center rounded-md  lg:mt-0">
                  <Image
                    src="/icons/listingDetailPageIcons/Icon.png"
                    width={16}
                    height={16}
                    alt="sadu-logo"
                  />

                  <p className="text-primary text-sm pl-1 whitespace-nowrap">
                    {property?.country} {property?.city}
                  </p>
                </div>
                {/* <div className="flex items-center border-2 border-primary bg-primary px-4 py-1 rounded-sm mt-2 lg:mt-0 cursor-pointer">
                  <p className="text-white font-medium text-sm pl-1 whitespace-nowrap">
                    download pdf
                  </p>
                </div>
                <div className="flex gap-2 mt-2 lg:mt-0 flex-wrap">
                  <div className="flex items-center w-8 h-8 border-2 border-primary bg-primary rounded-full justify-center cursor-pointer">
                    <Image
                      src="/icons/listingDetailPageIcons/Vector.png"
                      width={11}
                      height={11}
                      alt="sadu-logo"
                    />
                  </div>
                  <div className="flex items-center w-8 h-8 border-2 border-primary bg-primary rounded-full justify-center cursor-pointer">
                    <Image
                      src="/icons/listingDetailPageIcons/material-symbols_share-outline.png"
                      width={11}
                      height={11}
                      alt="sadu-logo"
                    />
                  </div>
                  <div className="flex items-center w-8 h-8 border-2 border-primary bg-primary rounded-full justify-center cursor-pointer">
                    <Image
                      src="/icons/listingDetailPageIcons/ion_git-pull-request-outline.png"
                      width={11}
                      height={11}
                      alt="sadu-logo"
                    />
                  </div>
                </div> */}
              </div>
              {/* <p className="text-gray text-sm sm:text-base mt-2 max-w-full text-center lg:text-left">
                Spacious villa with private pool in gated community
              </p> */}
            </div>
            {/* <div className="mt-4 md:mt-0 flex flex-col lg:items-start ">
              <p className="text-black text-sm font-medium ">Price</p>
              <h1 className="font-semibold text-xl sm:text-2xl whitespace-nowrap">
                5,800,000 SAR
              </h1>
            </div> */}
          </div>
        </div>
        <Gallery property={property} />
        {/* //below images/ */}
        <div className="mt-5">
          <div className="flex items-center flex-wrap gap-3 lg:gap-5">
            {property?.category && (
              <div className="flex items-center gap-1 ">
                <Image
                  width={20}
                  height={18}
                  src="/icons/listingDetailPageIcons/Vector (20).png"
                  alt="featured"
                />
                <p className="pt-1">{property?.category}</p>
                {/* <p className="pt-1">{listing?.features?.beds}</p> */}
              </div>
            )}
            {property?.bedrooms && (
              <div className="flex items-center gap-1 ">
                <Image
                  width={20}
                  height={18}
                  src="/icons/listingCardIcons/Vector (3).png"
                  alt="featured"
                />
                <p className="pt-1">{property?.bedrooms} Beds</p>
                {/* <p className="pt-1">{listing?.features?.beds}</p> */}
              </div>
            )}
            {property?.bathrooms && (
              <div className="flex items-center gap-1 ">
                <Image
                  width={20}
                  height={18}
                  src="/icons/listingCardIcons/Vector (4).png"
                  alt="featured"
                />
                <p className="pt-1">{property?.bathrooms} Baths</p>
                {/* <p className="pt-1">{listing?.features?.baths}</p> */}
              </div>
            )}
            {property?.size_sqft && (
              <div className="flex items-center gap-1 ">
                <Image
                  width={20}
                  height={18}
                  src="/icons/listingCardIcons/Vector (5).png"
                  alt="featured"
                />
                <p className="pt-1">{property?.size_sqft} sqft</p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
          </div>
          {/* //extra features// */}
          <div className="flex items-center flex-wrap gap-x-3 gap-y-1 lg:gap-x-5 lg:gap-y-3 pt-5">
            {property?.builder_name && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Builder Name: </span>
                <p className="pt-1">{property?.builder_name} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.construction_completion && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">
                  Construction Completion Date:{" "}
                </span>

                <p className="pt-1">{property?.construction_completion} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.floor_no && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Floor No.: </span>

                <p className="pt-1">{property?.floor_no} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.furnished && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Furnished: </span>

                <p className="pt-1">{property?.furnished} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.neighborhood && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Neighborhood: </span>
                <p className="pt-1">{property?.neighborhood} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.no_apartments && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">No. of Apartments: </span>

                <p className="pt-1">{property?.no_apartments} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.no_floor && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">No. of Floors: </span>
                <p className="pt-1">{property?.no_floor} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.property_status && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Property Status: </span>

                <p className="pt-1">{property?.property_status} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.type && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Property Type: </span>

                <p className="pt-1">{property?.type} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.agreement_type && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Agreement Type: </span>

                <p className="pt-1">{property?.agreement_type} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.payment_condition && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Payment Condition: </span>
                <p className="pt-1">{property?.payment_condition} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
            {property?.rent_amount && (
              <div className="flex items-center gap-1 ">
                <span className="font-semibold">Rent Amount: </span>
                <p className="pt-1">{property?.rent_amount} </p>
                {/* <p className="pt-1">{listing?.features?.area}</p> */}
              </div>
            )}
          </div>
          <h1 className="font-semibold text-lg ps-2 pb-2 lg:text-xl text-black mt-[20px]">
            Description
          </h1>
          <div className="px-4 py-1  border-2 rounded-2xl">
            {/* <p className="font-normal mt-[8px] text-[14px] md:text-[16px] lg:text-[18px] text-gray  ">
              Experience elevated living in this stunning 4-bedroom luxury
              villa, located in one of Riyadh’s most prestigious neighborhoods.
              This spacious home features elegant interiors, high-end finishes,
              and abundant natural light throughout. Enjoy a private garden,
              modern kitchen, en-suite bathrooms, and a dedicated maid’s room.
              Perfect for families seeking comfort, privacy, and style—just
              minutes away from top schools, shopping centers, and key city
              landmarks.
            </p> */}
            <div
              className="font-normal mt-[8px] text-[14px] md:text-[16px] lg:text-[18px] text-gray"
              dangerouslySetInnerHTML={{ __html: property?.short_description }}
            />
            {/* <p className="font-normal mt-[8px] text-[14px] md:text-[16px] lg:text-[18px] text-gray  ">
              Experience elevated living in this stunning 4-bedroom luxury
              villa, located in one of Riyadh’s most prestigious neighborhoods.
              This spacious home features elegant interiors, high-end finishes,
              and abundant natural light throughout. Enjoy a private garden,
              modern kitchen, en-suite bathrooms, and a dedicated maid’s room.
              Perfect for families seeking comfort, privacy, and style—just
              minutes away from top schools, shopping centers, and key city
              landmarks.
            </p> */}
            <div
              className="font-normal mt-[8px] text-[14px] md:text-[16px] lg:text-[18px] text-gray"
              dangerouslySetInnerHTML={{ __html: property?.description }}
            />
          </div>
        </div>
        <section className="w-full py-6">
          <h2 className="text-2xl font-semibold mb-4">Amenities</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {property?.amenities.map((item) => (
              <Card
                key={item.id}
                className="border-none bg-ligbg transition-colors py-3"
              >
                <CardContent className="flex items-center gap-3 px-2 py-1">
                  {/* Icon or dot */}
                  <CheckCircle2 className="text-primary w-5 h-5 flex-shrink-0" />
                  {/* Amenity name */}
                  <p className="text-sm text-primary">{item.name}</p>
                </CardContent>
              </Card>
            ))}
          </div>
        </section>
        <section className="w-full py-6">
          <h2 className="text-2xl font-semibold mb-4">Units</h2>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {property?.units?.map((unit) => (
              <Card
                key={unit.id}
                className="borde-none bg-ligbg transition-colors pt-0 gap-3"
              >
                {unit?.floor_plan_image && (
                  <div className="relative w-full h-48">
                    <Image
                      src="/icons/listingCardIcons/Vector (5).png"
                      // src={`${baseUrl}/${unit.floor_plan_image}`}
                      alt={`Floor plan of unit ${unit.unit_type}`}
                      fill
                      className="object-cover rounded-t-lg"
                    />
                  </div>
                )}

                <CardHeader className="px-4">
                  <CardTitle className="text-lg text-primary">
                    Unit Type {unit.unit_type}
                  </CardTitle>
                </CardHeader>

                <CardContent className="grid grid-cols-2 gap-x-4 px-4 gap-y-2 text-sm text-primary">
                  <div className="flex justify-between">
                    <span>Bedrooms:</span>
                    <span>{unit.bedrooms}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Bathrooms:</span>
                    <span>{unit.bathrooms}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Kitchens:</span>
                    <span>{unit.kitchens}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Dining Rooms:</span>
                    <span>{unit.dining_rooms}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Living Rooms:</span>
                    <span>{unit.living_rooms}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Salons:</span>
                    <span>{unit.salons}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Driver’s Rooms:</span>
                    <span>{unit.drivers_rooms}</span>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </section>

        {/* <div className="w-full">
          <div className="w-full">
            <div className="grid grid-cols-1 lg:grid-cols-[30%_70%]  gap-y-12 ">
              <div className="mt-[50px]">
                <h1 className="font-semibold text-2xl text-black lg:text-left text-center">
                  Key Features
                </h1>
                <div className="flex flex-row lg:justify-start justify-center mt-[41px]">
                  <div className="grid grid-cols-1">
                    {features.map((feature, index) => (
                      <div
                        key={index}
                        className={`flex items-center ${
                          index !== 0 ? "mt-[30px]" : ""
                        }`}
                      >
                        
                        <Image
                          src={feature.img}
                          width={16}
                          height={16}
                          alt="sadu-logo"
                        />

                        <p className="pl-1 font-light xl:text-sm md:text-xs sm:text-sm">
                          {feature.value}
                          <span className="pl-2 font-light xl:text-sm md:text-xs sm:text-sm">
                            {feature.label}
                          </span>
                        </p>
                      </div>
                    ))}
                  </div>
                  <div className="w-px bg-[#E1E1E1]   mx-5" />
                  <div className="grid grid-cols-1 gap-[8px] max-h-20">
                    {features2.map((feature, index) => (
                      <div
                        key={index}
                        className="flex items-start space-x-2" 
                      >
                        <Image
                          src={feature.img}
                          width={16}
                          height={16}
                          alt="sadu-logo"
                        />
                        <p className="font-light xl:text-sm md:text-xs sm:text-sm leading-none">
                          {feature.value}
                          <span className="pl-2 font-light xl:text-sm md:text-xs sm:text-sm">
                            {feature.label}
                          </span>
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
              <div className="mt-[50px] ml-5">
                <h1 className="font-semibold text-2xl text-black">
                  Map Location
                </h1>
                <div className="w-full  h-[316px] mt-[17px]">
                  <iframe
                    className="w-full h-full rounded-2xl"
                    src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3624.6450343813747!2d46.67529577588334!3d24.713551078052975!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3e2f038d0923af4d%3A0xc7f0f65d8f37a8ce!2sRiyadh%2C%20Saudi%20Arabia!5e0!3m2!1sen!2sus!4v1625215781694!5m2!1sen!2sus"
                    allowFullScreen=""
                    loading="lazy"
                    referrerPolicy="no-referrer-when-downgrade"
                  ></iframe>
                </div>
              </div>
            </div>
          </div>
        </div> */}
        <Location />
        {/* Form */}
        <AgentContactInfo property_id={property?.id} property={property} />
        <PropertyListingsRelated relatedProperties={relatedProperties} />
      </div>
      <Footer />
    </div>
  );
}
