"use client";

import { useEffect, useMemo, useState } from "react";
import Image from "next/image";
import { Modal, ModalContent, ModalBody } from "@heroui/react";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination } from "swiper/modules";
import { useTranslations } from "next-intl";
import "swiper/css";
import "swiper/css/pagination";

import {
  googleMapsEmbedUrl,
  googleMapsLinkUrl,
  type ServiceMapCoords,
} from "@/lib/serviceGeo";
import { formatRatingWithMax, parseServiceRating } from "@/lib/serviceRating";
import type { ReviewableType } from "@/lib/publicReviewsApi";
import type { ServiceDetailPackage } from "./detailHelpers";
import { ServiceStarRow } from "./ServiceRatingStars";
import ServiceDetailReviewsSection from "./ServiceDetailReviewsSection";

const PLACEHOLDER = "/placeholder.png";

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

export type ServiceDetailInfoRow = {
  label: string;
  value: string;
  valueClassName?: string;
};

export type ServiceDetailModalProps = {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  images: string[];
  imageAlt: string;
  /** All labeled fields to show (doctor, specialty, phone, etc.). */
  infoRows: ServiceDetailInfoRow[];
  descriptionLabel: string;
  description: string | null | undefined;
  /** When set, shows Google Maps embed + link at bottom of modal. */
  mapCoords?: ServiceMapCoords | null;
  /** Aggregate rating from list row (`rating` string from API). */
  serviceRatingRaw?: string | null;
  reviewableId?: string | null;
  reviewableType?: ReviewableType | null;
  /** Medical list-item `packages` only; ignored when empty. */
  packages?: ServiceDetailPackage[] | null;
  phone?: string | null;
  whatsapp?: string | null;
  onBook?: () => void;
};

function InfoRow({
  label,
  value,
  valueClassName = "text-slate-900 font-semibold",
}: {
  label: string;
  value: string;
  valueClassName?: string;
}) {
  return (
    <div
      className="flex flex-row items-start justify-between gap-3 border-b border-slate-100 pb-2.5 text-sm"
      dir="rtl"
    >
      <span className="shrink-0 text-slate-500">{label}</span>
      <span
        className={`min-w-0 flex-1 text-end leading-snug ${valueClassName}`}
      >
        {value || "—"}
      </span>
    </div>
  );
}

