"use client";

import { useEffect, useMemo, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination } from "swiper/modules";
import { User, Briefcase, ChevronRight } from "lucide-react";
import { useTranslations } from "next-intl";
import "swiper/css";
import { ServiceRatingSummary } from "./ServiceRatingStars";

function digitsForWa(raw: string | undefined | null): string {
  if (raw == null || !String(raw).trim()) return "";
  return String(raw).replace(/\D/g, "");
}

const IMAGE_FALLBACK = "/placeholder.jpg";

export type ServiceListingCardProps = {
  images: string[];
  imageAlt: string;
  primaryLabel: string;
  primaryValue: string;
  secondaryLabel: string;
  secondaryValue: string;
  phone?: string;
  whatsapp?: string;
  /** Shown with chevron; use `href` or `onDetailsClick`. */
  detailsLabel?: string;
  detailsHref?: string | null;
  onDetailsClick?: () => void;
  className?: string;
  /** List row `rating` (string); shown with stars when parsable. */
  ratingRaw?: unknown;
  /** Preformatted e.g. "4.2 / 5" */
  ratingLine?: string | null;
};

export default function ServiceListingCard({
  images,
  imageAlt,
  primaryLabel,
  primaryValue,
  secondaryLabel,
  secondaryValue,
  phone,
  whatsapp,
  detailsLabel,
  detailsHref,
  onDetailsClick,
  className = "",
  ratingRaw,
  ratingLine,
}: ServiceListingCardProps) {
  const t = useTranslations("TRANSPORT_CARD");
  const tCard = useTranslations("SERVICE_LISTING_CARD");
  const detailsText = detailsLabel ?? tCard("details");

  const slides = useMemo(() => {
    const u = (images || []).map((s) => String(s).trim()).filter(Boolean);
    return u.length ? u : [IMAGE_FALLBACK];
  }, [images]);

  const [imgBroken, setImgBroken] = useState<Record<number, boolean>>({});

  useEffect(() => {
    setImgBroken({});
  }, [images]);

  const waDigits = digitsForWa(whatsapp);
  const tel = String(phone ?? "").replace(/\s/g, "");

  const hasDetailsAction =
    (typeof detailsHref === "string" && detailsHref.length > 0) ||
    typeof onDetailsClick === "function";

  const showPagination = slides.length > 1;

  return (
    <article
      className={`service-listing-card flex h-full flex-col overflow-hidden rounded-2xl border border-slate-200/90 bg-white shadow-md transition-shadow duration-300 hover:shadow-lg ${className}`}
      dir="rtl"
    >
      <div className="relative h-56 w-full shrink-0 overflow-hidden md:h-60">
        {showPagination ? (
          <Swiper
            modules={[Pagination]}
            pagination={{
              clickable: true,
              dynamicBullets: false,
            }}
            loop={slides.length > 1}
            className="service-listing-card-swiper h-full w-full"
            dir="rtl"
          >
            {slides.map((src, idx) => (
              <SwiperSlide key={`${src}-${idx}`}>
                <div className="relative h-56 w-full md:h-60">
                  <Image
                    src={imgBroken[idx] ? IMAGE_FALLBACK : src}
                    alt={imageAlt}
                    fill
                    sizes="(max-width: 640px) 100vw, 25vw"
                    className="object-cover"
                    onError={() =>
                      setImgBroken((prev) => ({ ...prev, [idx]: true }))
                    }
                  />
                </div>
              </SwiperSlide>
            ))}
          </Swiper>
        ) : (
          <div className="relative h-full w-full">
            <Image
              src={imgBroken[0] ? IMAGE_FALLBACK : slides[0]}
              alt={imageAlt}
              fill
              sizes="(max-width: 640px) 100vw, 25vw"
              className="object-cover"
              onError={() => setImgBroken((prev) => ({ ...prev, 0: true }))}
            />
          </div>
        )}
      </div>

      <div className="flex flex-1 flex-col px-4 pb-4 pt-3">
        <div className="space-y-2.5 text-sm">
          <div className="flex items-start gap-2">
            <User
              className="mt-0.5 h-4 w-4 shrink-0 text-slate-400"
              aria-hidden
            />
            <div className="min-w-0 flex-1 leading-snug">
              <span className="text-slate-500">{primaryLabel}</span>
              <span className="mr-1 font-semibold text-slate-900">
                {primaryValue || "—"}
              </span>
            </div>
          </div>

          <div className="flex items-start gap-2">
            <Briefcase
              className="mt-0.5 h-4 w-4 shrink-0 text-slate-400"
              aria-hidden
            />
            <div className="min-w-0 flex-1 leading-snug">
              <span className="text-slate-500">{secondaryLabel}</span>
              <span className="mr-1 font-bold text-[#1B7A50]">
                {secondaryValue || "—"}
              </span>
            </div>
          </div>

          <ServiceRatingSummary ratingRaw={ratingRaw} textLabel={ratingLine} />
        </div>

        <div
          className="mt-auto flex flex-row items-center justify-between gap-3 border-t border-slate-100 pt-3"
          style={{ direction: "ltr" }}
        >
          {hasDetailsAction ? (
            detailsHref ? (
              <Link
                href={detailsHref}
                className="inline-flex items-center gap-1 text-sm font-bold text-slate-700 hover:text-[#0F5132]"
              >
                <span>{detailsText}</span>
                <ChevronRight className="h-4 w-4" aria-hidden />
              </Link>
            ) : (
              <button
                type="button"
                onClick={onDetailsClick}
                className="inline-flex items-center gap-1 text-sm font-bold text-slate-700 hover:text-[#0F5132]"
              >
                <span>{detailsText}</span>
                <ChevronRight className="h-4 w-4" aria-hidden />
              </button>
            )
          ) : (
            <span className="text-sm text-transparent select-none">.</span>
          )}

          <div className="flex items-center gap-2">
            <a
              href={waDigits ? `https://wa.me/${waDigits}` : undefined}
              target="_blank"
              rel="noopener noreferrer"
              title={t("whatsapp")}
              aria-label={t("whatsapp")}
              className={`grid h-10 w-10 shrink-0 place-items-center rounded-full bg-[#25D366] text-white shadow-sm transition hover:bg-[#20b858] ${!waDigits ? "pointer-events-none opacity-40" : ""}`}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5"
                viewBox="0 0 448 512"
                aria-hidden
              >
                <path
                  fill="currentColor"
                  d="M380.9 97.1C339 55.1 283.2 32 224.6 32c-117.3 0-212.6 95.2-212.6 212.2 0 37.4 9.8 73.9 28.5 106.1L0 480l132.6-34.8c30.9 16.9 65.9 25.8 101.9 25.8h.1c117.3 0 212.6-95.2 212.6-212.2 0-58.6-23.2-114.4-66.3-156.7zM224.6 438.6c-31.8 0-62.9-8.5-90.1-24.6l-6.5-3.9-78.6 20.6 21-76.6-4.2-7c-17.5-29.1-26.7-62.4-26.7-96.3 0-103.5 84.2-187.7 187.9-187.7 50.2 0 97.3 19.5 132.7 55 35.4 35.3 54.9 82.3 54.8 132.3-.2 103.5-84.3 187.8-187.8 187.8zm101.7-138.2c-5.6-2.8-33.1-16.3-38.2-18.1-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18.1-17.6 21.8-3.2 3.7-6.5 4.2-12.1 1.4-5.6-2.8-23.6-8.7-45-27.9-16.6-14.8-27.8-33.1-31-38.7-3.2-5.6-.3-8.6 2.4-11.3 2.5-2.5 5.6-6.5 8.4-9.7 2.8-3.2 3.7-5.6 5.6-9.3 1.9-3.7.9-7-.5-9.8-1.4-2.8-12.5-30.1-17.1-41.3-4.5-10.8-9.1-9.4-12.5-9.6-3.2-.2-7-.2-10.8-.2s-9.8 1.4-14.9 7c-5.1 5.6-19.5 19.1-19.5 46.6s20 54 22.8 57.8c2.8 3.7 39.1 59.6 94.7 83.6 13.2 5.7 23.5 9.1 31.5 11.6 13.2 4.2 25.2 3.6 34.7 2.2 10.6-1.6 33.1-13.5 37.8-26.6 4.7-13.1 4.7-24.3 3.3-26.6-1.3-2.3-5.1-3.7-10.7-6.5z"
                />
              </svg>
            </a>
            <a
              href={tel ? `tel:${tel}` : undefined}
              title={t("call")}
              aria-label={t("call")}
              className={`grid h-10 w-10 shrink-0 place-items-center rounded-full bg-[#0F5132] text-white shadow-sm transition hover:bg-[#0c4028] ${!tel ? "pointer-events-none opacity-40" : ""}`}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                aria-hidden
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M3 5a2 2 0 012-2h1.28a2 2 0 011.94 1.515l.518 2.073a2 2 0 01-.45 1.86l-1.1 1.1a16 16 0 006.364 6.364l1.1-1.1a2 2 0 011.86-.45l2.073.518A2 2 0 0021 18.72V20a2 2 0 01-2 2h-.25C9.455 22 2 14.545 2 5.25V5a2 2 0 011-1.732V3z"
                />
              </svg>
            </a>
          </div>
        </div>
      </div>
    </article>
  );
}
