'use client';
import React, { useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay } from 'swiper/modules';
import Heading from '../atoms/Heading';
import Link from 'next/link';
import 'swiper/css';
import Image from 'next/image';

function slugify(str) {
  return str
    .toLowerCase()
    .replace(/\s*\([^)]*\)/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .replace(/-+/g, '-');
}

const UniversityCountryatom = ({
  data = [],
  heading = 'Discover Universities by Country',
  viewType = 'grid',
  columns = 4,
  limit = 0,
  imageSize = { width: 60, height: 40 },
  cardPadding = 'px-6 py-4',
  cardRounded = 'rounded-xl',
  imageRounded = 'rounded-lg',
  showDiscountBadge = false,
  showBottomSpace = true,
  customBottomSpaceClass = '',
  linkType = 'visit-visa-detail',
  autoplay = false,
}) => {
  const [selectedContinent, setSelectedContinent] = useState("All");
  const [searchQuery, setSearchQuery] = useState("");

  // Define grid columns mapping
  const gridCols = {
    1: 'grid-cols-1',
    2: 'lg:grid-cols-2',
    3: 'lg:grid-cols-3',
    4: 'lg:grid-cols-4',
    5: 'lg:grid-cols-5',
  }[columns] || 'lg:grid-cols-4';

  // Get unique continents from data
  const availableContinents = Array.from(
    new Set(data.map(item => item.continent))
  ).filter(Boolean);

  // Add "All" option with count
  const continentOptions = [
    { 
      name: "All", 
      count: data.length
    },
    ...availableContinents.map(continent => ({
      name: continent,
      count: data.filter(item => item.continent === continent).length
    }))
  ];

  // Filter data by continent and search
  const filteredData = (selectedContinent === 'All' 
    ? data 
    : data.filter(item => item.continent === selectedContinent))
    .filter(item => 
      item.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.continent?.toLowerCase().includes(searchQuery.toLowerCase())
    );

  const limitedData = limit > 0 ? filteredData.slice(0, limit) : filteredData;
  const bottomSpaceClass = showBottomSpace
    ? customBottomSpaceClass || 'mb-16'
    : '';

  const renderUniversityCard = (university, index) => {

    console.log(university);

    const universityName = university.name
      ? university.name.replace(/\s*\([^)]*\)/, '').trim()
      : '';
    const slug = slugify(universityName) + '-visit-visa';
    const cleanName = universityName.replace(/\s*\([^)]*\)/, '').trim();
    const searchUrl = `/search?type=university&country=${encodeURIComponent(cleanName)}`;

    return (
      <Link
        key={index}
        href={linkType === 'search' ? searchUrl : `/visit-visa-detail/${slug}`}
        className="block"
      >
        <div
  className={`${cardRounded} shadow-lg bg-white ${cardPadding} transition-all duration-300 cursor-pointer flex items-center gap-4 border border-gray-100 group hover:shadow-2xl hover:scale-105 hover:border-transparent relative overflow-hidden`}
>
  {/* Gradient Border Effect */}
  <div className="absolute inset-0 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] opacity-0 group-hover:opacity-5 transition-opacity duration-300"></div>
  
  {/* University/Country Image/Logo */}
  <div className={`relative ${imageRounded} overflow-hidden flex-shrink-0`}>
    {university.flag ? (
      <div className="w-14 h-14 rounded-lg overflow-hidden bg-gray-200">
        <img 
          src={university.flag.startsWith('/') 
            ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com${university.flag}`
            : `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${university.flag}`
          }
          alt={university.name}
          className="w-full h-full object-cover"
          onError={(e) => {
            // Fallback to gradient background if image fails to load
            e.target.style.display = 'none';
            e.target.nextSibling.style.display = 'flex';
          }}
        />
        {/* Fallback gradient background */}
        <div className="w-14 h-14 bg-gradient-to-br from-[#0B6F78] to-[#0a306b] rounded-lg flex items-center justify-center hidden">
          <span className="text-white font-bold text-lg">
            {university.name?.charAt(0).toUpperCase() || 'U'}
          </span>
        </div>
      </div>
    ) : (
      // Default gradient background when no image
      <div className="w-14 h-14 bg-gradient-to-br from-[#0B6F78] to-[#0a306b] rounded-lg flex items-center justify-center">
        <span className="text-white font-bold text-lg">
          {university.name?.charAt(0).toUpperCase() || 'U'}
        </span>
      </div>
    )}
  </div>

  {/* University Info */}
  <div className="flex-1 min-w-0">
    <h4 className="text-lg font-bold text-gray-900 group-hover:text-[#0B6F78] transition-colors duration-300 mb-1">
      {university.name}
    </h4>
    {university.continent && (
      <p className="text-sm text-gray-600 flex items-center gap-1">
        <span className="w-2 h-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-full"></span>
        {university.continent}
      </p>
    )}
  </div>

  {/* Arrow Icon */}
  <div className="text-[#0B6F78] group-hover:text-[#0a306b] transition-colors duration-300">
    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
    </svg>
  </div>
</div>
      </Link>
    );
  };

  return (
    <div className="py-12 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
      {/* Header Section */}
      <div className="text-center max-w-4xl mx-auto mb-12">
        <div className="inline-flex items-center gap-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white px-6 py-2 rounded-full text-sm font-medium mb-6">
          <span>🌍</span>
          <span>List Of Visa Contries</span>
        </div>
 
      </div>

      {/* Content Section */}
      <div className="relative">
        {/* Background Pattern */}
        <div className="absolute inset-0 opacity-5 bg-gradient-to-br from-[#0B6F78] to-[#0a306b] rounded-3xl"></div>
        
        {viewType === 'swiper' ? (
          <Swiper
            modules={[Autoplay]}
            spaceBetween={30}
            slidesPerView={2}
            breakpoints={{
              640: { slidesPerView: 2 },
              768: { slidesPerView: 3 },
              1024: { slidesPerView: columns > 4 ? columns : 4 },
            }}
            autoplay={autoplay ? { delay: 2500 } : false}
            className="py-6"
          >
            {limitedData.map((university, index) => (
              <SwiperSlide key={index} className="!h-auto py-4">
                {renderUniversityCard(university, index)}
              </SwiperSlide>
            ))}
          </Swiper>
        ) : (
          <div className={`grid ${gridCols} sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:${gridCols} gap-8 relative z-10`}>
            {limitedData.map((university, index) => (
              <React.Fragment key={index}>
                {renderUniversityCard(university, index)}
              </React.Fragment>
            ))}
          </div>
        )}

        {/* Empty State */}
        {limitedData.length === 0 && (
          <div className="text-center py-16 relative z-10">
            <div className="w-24 h-24 mx-auto mb-6 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-full flex items-center justify-center">
              <svg className="w-12 h-12 text-white" 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.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div className="text-2xl font-bold text-gray-700 mb-2">No universities found</div>
            <p className="text-gray-500 text-lg max-w-md mx-auto">
              {searchQuery || selectedContinent !== 'All' 
                ? "Try adjusting your search or filter criteria" 
                : "Universities will appear here once they are added to the system."}
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default UniversityCountryatom;