"use client";
import { motion } from "motion/react";
import { CrossMark } from "@/components/ui/icons";
import { fadeInOut, slideUpModal } from "@/lib/variants";
import { useEffect, useRef } from "react";
import { Button } from "../ui";
import { SelectedPrestador } from "./types";
import { LazyMapContainer, LazyMarker, LazyTileLayer } from "./cartilla-results-map";

interface Props {
  prestador: SelectedPrestador;
  setModal: (state: boolean) => void;
}

export const CartillaModal = ({ setModal, prestador }: Props) => {
  const contentRef = useRef<HTMLDivElement>(null);
  const hasCoords = typeof prestador.lat === "number" && typeof prestador.lng === "number";

  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev || "auto";
    };
  }, []);

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setModal(false);
    };
    window.addEventListener("keydown", handleKey);
    return () => window.removeEventListener("keydown", handleKey);
  }, [setModal]);

  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (contentRef.current && !contentRef.current.contains(e.target as Node)) setModal(false);
  };

  return (
    <motion.div
      className="fixed bg-black/80 inset-0 z-9999 backdrop-blur-[0.125rem] overflow-hidden"
      {...fadeInOut(0.5, 0.5)}
      onMouseDown={handleBackdropClick}
      role="dialog"
      aria-modal="true"
      aria-labelledby="modal-title"
    >
      <motion.div
        ref={contentRef}
        className="absolute w-[min(95%,37.5rem)] h-[90svh] bg-white rounded-3xl left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2"
        {...slideUpModal()}
      >
        <div className="px-5 pb-5 h-[95%] flex flex-col gap-4">
          <div className="flex justify-between items-center w-full mt-5 shrink-0">
            <h2 id="modal-title" className="font-medium text-3xl">
              {prestador.nombre}
            </h2>
            <button
              className="text-contigo-verde transition-colors duration-100 hover:text-contigo-violeta"
              onClick={() => setModal(false)}
              aria-label="Cerrar modal"
            >
              <CrossMark className="size-6" />
            </button>
          </div>

          <div className="max-h-32 overflow-auto w-full scrollbar-contigo space-y-2 text-base shrink-0">
            {prestador.especialidades
              .slice()
              .sort()
              .map((s, i) => (
                <p key={i}>{s}</p>
              ))}
          </div>

          <div className="flex-1 min-h-0 w-full rounded-2xl overflow-hidden bg-gray-100">
            {hasCoords ? (
              <LazyMapContainer
                center={[prestador.lat!, prestador.lng!]}
                zoom={15}
                className="w-full h-full"
                scrollWheelZoom={false}
              >
                <LazyTileLayer
                  attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                  url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <LazyMarker position={[prestador.lat!, prestador.lng!]} title={prestador.nombre} />
              </LazyMapContainer>
            ) : (
              <div className="w-full h-full flex items-center justify-center text-gray-500 text-sm">
                Ubicación no disponible
              </div>
            )}
          </div>

          <Button className="w-full shrink-0" onClick={() => setModal(false)}>
            Cerrar
          </Button>
        </div>
      </motion.div>
    </motion.div>
  );
};