export default function ServiceDetailModal({
  isOpen,
  onOpenChange,
  images,
  imageAlt,
  infoRows,
  descriptionLabel,
  description,
  mapCoords,
  serviceRatingRaw,
  reviewableId,
  reviewableType,
  packages,
  phone,
  whatsapp,
  onBook,
}: ServiceDetailModalProps) {
  const tDetail = useTranslations("SERVICE_DETAIL_MODAL");
  const [imgBroken, setImgBroken] = useState<Record<number, boolean>>({});

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

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

  const showPagination = slides.length > 1;
  const waDigits = digitsForWa(whatsapp);
  const tel = String(phone ?? "").replace(/\s/g, "");
  const desc = typeof description === "string" ? description.trim() : "";

  const handleBook = () => {
    if (onBook) {
      onBook();
      return;
    }
    if (waDigits) {
      const msg = tDetail("book_message_prefill");
      window.open(
        `https://wa.me/${waDigits}?text=${encodeURIComponent(msg)}`,
        "_blank",
      );
      return;
    }
    if (tel) window.location.href = `tel:${tel}`;
  };

  const showMap = Boolean(mapCoords);
  const ratingNum = parseServiceRating(serviceRatingRaw);
  const ratingLine = formatRatingWithMax(serviceRatingRaw);
  const hasPackages = Array.isArray(packages) && packages.length > 0;

  return (
    <Modal
      isOpen={isOpen}
      onOpenChange={onOpenChange}
      size="md"
      scrollBehavior="inside"
      backdrop="blur"
      classNames={{
        base: "max-h-[92vh] max-w-lg mx-4 sm:mx-auto",
        wrapper: "items-center px-0",
        backdrop: "bg-black/40 backdrop-blur-sm",
      }}
    >
      <ModalContent className="m-0 overflow-hidden rounded-2xl border border-slate-200/90 bg-white shadow-2xl">
        {() => (
          <ModalBody className="gap-0 p-0">
            <div className="relative h-56 w-full shrink-0 overflow-hidden bg-slate-100 sm:h-64">
              {showPagination ? (
                <Swiper
                  modules={[Pagination]}
                  pagination={{ clickable: true }}
                  loop={slides.length > 1}
                  className="service-detail-modal-swiper h-full w-full"
                  dir="rtl"
                >
                  {slides.map((src, idx) => (
                    <SwiperSlide key={`${src}-${idx}`}>
                      <div className="relative h-56 w-full sm:h-64">
                        <Image
                          src={imgBroken[idx] ? PLACEHOLDER : src}
                          alt={imageAlt}
                          fill
                          sizes="(max-width: 640px) 100vw, 32rem"
                          className="object-cover"
                          onError={() =>
                            setImgBroken((prev) => ({ ...prev, [idx]: true }))
                          }
                        />
                      </div>
                    </SwiperSlide>
                  ))}
                </Swiper>
              ) : (
                <Image
                  src={imgBroken[0] ? PLACEHOLDER : slides[0]}
                  alt={imageAlt}
                  fill
                  sizes="(max-width: 640px) 100vw, 32rem"
                  className="object-cover"
                  onError={() => setImgBroken((p) => ({ ...p, 0: true }))}
                />
              )}
            </div>

            {ratingNum != null && ratingLine ? (
              <div
                className="flex flex-wrap items-center gap-2 border-b border-slate-100 px-4 py-3"
                dir="rtl"
              >
                <span className="text-sm font-semibold text-slate-500">
                  {tDetail("label_rating")}
                </span>
                <ServiceStarRow value={ratingNum} className="text-lg" />
                <span className="text-base font-extrabold text-slate-900">
                  {ratingLine}
                </span>
              </div>
            ) : null}

            <div className="space-y-1 px-4 pt-4" dir="rtl">
              {infoRows.map((row, idx) => (
                <InfoRow
                  key={`${row.label}-${idx}`}
                  label={row.label}
                  value={row.value}
                  valueClassName={row.valueClassName}
                />
              ))}
            </div>

            {desc ? (
              <div className="space-y-1.5 px-4 pt-3 border-t border-slate-100 mt-3" dir="rtl">
                <div className="text-sm text-slate-500">{descriptionLabel}</div>
                <p className="text-center text-sm leading-relaxed text-slate-700 whitespace-pre-line px-1 pb-2">
                  {desc}
                </p>
              </div>
            ) : null}

            {hasPackages ? (
              <div className="border-t border-slate-100 px-4 py-3 mt-3" dir="rtl">
                <div className="mb-2 text-sm font-bold text-slate-800">
                  {tDetail("packages_title")}
                </div>
                <ul className="space-y-2 rounded-xl bg-slate-50/90 p-3">
                  {packages!.map((pkg, idx) => (
                    <li
                      key={`${pkg.name}-${idx}`}
                      className="flex flex-row items-center justify-between gap-2 border-b border-slate-100/80 pb-2 last:border-0 last:pb-0 text-sm"
                    >
                      <span className="min-w-0 flex-1 font-medium text-slate-800">
                        {pkg.name}
                      </span>
                      <span className="shrink-0 font-extrabold text-[#1B7A50]">
                        {pkg.price}
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
            ) : null}

            <ServiceDetailReviewsSection
              isActive={isOpen}
              reviewableId={reviewableId ?? null}
              reviewableType={reviewableType ?? null}
            />

            {showMap ? (
              <div
                className="border-t border-slate-100 px-4 pb-3 pt-4 mt-3"
                dir="rtl"
              >
                <div className="mb-2 text-sm font-bold text-slate-800">
                  {tDetail("location_title")}
                </div>
                <div className="relative aspect-[16/10] w-full overflow-hidden rounded-xl border border-slate-200 bg-slate-100">
                  <iframe
                    title={tDetail("location_title")}
                    src={googleMapsEmbedUrl(mapCoords!.lat, mapCoords!.lng)}
                    className="absolute inset-0 h-full w-full border-0"
                    loading="lazy"
                    referrerPolicy="no-referrer-when-downgrade"
                  />
                </div>
                <a
                  href={googleMapsLinkUrl(mapCoords!.lat, mapCoords!.lng)}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-2 inline-flex text-sm font-bold text-[#1B7A50] hover:text-[#14623c]"
                >
                  {tDetail("open_in_maps")}
                </a>
              </div>
            ) : null}

            <div
              className="flex flex-row items-center gap-2.5 border-t border-slate-100 px-4 py-4 pb-5"
              style={{ direction: "ltr" }}
            >
              <button
                type="button"
                onClick={handleBook}
                className="min-w-0 flex-1 rounded-full bg-[#1B7A50] px-5 py-3 text-sm font-extrabold text-white shadow-md transition hover:bg-[#14623c] disabled:cursor-not-allowed disabled:opacity-50"
                disabled={!onBook && !waDigits && !tel}
              >
                {tDetail("book")}
              </button>
              <a
                href={waDigits ? `https://wa.me/${waDigits}` : undefined}
                target="_blank"
                rel="noopener noreferrer"
                title={tDetail("whatsapp_aria")}
                aria-label={tDetail("whatsapp_aria")}
                className={`grid h-12 w-12 shrink-0 place-items-center rounded-full bg-[#25D366] text-white shadow-md transition hover:bg-[#20b858] ${!waDigits ? "pointer-events-none opacity-40" : ""}`}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="h-6 w-6"
                  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={tDetail("phone_aria")}
                aria-label={tDetail("phone_aria")}
                className={`grid h-12 w-12 shrink-0 place-items-center rounded-full bg-[#0F5132] text-white shadow-md transition hover:bg-[#0c4028] ${!tel ? "pointer-events-none opacity-40" : ""}`}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="h-6 w-6"
                  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>
          </ModalBody>
        )}
      </ModalContent>
    </Modal>
  );
}
