"use client";

import type { Certificate } from "@/types";
import Image from "next/image";
import { X, ChevronLeft, ChevronRight, Building } from "lucide-react";
import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";

interface CertificateModalProps {
  certificate: Certificate;
  onClose: () => void;
  certificates: Certificate[];
  onNavigate: (certificate: Certificate) => void;
}

export default function CertificateModal({
  certificate,
  onClose,
  certificates,
  onNavigate,
}: CertificateModalProps) {
  const [isImageLoaded, setIsImageLoaded] = useState(false);

  // const formattedDate = new Date(certificate.created_at).toLocaleDateString();

  const currentIndex = certificates.findIndex((c) => c.id === certificate.id);

  const prevCertificate =
    currentIndex > 0 ? certificates[currentIndex - 1] : null;
  const nextCertificate =
    currentIndex < certificates.length - 1
      ? certificates[currentIndex + 1]
      : null;

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      } else if (e.key === "ArrowLeft" && prevCertificate) {
        onNavigate(prevCertificate);
      } else if (e.key === "ArrowRight" && nextCertificate) {
        onNavigate(nextCertificate);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose, prevCertificate, nextCertificate, onNavigate]);

  return (
    <AnimatePresence>
      <motion.div
        className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4 md:p-8"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        onClick={onClose}
      >
        <motion.div
          className="relative bg-white rounded-xl overflow-hidden max-w-5xl w-full max-h-[90vh] flex flex-col"
          initial={{ scale: 0.9, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          exit={{ scale: 0.9, opacity: 0 }}
          transition={{ type: "spring", damping: 25, stiffness: 300 }}
          onClick={(e) => e.stopPropagation()}
        >
          <button
            className="absolute top-4 right-4 z-10 bg-white/10 backdrop-blur-sm text-white hover:bg-white/20 rounded-full p-2 transition-colors"
            onClick={onClose}
            aria-label="Close modal"
          >
            <X className="w-5 h-5" />
          </button>

          <div className="absolute top-1/2 left-4 -translate-y-1/2 z-10 flex space-x-2">
            {prevCertificate && (
              <button
                className="bg-white/10 backdrop-blur-sm text-white hover:bg-white/20 rounded-full p-2 transition-colors"
                onClick={(e) => {
                  e.stopPropagation();
                  onNavigate(prevCertificate);
                }}
                aria-label="Previous certificate"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>
            )}
          </div>

          <div className="absolute top-1/2 right-4 -translate-y-1/2 z-10 flex space-x-2">
            {nextCertificate && (
              <button
                className="bg-white/10 backdrop-blur-sm text-white hover:bg-white/20 rounded-full p-2 transition-colors"
                onClick={(e) => {
                  e.stopPropagation();
                  onNavigate(nextCertificate);
                }}
                aria-label="Next certificate"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            )}
          </div>

          <div className="overflow-y-auto">
            <div className="relative bg-gray-100 flex justify-center items-center">
              {!isImageLoaded && (
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="w-10 h-10 border-4 border-gray-200 border-t-red-600 rounded-full animate-spin"></div>
                </div>
              )}
              <Image
                src={`${process.env.NEXT_PUBLIC_API_URL}/storage/${certificate.image}`}
                alt={certificate.title}
                width={1000}
                height={800}
                className={`max-h-[70vh] w-auto object-contain ${isImageLoaded ? "opacity-100" : "opacity-0"}`}
                onLoad={() => setIsImageLoaded(true)}
              />
            </div>

            <div className="p-6 bg-white">
              <h3 className="text-2xl font-bold text-gray-900 mb-3">
                {certificate.title}
              </h3>

              <div className="flex flex-wrap gap-4 mb-4">
                <div className="flex items-center text-gray-600">
                  <Building className="w-5 h-5 mr-2 text-gray-500" />
                  <span>
                    Issued by:{" "}
                    <span className="font-medium">{certificate.issuer}</span>
                  </span>
                </div>

                {/* <div className="flex items-center text-gray-600">
                  <Calendar className="w-5 h-5 mr-2 text-gray-500" />
                  <span>
                    Date: <span className="font-medium">{formattedDate}</span>
                  </span>
                </div> */}
              </div>
            </div>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
