"use client";

import { useState, useEffect, useRef } from "react";
import { fetchCertificates } from "@/lib/api";
import type { Certificate } from "@/types";
import CertificateCard from "./certificate-card";
import CertificateModal from "./certificate-modal";
import { ChevronLeft, ChevronRight } from "lucide-react";
import CertificateCardSkeleton from "./certificate-card-skeleton";

import { motion } from "framer-motion";

export default function CertificateShowcase() {
  const [certificates, setCertificates] = useState<Certificate[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCertificate, setSelectedCertificate] =
    useState<Certificate | null>(null);
  const carouselRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    async function loadCertificates() {
      setLoading(true);
      const certs = await fetchCertificates();
      if (certs) {
        setCertificates(certs);
      }
      setLoading(false);
    }
    loadCertificates();
  }, []);

  const openCertificateModal = (certificate: Certificate) => {
    setSelectedCertificate(certificate);
    document.body.classList.add("overflow-hidden");
  };

  const closeCertificateModal = () => {
    setSelectedCertificate(null);
    document.body.classList.remove("overflow-hidden");
  };

  const scrollLeft = () => {
    if (carouselRef.current) {
      const scrollAmount = carouselRef.current.clientWidth * 0.8;
      carouselRef.current.scrollBy({
        left: -scrollAmount,
        behavior: "smooth",
      });
    }
  };

  const scrollRight = () => {
    if (carouselRef.current) {
      const scrollAmount = carouselRef.current.clientWidth * 0.8;
      carouselRef.current.scrollBy({
        left: scrollAmount,
        behavior: "smooth",
      });
    }
  };

  return (
    <div className="bg-white py-16 md:py-24">
      <div className="">
        <div className="relative mb-12">
          <div className="flex items-center justify-center">
            <div className="mb-6 md:mb-0">
              <motion.h2
                initial={{ y: 20, opacity: 0 }}
                whileInView={{ y: 0, opacity: 1 }}
                viewport={{ once: true }}
                className="text-4xl font-bold text-red-600 text-center mb-16"
              >
                Our Certifications & Achievements
              </motion.h2>
            </div>
          </div>
        </div>

        <div className="relative">
          <div className="absolute -left-4 top-1/2 -translate-y-1/2 z-10">
            <button
              onClick={scrollLeft}
              className="w-10 h-10 rounded-full bg-white shadow-lg flex items-center justify-center text-gray-700 hover:bg-red-50 hover:text-red-600 transition-colors focus:outline-none"
              aria-label="Scroll left"
            >
              <ChevronLeft className="w-5 h-5" />
            </button>
          </div>

          <div className="absolute -right-4 top-1/2 -translate-y-1/2 z-10">
            <button
              onClick={scrollRight}
              className="w-10 h-10 rounded-full bg-white shadow-lg flex items-center justify-center text-gray-700 hover:bg-red-50 hover:text-red-600 transition-colors focus:outline-none"
              aria-label="Scroll right"
            >
              <ChevronRight className="w-5 h-5" />
            </button>
          </div>

          <div
            ref={carouselRef}
            className="overflow-x-auto hide-scrollbar"
            style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}
          >
            <div className="flex space-x-6">
              {loading ? (
                // Loading skeletons
                Array.from({ length: 4 }).map((_, index) => (
                  <div key={index} className="flex-shrink-0 w-[280px]">
                    <CertificateCardSkeleton />
                  </div>
                ))
              ) : certificates.length === 0 ? (
                <div className="w-full text-center py-12 bg-gray-50 rounded-lg">
                  <div className="w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center mx-auto mb-4">
                    <svg
                      className="w-8 h-8 text-gray-400"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="2"
                        d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M12 20a8 8 0 100-16 8 8 0 000 16z"
                      />
                    </svg>
                  </div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">
                    No Certificates Found
                  </h3>
                  <p className="text-gray-500">
                    No certificates are available at this time.
                  </p>
                </div>
              ) : (
                certificates.map((certificate) => (
                  <div key={certificate.id} className="flex-shrink-0 w-[280px]">
                    <CertificateCard
                      certificate={certificate}
                      onClick={() => openCertificateModal(certificate)}
                    />
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>

      {selectedCertificate && (
        <CertificateModal
          certificate={selectedCertificate}
          onClose={closeCertificateModal}
          certificates={certificates}
          onNavigate={setSelectedCertificate}
        />
      )}

      <style jsx global>{`
        /* Hide scrollbar for Chrome, Safari and Opera */
        .hide-scrollbar::-webkit-scrollbar {
          display: none;
        }

        /* Hide scrollbar for IE, Edge and Firefox */
        .hide-scrollbar {
          -ms-overflow-style: none; /* IE and Edge */
          scrollbar-width: none; /* Firefox */
        }
      `}</style>
    </div>
  );
}
