"use client";

import { motion, AnimatePresence } from "motion/react";
import { useEffect } from "react";
import TermsAndConditionsHeader from "./TermsAndConditions/TermsAndConditionsHeader";
import TermsAndConditionsContent from "./TermsAndConditions/TermsAndConditionsContent";
import TermsAndConditionsActions from "./TermsAndConditions/TermsAndConditionsActions";
import { Card } from "@/components/ui/card";
import { Policy } from "@/types/policy";

interface TermsAndConditionsModalProps {
  isOpen: boolean;
  onClose: (agreed?: boolean) => void;
  terms?: Policy | null;
}

export default function TermsAndConditionsModal({
  isOpen,
  onClose,
  terms,
}: TermsAndConditionsModalProps) {
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [isOpen]);

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

  return (
    <AnimatePresence>
      {isOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm"
            onClick={() => onClose()}
          />
          <motion.div
            initial={{ opacity: 0, scale: 0.95, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 20 }}
            className="relative w-full max-w-7xl max-h-[90vh] overflow-y-auto"
          >
            <Card className="flex flex-col h-full overflow-hidden p-6 md:p-10 bg-white/90 dark:bg-black/90 backdrop-blur-md border border-white/20 shadow-2xl text-primary-darker">
              <div className="flex-1 overflow-y-auto pr-2 custom-scrollbar">
                <div className="space-y-8">
                  <TermsAndConditionsHeader updatedAt={terms?.updated_at} />
                  <TermsAndConditionsContent content={terms?.content} />
                </div>
              </div>
              <TermsAndConditionsActions onToggle={onClose} />
            </Card>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
}
