"use client";

import React from "react";
import Link from "next/link";
import Pagination from "../properties/contents/pagination";
import { getStrapiImageUrl } from "@/utils/getStrapiUrl";
import type { PropertyData } from "@/utils/strapi";
import { getPrimaryTypeSlugForUrl } from "@/utils/propertyTypes";

interface PropertyCardProps {
  image: string | null;
  hoverImage?: string | null;
  title: string;
  category: string;
  location?: string;
  slug?: string;
  propertyType?: string;
}

// Helper function to get image URL with fallback to heroBackgroundImageMobile
const getImageUrl = (
  imageData:
    | {
        url?: string;
        data?: {
          attributes: {
            url: string;
            alternativeText?: string;
          };
        };
      }
    | null
    | undefined,
  fallbackImageData?:
    | {
        url?: string;
        data?: {
          attributes: {
            url: string;
            alternativeText?: string;
          };
        };
      }
    | null
    | undefined,
): string | null => {
  // First try the primary image
  if (imageData) {
    const imageUrl = imageData.url || imageData.data?.attributes?.url;
    if (imageUrl) {
      return getStrapiImageUrl(imageUrl);
    }
  }

  // If primary image not found, try fallback (heroBackgroundImageMobile)
  if (fallbackImageData) {
    const fallbackUrl =
      fallbackImageData.url || fallbackImageData.data?.attributes?.url;
    if (fallbackUrl) {
      return getStrapiImageUrl(fallbackUrl);
    }
  }

  // Return null if no image found (don't use default images)
  return null;
};

const PropertyCard = ({
  image,
  hoverImage,
  title,
  category,
  location,
  slug,
  propertyType,
}: PropertyCardProps) => {
  const href =
    slug && propertyType
      ? `/properties/${propertyType}/${slug}`
      : "/property-details";

  return (
    <div className="group">
      <Link href={href}>
        <div className="relative w-full aspect-[3/4] overflow-hidden cursor-pointer">
          {/* Day image (base image) */}
          {image && (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={image}
              alt={title}
              className="w-full h-full object-cover transition-opacity duration-[1500ms] ease-in-out group-hover:opacity-0"
            />
          )}
          {/* Night image (hover image) */}
          {hoverImage && (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={hoverImage}
              alt={`${title} - Night view`}
              className="absolute inset-0 w-full h-full object-cover opacity-0 transition-opacity duration-[1500ms] ease-in-out group-hover:opacity-100"
            />
          )}
          {/* Placeholder if no images */}
          {!image && (
            <div className="w-full h-full bg-gray-200 flex items-center justify-center">
              <span className="text-gray-400 text-sm">No image available</span>
            </div>
          )}
          <div className="bg-black/25 absolute w-full h-full top-0 left-0"></div>
          <h3 className="font-creato text-white text-[14px] lg:text-[18px] font-light tracking-[0.38em] leading-[110%] uppercase absolute top-24 lg:top-32 -right-10 lg:-right-14 rotate-270 group-hover:scale-[1.1] transition-all duration-1000">
            {category}
          </h3>
        </div>
      </Link>
      <div className="pt-5 md:pt-6">
        <Link href={href}>
          <h3 className="text-[#333333] leading-tight font-creato font-medium text-[14px] md:text-[18px] xl:text-[24px] tracking-widest uppercase mb-1.5">
            {title}
          </h3>
        </Link>
        {/* location block */}
        {location && (
          <div>
            <p className="text-[#888888] font-creato font-normal leading-relaxed tracking-widest xl:tracking-widest text-[14px]">
              {location}
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

interface SearchContentGridProps {
  properties: PropertyData[];
  totalItems?: number;
  currentPage?: number;
  itemsPerPage?: number;
}

const SearchContentGrid = ({
  properties,
  totalItems = 0,
  itemsPerPage = 8,
}: SearchContentGridProps) => {
  if (properties.length === 0) {
    return (
      <section className="bg-white py-10 lg:py-24">
        <div className="container mx-auto px-4 lg:px-8">
          <div className="text-center py-16">
            <p className="text-gray-500">No properties found.</p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="bg-white py-10 lg:py-24">
      <div className="container mx-auto px-4 lg:px-8">
        {/* Property Grid - 3 columns on desktop, 2 on tablet, 1 on mobile */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 lg:gap-12 xl:gap-16">
          {properties.map((property) => {
            const urlSlug = getPrimaryTypeSlugForUrl(property);
            const categoryLabel =
              property.types?.find((t) => t.slug === urlSlug)?.name ||
              property.types?.[0]?.name ||
              urlSlug;
            // Get cardImage with fallback to heroBackgroundImageMobile
            const cardImage = getImageUrl(
              property.cardImage,
              property.heroBackgroundImageMobile,
            );

            // Get cardHoverImage with fallback to heroBackgroundImageMobile (only if cardImage exists)
            const cardHoverImage = property.cardHoverImage
              ? getImageUrl(
                  property.cardHoverImage,
                  property.heroBackgroundImageMobile,
                )
              : null;

            return (
              <PropertyCard
                key={property.id}
                image={cardImage}
                hoverImage={cardHoverImage || undefined}
                title={property.title}
                category={categoryLabel}
                location={property.location?.name || ""}
                slug={property.slug}
                propertyType={urlSlug}
              />
            );
          })}
        </div>
        {/* Pagination */}
        <div className="flex justify-center pt-12 xl:pt-20 pb-10">
          <Pagination
            totalItems={totalItems}
            itemsPerPage={itemsPerPage}
            basePath="/search"
          />
        </div>
      </div>
    </section>
  );
};

export default SearchContentGrid;
