"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";

interface Props {
  content: string[];
  setModal: (state: boolean) => void;
}

export const CartillaModal = ({ setModal, content }: Props) => {
  const contentRef = useRef<HTMLDivElement>(null);

  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 h-[95%] flex flex-col gap-4 items-center justify-between">
          <div className="flex justify-between items-center w-full mt-5">
            <h2 id="modal-title" className="font-medium text-3xl">
              Especialidades
            </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="overflow-auto h-full w-full scrollbar-contigo space-y-2 text-base">
            {content.sort().map((s, i) => (
              <p key={i}>{s}</p>
            ))}
          </div>

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