import { useRef, type RefObject } from "react";
import { useOnClickOutside } from "usehooks-ts";
import { useModalStore } from "@/stores/useModalStore";
import type { Product } from "@/types";
import FeedbackModal from "./FeedbackFormModal";
import CloseIcon from "@/components/icons/CloseIcon";
import { LeadForm } from "@/features/lead-form/LeadForm";

const DEFAULT_MODAL_PRODUCTS = [
  "Создание сайтов",
  "Веб-тур по 360 сферам",
] as Product[];

interface QuestionFormModalProps {
  products?: Product[];
}

export default function QuestionFormModal({
  products,
}: QuestionFormModalProps) {
  const { setModal } = useModalStore();

  const formRef = useRef<HTMLDivElement>(null);

  useOnClickOutside(formRef as RefObject<HTMLElement>, () => {
    setModal(null);
  });

  return (
    <div
      ref={formRef}
      className="p-[3.333vw] w-[64.514vw] backdrop-blur-[20px] rounded-[1.111vw] z-10 bg-[radial-gradient(circle_at_bottom_right,rgba(24,25,26,0.84)_0%,rgba(45,46,47,0.86)_100%)] absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 max-md:w-[94.444vw] max-md:px-[6.667vw] max-md:py-[5.556vw] max-md:rounded-[4.444vw]"
    >
      <button
        type="button"
        onClick={() => setModal(null)}
        className="absolute lg:p-4 p-0 lg:top-[1.667vw] md:top-[3.125vw] top-[3.333vw] right-[3.333vw] md:right-[3.125vw] cursor-pointer"
      >
        <div className="text-white lg:size-[1.667vw] md:size-[3.125vw] size-[6.667vw]">
          <CloseIcon />
        </div>
      </button>
      <LeadForm
        defaultProducts={products ?? DEFAULT_MODAL_PRODUCTS}
        idPrefix="modal-"
        phonePlaceholder="+X (XXX) XXX - XX - XX"
        onSuccess={(id) => setModal(<FeedbackModal id={id} />)}
      />
    </div>
  );
}
