'use client';

import { useState } from 'react';
import UniversityCountryatom from '../atoms/UniversityCountryatom';
import Pagination from '../../admin/components/Pagination';
import ModernCard from '../../components/shared/ModernCard';
import { Search, Map } from 'lucide-react';

const COUNTRIES_PER_PAGE = 12;

interface CountryData {
  id: number;
  name: string;
  flag: string;
  banner?: string;
  continent: string;
  actual: string;
  discounted: string | null;
  discount: string | null;
  slug: string;
  visaTypes: string[];
  link: string;
  popularity: number;
}

interface AllVisaDestinationProps {
  allCountries: CountryData[];
}

const AllVisaDestination = ({ allCountries }: AllVisaDestinationProps) => {
  // Initialize states without URL params
  const [currentPage, setCurrentPage] = useState(1);
  const [searchTerm, setSearchTerm] = useState('');
  const [filter, setFilter] = useState('all');

  // Filter countries based on search term and filter
  const filteredCountries = allCountries.filter(country => {
    const matchesSearch = searchTerm.trim() === '' || 
      country.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (country.continent && country.continent.toLowerCase().includes(searchTerm.toLowerCase()));

    const matchesFilter = 
      filter === 'all' ||
      (filter === 'popular' && country.popularity > 70) ||
      (filter === 'discount' && country.discount);

    return matchesSearch && matchesFilter;
  });

  // Calculate pagination for filtered results
  const totalPages = Math.ceil(filteredCountries.length / COUNTRIES_PER_PAGE);
  const totalItems = filteredCountries.length;
  
  // Get current page data
  const startIndex = (currentPage - 1) * COUNTRIES_PER_PAGE;
  const endIndex = startIndex + COUNTRIES_PER_PAGE;
  const currentPageCountries = filteredCountries.slice(startIndex, endIndex);

  const handlePageChange = (newPage: number) => {
    if (newPage >= 1 && newPage <= totalPages) {
      setCurrentPage(newPage);
      // Removed URL update - silent action
    }
  };

  const handleSearch = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1); // Reset to first page when searching
    // Removed URL update - silent action
  };

  const handleFilterChange = (newFilter: string) => {
    setFilter(newFilter);
    setCurrentPage(1); // Reset to first page when filtering
    // Removed URL update - silent action
  };

  const clearFilters = () => {
    setSearchTerm('');
    setFilter('all');
    setCurrentPage(1);
    // Removed URL update - silent action
  };

  const handleSubmitSearch = (e: React.FormEvent) => {
    e.preventDefault(); // Prevent form submission/page reload
  };

  const isFilterActive = searchTerm.trim() !== '' || filter !== 'all';

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header Section with new design */}
      <div className="text-center mb-12">
        <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-6 animate-pulse">
          <Map className="w-5 h-5" />
          Global Visa Destinations
        </div>

        <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
          Explore{' '}
          <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
            Visa Destinations
          </span>
        </h1>
        <p className="text-xl text-gray-600 max-w-3xl mx-auto">
          Discover {allCountries.length}+ countries with our expert visa processing services. Fast, reliable, and affordable.
        </p>
      </div>

      {/* Search and Filter Section - New Design */}
      <ModernCard className="p-6 mb-8">
        <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
          <div className="flex-1 w-full">
            <form onSubmit={handleSubmitSearch} className="relative">
              <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <input
                type="text"
                placeholder="Search destinations by country or continent..."
                value={searchTerm}
                onChange={(e) => handleSearch(e.target.value)}
                className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50"
              />
            </form>
          </div>
          
          <div className="flex gap-3 flex-wrap justify-center">
            <button
              onClick={() => handleFilterChange('all')}
              className={`px-4 py-2 rounded-lg transition-all ${
                filter === 'all' 
                  ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              All Countries
            </button>
            <button
              onClick={() => handleFilterChange('popular')}
              className={`px-4 py-2 rounded-lg transition-all ${
                filter === 'popular' 
                  ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              Popular
            </button>
            <button
              onClick={() => handleFilterChange('discount')}
              className={`px-4 py-2 rounded-lg transition-all ${
                filter === 'discount' 
                  ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              Special Offers
            </button>
          </div>
        </div>
        
        <div className="flex items-center justify-between mt-4 text-sm text-gray-600">
          <span>
            Showing {Math.min(endIndex, totalItems)} of {totalItems} destinations
            {isFilterActive && ` (filtered from ${allCountries.length} total)`}
          </span>
          {isFilterActive && (
            <button 
              onClick={clearFilters}
              className="text-teal-600 hover:text-teal-700 font-medium hover:underline"
            >
              Clear all filters
            </button>
          )}
        </div>
      </ModernCard>

      {currentPageCountries.length === 0 ? (
        <ModernCard className="py-16 text-center">
          <div className="flex flex-col items-center justify-center">
            <div className="w-16 h-16 rounded-full bg-linear-to-r from-teal-50 to-blue-50 flex items-center justify-center mb-4">
              <Map className="w-8 h-8 text-teal-600" />
            </div>
            <p className="text-gray-500 text-lg mb-4">
              {isFilterActive 
                ? 'No destinations match your search criteria' 
                : 'No visa destinations available'
              }
            </p>
            {isFilterActive && (
              <button 
                onClick={clearFilters}
                className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-2 rounded-lg hover:opacity-90 transition-opacity"
              >
                View all destinations
              </button>
            )}
          </div>
        </ModernCard>
      ) : (
        <>
          <UniversityCountryatom 
            heading="" 
            data={currentPageCountries} 
          />

          {/* Pagination */}
          {(totalPages > 1) && (
            <div className="mt-12">
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                onPageChange={handlePageChange}
                totalItems={totalItems}
                startIndex={startIndex}
                endIndex={Math.min(endIndex, totalItems)}
              />
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default AllVisaDestination;