'use client';

import { useState, useMemo, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { motion } from 'motion/react';
import Link from 'next/link';
import { MapPin, Clock, Search, ChevronLeft, ChevronRight, ChevronDown, DollarSign, Package, SearchX, Filter, Home } from 'lucide-react';
import { Container, Card } from '@/components/ui';
import { fetchCities } from '@/lib/cities/client';
import type { CityTariffRow } from '@/lib/cities/types';

const ITEMS_PER_PAGE = 10;

export default function TariffsPage() {
  const { t, i18n } = useTranslation();
  const [cities, setCities] = useState<CityTariffRow[]>([]);
  const [citiesError, setCitiesError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedDurations, setSelectedDurations] = useState<string[]>([]);
  const [priceRange, setPriceRange] = useState(30);
  const [pickupOnly, setPickupOnly] = useState(false);
  const [isDurationDropdownOpen, setIsDurationDropdownOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  const currentLang = i18n.language as 'en' | 'fr' | 'ar';
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let cancelled = false;
    fetchCities()
      .then((data) => {
        if (cancelled) return;
        setCities(data);
        setCitiesError(null);
        setPriceRange((prev) => {
          if (prev !== 30) return prev;
          const values = data
            .map((c) => c.priceValue)
            .filter((v): v is number => typeof v === 'number' && Number.isFinite(v));
          return Math.max(30, ...values);
        });
      })
      .catch((err: unknown) => {
        if (cancelled) return;
        setCitiesError(err instanceof Error ? err.message : 'Failed to load cities');
        setCities([]);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const durationOptions = useMemo(() => {
    const set = new Set<string>();
    for (const c of cities) {
      const d = String(c.duration ?? '').trim().toUpperCase();
      if (d) set.add(d);
    }
    const knownOrder = ['12H', '24H', '48H', '72H'];
    const sorted = Array.from(set).sort((a, b) => {
      const ia = knownOrder.indexOf(a);
      const ib = knownOrder.indexOf(b);
      if (ia !== -1 && ib !== -1) return ia - ib;
      if (ia !== -1) return -1;
      if (ib !== -1) return 1;
      return a.localeCompare(b);
    });
    return sorted.length ? sorted : ['24H', '48H', '72H'];
  }, [cities]);

  const maxPriceValue = useMemo(() => {
    const values = cities
      .map((c) => c.priceValue)
      .filter((v): v is number => typeof v === 'number' && Number.isFinite(v));
    return Math.max(30, ...values);
  }, [cities]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDurationDropdownOpen(false);
      }
    };

    if (isDurationDropdownOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isDurationDropdownOpen]);

  // Filter cities based on search and duration
  const filteredCities = useMemo(() => {
    return cities.filter(city => {
      const matchesSearch = city.name[currentLang].toLowerCase().includes(searchQuery.toLowerCase());

      if (!matchesSearch) return false;

      const duration = String(city.duration ?? '').trim().toUpperCase();
      const matchesDuration = selectedDurations.length === 0 || selectedDurations.includes(duration);
      if (!matchesDuration) return false;

      if (typeof city.priceValue === 'number' && Number.isFinite(city.priceValue) && city.priceValue > priceRange) {
        return false;
      }

      // Pickup filter
      if (pickupOnly && !city.pickup) return false;

      return true;
    });
  }, [cities, searchQuery, selectedDurations, priceRange, pickupOnly, currentLang]);

  // Pagination
  const totalPages = Math.ceil(filteredCities.length / ITEMS_PER_PAGE);
  const paginatedCities = filteredCities.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  const handleDurationToggle = (duration: string) => {
    setSelectedDurations((prev) => {
      const d = duration.toUpperCase();
      if (prev.includes(d)) return prev.filter((x) => x !== d);
      return [...prev, d];
    });
    setCurrentPage(1);
  };

  const handleSearchChange = (value: string) => {
    setSearchQuery(value);
    setCurrentPage(1);
  };

  return (
    <div className="pt-20">
      {/* Header Section */}
      <section className="relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-[#2d3875] via-[#3A4A9C] to-[#2d3875]" />
        <div className="absolute inset-0 bg-gradient-to-b from-black/10 via-transparent to-black/20" />
        <div className="absolute inset-0 opacity-[0.05]" style={{
          backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        }} />

        <Container className="relative z-10">
          <div className="py-12 pb-24">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.1 }}
              className="max-w-4xl mx-auto text-center"
            >
              <div className="inline-flex items-center gap-2 px-3 py-1.5 bg-white/10 backdrop-blur-xl rounded-full mb-6 border border-white/20">
                <span className="w-1.5 h-1.5 rounded-full bg-white animate-pulse"></span>
                <span className="text-sm font-semibold text-white">
                  {t('tariffs.badge', 'Tarification Transparente')}
                </span>
              </div>

              <h1 className="text-5xl md:text-6xl font-bold text-white mb-3 leading-tight">
                {t('tariffs.title', 'Tarifs de Livraison')}
              </h1>

              <motion.nav
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.4, delay: 0.15 }}
                className="mb-8 flex justify-center"
              >
                <ol className="flex items-center gap-2 text-sm">
                  <li className="flex items-center gap-2 group">
                    <Link
                      href="/"
                      className="flex items-center gap-1.5 text-white/80 hover:text-white transition-colors"
                    >
                      <Home className="w-4 h-4" />
                      <span className="font-medium">{t('breadcrumb.home', 'Accueil')}</span>
                    </Link>
                  </li>
                  <li className="text-white/50">
                    <ChevronRight className="w-4 h-4" />
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="text-white font-semibold">{t('tariffs.title', 'Tarifs de Livraison')}</span>
                  </li>
                </ol>
              </motion.nav>

              <p className="text-xl text-white/90 mb-10 leading-relaxed">
                {t('tariffs.subtitle', 'Tarification transparente pour toutes les villes du Maroc')}
              </p>
            </motion.div>
          </div>
        </Container>

        {/* Wave Transition */}
        <div className="absolute bottom-0 left-0 right-0 z-20 pointer-events-none">
          <svg viewBox="0 0 1440 120" fill="none" xmlns="http://www.w3.org/2000/svg" className="w-full h-auto" preserveAspectRatio="none">
            <path d="M0,64 C360,96 720,96 1080,64 C1260,48 1350,32 1440,32 L1440,120 L0,120 Z" className="fill-white" />
          </svg>
        </div>
      </section>

      {/* Pricing Table */}
      <section className="py-20 bg-gradient-to-b from-white to-gray-50/50">
        <Container>
	          <motion.div
	            initial={{ opacity: 0, y: 20 }}
	            animate={{ opacity: 1, y: 0 }}
	            transition={{ duration: 0.6, delay: 0.2 }}
	          >
	            {citiesError ? (
	              <div className="mb-4 px-4 py-3 rounded-lg border border-red-200 bg-red-50 text-red-700 text-sm">
	                {citiesError}
	              </div>
	            ) : null}

	            {/* Search and Filters Bar */}
	            <Card padding="lg" className="mb-6">
              <div className="flex flex-col lg:flex-row gap-4">
                {/* Search */}
                <div className="flex-1 min-w-0">
                  <label className="text-xs font-semibold text-gray-700 mb-2 block">
                    {t('tariffs.filters.search', 'Recherche')}
                  </label>
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="text"
                      placeholder={t('map.search', 'Rechercher une ville...')}
                      value={searchQuery}
                      onChange={(e) => handleSearchChange(e.target.value)}
                      className="w-full pl-10 pr-4 py-2.5 bg-gray-50 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#3A4A9C]/20 transition-all border border-gray-200"
                    />
                  </div>
                </div>

                {/* Delivery Time Multi-Select Dropdown */}
                <div className="w-full lg:w-56 relative" ref={dropdownRef}>
                  <label className="text-xs font-semibold text-gray-700 mb-2 block">
                    {t('tariffs.filters.deliveryTime', 'Délai de Livraison')}
                  </label>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() => setIsDurationDropdownOpen(!isDurationDropdownOpen)}
                      className="w-full px-4 py-2.5 bg-gray-50 rounded-lg text-sm text-left border border-gray-200 hover:border-gray-300 transition-all flex items-center justify-between"
                    >
                      <div className="flex items-center gap-2">
                        <Clock className="w-4 h-4 text-gray-400" />
                        <span className={selectedDurations.length === 0 ? 'text-gray-400' : 'text-gray-900'}>
                          {selectedDurations.length === 0
                            ? t('tariffs.filters.selectTime', 'Sélectionner...')
                            : selectedDurations.length === 1
                            ? selectedDurations[0].toUpperCase()
                            : `${selectedDurations.length} sélectionnés`}
                        </span>
                      </div>
                      <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${isDurationDropdownOpen ? 'rotate-180' : ''}`} />
                    </button>

                    {isDurationDropdownOpen && (
                      <div className="absolute top-full left-0 right-0 mt-1 bg-white rounded-lg shadow-lg border border-gray-200 z-50 py-1">
                        {durationOptions.map((duration) => {
                          const isChecked = selectedDurations.includes(duration);
                          return (
                            <label
                              key={duration}
                              className="flex items-center gap-3 px-4 py-2.5 hover:bg-gray-50 cursor-pointer transition-colors group"
                            >
                              <div className="relative flex items-center justify-center">
                                <input
                                  type="checkbox"
                                  checked={isChecked}
                                  onChange={() => handleDurationToggle(duration)}
                                  className="sr-only peer"
                                />
                                <div className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${
                                  isChecked
                                    ? 'bg-gray-900 border-gray-900'
                                    : 'bg-white border-gray-300 group-hover:border-gray-400'
                                }`}>
                                  {isChecked && (
                                    <svg className="w-3 h-3 text-white" viewBox="0 0 12 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                                      <path d="M1 5.5L4 8.5L11 1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                    </svg>
                                  )}
                                </div>
                              </div>
                              <span className="text-sm text-gray-900 font-mono font-medium select-none">
                                {duration}
                              </span>
                            </label>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>

                {/* Price Range Slider */}
                <div className="w-full lg:w-56">
                  <label className="text-xs font-semibold text-gray-700 mb-2 block flex items-center gap-2">
                    <DollarSign className="w-3.5 h-3.5 text-[#3A4A9C]" />
                    {t('tariffs.filters.maxPrice', 'Prix Maximum')}
                  </label>
                  <div className="space-y-2">
                    <input
                      type="range"
                      min="0"
                      max={maxPriceValue}
                      step="1"
                      value={priceRange}
                      onChange={(e) => {
                        setPriceRange(Number(e.target.value));
                        setCurrentPage(1);
                      }}
                      className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-[#3A4A9C]"
                      style={{
                        background: `linear-gradient(to right, #3A4A9C 0%, #3A4A9C ${maxPriceValue === 0 ? 0 : (priceRange / maxPriceValue) * 100}%, #e5e7eb ${maxPriceValue === 0 ? 0 : (priceRange / maxPriceValue) * 100}%, #e5e7eb 100%)`
                      }}
                    />
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-gray-500">0 DH</span>
                      <span className="px-2 py-1 bg-[#3A4A9C] text-white rounded font-medium font-mono">
                        {priceRange} DH
                      </span>
                      <span className="text-gray-500">{maxPriceValue} DH</span>
                    </div>
                  </div>
                </div>

                {/* Pickup Toggle */}
                <div className="w-full lg:w-56">
                  <label className="text-xs font-semibold text-gray-700 mb-2 block flex items-center gap-2">
                    <Package className="w-3.5 h-3.5 text-[#3A4A9C]" />
                    {t('tariffs.filters.pickupOnly', 'Ramassage Disponible')}
                  </label>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={pickupOnly}
                      onChange={(e) => {
                        setPickupOnly(e.target.checked);
                        setCurrentPage(1);
                      }}
                      className="sr-only peer"
                    />
                    <div className="w-14 h-8 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#3A4A9C]/20 rounded-full peer peer-checked:after:translate-x-6 after:content-[''] after:absolute after:top-1 after:left-1 after:bg-white after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-emerald-500 border border-gray-300 peer-checked:border-emerald-500"></div>
                    <span className="ml-3 text-sm font-medium text-gray-700">
                      {pickupOnly ? t('tariffs.filters.yes', 'Oui') : t('tariffs.filters.no', 'Non')}
                    </span>
                  </label>
                </div>
              </div>

              {/* Active Filters Summary */}
              {(selectedDurations.length > 0 || pickupOnly || priceRange < maxPriceValue) && (
                <div className="flex items-center gap-2 mt-4 pt-4 border-t border-gray-200">
                  <span className="text-xs font-semibold text-gray-600">
                    {t('tariffs.filters.activeFilters', 'Filtres actifs:')}
                  </span>
                  {selectedDurations.map((duration) => (
                    <span
                      key={duration}
                      className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-[#3A4A9C]/10 text-[#3A4A9C] text-xs font-medium rounded-md"
                    >
                      {duration.toUpperCase()}
                      <button
                        onClick={() => handleDurationToggle(duration)}
                        className="hover:bg-[#3A4A9C]/20 rounded"
                      >
                        ×
                      </button>
                    </span>
                  ))}
                  {priceRange < maxPriceValue && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-[#3A4A9C]/10 text-[#3A4A9C] text-xs font-medium rounded-md">
                      ≤ {priceRange} DH
                      <button onClick={() => setPriceRange(maxPriceValue)} className="hover:bg-[#3A4A9C]/20 rounded">×</button>
                    </span>
                  )}
                  {pickupOnly && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-emerald-500/10 text-emerald-600 text-xs font-medium rounded-md">
                      Ramassage
                      <button onClick={() => setPickupOnly(false)} className="hover:bg-emerald-500/20 rounded">×</button>
                    </span>
                  )}
                  <button
                    onClick={() => {
                      setSelectedDurations([]);
                      setPriceRange(maxPriceValue);
                      setPickupOnly(false);
                      setCurrentPage(1);
                    }}
                    className="ml-auto text-xs text-gray-500 hover:text-gray-700 font-medium"
                  >
                    {t('tariffs.filters.clearAll', 'Effacer tout')}
                  </button>
                </div>
              )}
            </Card>

            {/* Mobile Card Layout */}
            <div className="md:hidden space-y-4">
              {paginatedCities.length === 0 ? (
                <Card padding="lg">
                  <div className="text-center py-8">
                    <div className="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mb-4 mx-auto">
                      {searchQuery ? <SearchX className="w-10 h-10 text-gray-400" /> : <Filter className="w-10 h-10 text-[#3A4A9C]" />}
                    </div>
                    <h3 className="text-xl font-semibold text-gray-900 mb-2">
                      {searchQuery ? t('tariffs.emptyState.noSearchResults', 'Aucun résultat trouvé') : t('tariffs.emptyState.noFilterResults', 'Aucune ville ne correspond')}
                    </h3>
                    <p className="text-gray-600 mb-6 text-sm">
                      {searchQuery ? t('tariffs.emptyState.noSearchResultsDesc', 'Essayez une autre recherche.') : t('tariffs.emptyState.noFilterResultsDesc', 'Essayez d\'ajuster vos critères.')}
                    </p>
                    <button
	                      onClick={() => {
	                        setSearchQuery('');
	                        setSelectedDurations([]);
	                        setPriceRange(maxPriceValue);
	                        setPickupOnly(false);
	                        setCurrentPage(1);
	                      }}
                      className="px-4 py-2 bg-[#3A4A9C] text-white rounded-lg text-sm font-medium hover:bg-[#2d3a7a] transition-colors"
                    >
                      {t('tariffs.emptyState.clearFilters', 'Réinitialiser les filtres')}
                    </button>
                  </div>
                </Card>
              ) : (
                paginatedCities.map((city, index) => (
                  <motion.div
                    key={city.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.3, delay: 0.05 * index }}
                  >
                    <Card padding="lg" className="border border-gray-200/60 shadow-sm hover:shadow-md transition-shadow">
                      <div className="flex items-center gap-3 mb-4 pb-4 border-b border-gray-100">
                        <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-[#3A4A9C]/10 to-blue-50 border border-[#3A4A9C]/20 flex items-center justify-center flex-shrink-0">
                          <MapPin className="w-6 h-6 text-[#3A4A9C]" />
                        </div>
                        <div>
                          <h3 className="text-lg font-bold text-gray-900">{city.name[currentLang]}</h3>
                          <p className="text-xs text-gray-500">{t('tariffs.table.city', 'Ville')}</p>
                        </div>
                      </div>
                      <div className="space-y-3">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2 text-gray-600">
                            <Clock className="w-4 h-4 text-[#3A4A9C]" />
                            <span className="text-sm font-medium">{t('tariffs.table.deliveryTime', 'Délai de Livraison')}</span>
                          </div>
	                          <span className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 text-gray-700 text-sm font-semibold rounded-lg font-mono">
	                            <Clock className="w-3.5 h-3.5" />
	                            {String(city.duration ?? '—').toUpperCase()}
	                          </span>
	                        </div>
	                        <div className="flex items-center justify-between">
	                          <div className="flex items-center gap-2 text-gray-600">
	                            <DollarSign className="w-4 h-4 text-[#3A4A9C]" />
	                            <span className="text-sm font-medium">{t('tariffs.table.price', 'Prix')}</span>
	                          </div>
	                          {city.price ? (
	                            <span className="inline-flex px-3 py-1.5 bg-[#3A4A9C] text-white text-sm font-semibold rounded-full font-mono">
	                              {city.price}
	                            </span>
	                          ) : <span className="text-gray-400 text-sm">—</span>}
	                        </div>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2 text-gray-600">
                            <Package className="w-4 h-4 text-[#3A4A9C]" />
                            <span className="text-sm font-medium">{t('tariffs.table.pickup', 'Ramassage')}</span>
                          </div>
                          {city.pickup ? (
                            <span className="inline-flex px-3 py-1.5 bg-emerald-500 text-white text-sm font-semibold rounded-full">{t('map.pickup', 'Disponible')}</span>
                          ) : (
                            <span className="text-gray-400 text-sm">—</span>
                          )}
                        </div>
                      </div>
                    </Card>
                  </motion.div>
                ))
              )}
            </div>

            {/* Desktop Table */}
            <Card padding="none" className="hidden md:block border border-gray-200/60 shadow-sm overflow-hidden">
              <div className="overflow-x-auto no-scrollbar">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gradient-to-r from-gray-50 to-gray-100/50 border-b border-gray-200">
                      <th className="px-6 py-4 text-left">
                        <div className="flex items-center gap-2">
                          <MapPin className="w-4 h-4 text-[#3A4A9C]" />
                          <span className="font-semibold text-gray-900 text-sm">{t('tariffs.table.city', 'Ville')}</span>
                        </div>
                      </th>
                      <th className="px-6 py-4 text-left">
                        <div className="flex items-center gap-2">
                          <Clock className="w-4 h-4 text-[#3A4A9C]" />
                          <span className="font-semibold text-gray-900 text-sm">{t('tariffs.table.deliveryTime', 'Délai de Livraison')}</span>
                        </div>
                      </th>
                      <th className="px-6 py-4 text-left">
                        <div className="flex items-center gap-2">
                          <DollarSign className="w-4 h-4 text-[#3A4A9C]" />
                          <span className="font-semibold text-gray-900 text-sm">{t('tariffs.table.price', 'Prix')}</span>
                        </div>
                      </th>
                      <th className="px-6 py-4 text-left">
                        <div className="flex items-center gap-2">
                          <Package className="w-4 h-4 text-[#3A4A9C]" />
                          <span className="font-semibold text-gray-900 text-sm">{t('tariffs.table.pickup', 'Ramassage')}</span>
                        </div>
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {paginatedCities.length === 0 ? (
                      <tr>
                        <td colSpan={4} className="px-6 py-16">
                          <div className="text-center">
                            <div className="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mb-4 mx-auto">
                              {searchQuery ? <SearchX className="w-10 h-10 text-gray-400" /> : <Filter className="w-10 h-10 text-[#3A4A9C]" />}
                            </div>
                            <h3 className="text-xl font-semibold text-gray-900 mb-2">
                              {searchQuery ? t('tariffs.emptyState.noSearchResults', 'Aucun résultat trouvé') : t('tariffs.emptyState.noFilterResults', 'Aucune ville ne correspond')}
                            </h3>
                            <p className="text-gray-600 mb-6 text-sm">
                              {searchQuery ? t('tariffs.emptyState.noSearchResultsDesc', 'Essayez une autre recherche.') : t('tariffs.emptyState.noFilterResultsDesc', 'Essayez d\'ajuster vos critères.')}
                            </p>
                            <button
	                              onClick={() => {
	                                setSearchQuery('');
	                                setSelectedDurations([]);
	                                setPriceRange(maxPriceValue);
	                                setPickupOnly(false);
	                                setCurrentPage(1);
	                              }}
                              className="px-4 py-2 bg-[#3A4A9C] text-white rounded-lg text-sm font-medium hover:bg-[#2d3a7a] transition-colors"
                            >
                              {t('tariffs.emptyState.clearFilters', 'Réinitialiser les filtres')}
                            </button>
                          </div>
                        </td>
                      </tr>
                    ) : (
                      paginatedCities.map((city, index) => (
                        <motion.tr
                          key={city.id}
                          initial={{ opacity: 0, x: -20 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ duration: 0.3, delay: 0.03 * index }}
                          className="hover:bg-gray-50/50 transition-colors group"
                        >
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-3">
                              <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-[#3A4A9C]/10 to-blue-50 border border-[#3A4A9C]/20 flex items-center justify-center flex-shrink-0">
                                <MapPin className="w-5 h-5 text-[#3A4A9C]" />
                              </div>
                              <span className="font-semibold text-gray-900">{city.name[currentLang]}</span>
                            </div>
                          </td>
	                          <td className="px-6 py-4">
	                            <span className="inline-flex items-center gap-2 px-3 py-1.5 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg font-mono">
	                              <Clock className="w-3.5 h-3.5" />
	                              {String(city.duration ?? '—').toUpperCase()}
	                            </span>
	                          </td>
	                          <td className="px-6 py-4">
	                            {city.price ? (
	                              <span className="inline-flex px-3 py-1.5 bg-[#3A4A9C] text-white text-sm font-medium rounded-full font-mono">
	                                {city.price}
	                              </span>
	                            ) : (
	                              <span className="text-gray-400 text-sm">—</span>
	                            )}
	                          </td>
                          <td className="px-6 py-4">
                            {city.pickup ? (
                              <span className="inline-flex px-3 py-1.5 bg-emerald-500 text-white text-sm font-medium rounded-full">{t('map.pickup', 'Disponible')}</span>
                            ) : (
                              <span className="text-gray-400 text-sm">—</span>
                            )}
                          </td>
                        </motion.tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="px-6 py-4 bg-gray-50 border-t border-gray-200">
                  <div className="flex items-center justify-between">
                    <div className="text-sm text-gray-600">
                      <span className="font-medium text-gray-900">{(currentPage - 1) * ITEMS_PER_PAGE + 1}</span>
                      {' - '}
                      <span className="font-medium text-gray-900">{Math.min(currentPage * ITEMS_PER_PAGE, filteredCities.length)}</span>
                      {' sur '}
                      <span className="font-medium text-gray-900">{filteredCities.length}</span>
                      {' villes'}
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                        disabled={currentPage === 1}
                        className="w-9 h-9 rounded-lg flex items-center justify-center bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                      >
                        <ChevronLeft className="w-4 h-4" />
                      </button>
                      {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
                        let page;
                        if (totalPages <= 5) {
                          page = i + 1;
                        } else if (currentPage <= 3) {
                          page = i + 1;
                        } else if (currentPage >= totalPages - 2) {
                          page = totalPages - 4 + i;
                        } else {
                          page = currentPage - 2 + i;
                        }
                        return (
                          <button
                            key={page}
                            onClick={() => setCurrentPage(page)}
                            className={`w-9 h-9 rounded-lg text-sm font-medium transition-all ${
                              currentPage === page
                                ? 'bg-[#3A4A9C] text-white shadow-md'
                                : 'bg-white border border-gray-200 text-gray-700 hover:bg-gray-50'
                            }`}
                          >
                            {page}
                          </button>
                        );
                      })}
                      <button
                        onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                        disabled={currentPage === totalPages}
                        className="w-9 h-9 rounded-lg flex items-center justify-center bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                      >
                        <ChevronRight className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </Card>

            {/* Mobile Pagination */}
            {totalPages > 1 && (
              <Card padding="md" className="md:hidden border border-gray-200/60 mt-4">
                <div className="flex flex-col gap-4">
                  <div className="text-sm text-gray-600 text-center">
                    <span className="font-medium text-gray-900">{(currentPage - 1) * ITEMS_PER_PAGE + 1}</span>
                    {' - '}
                    <span className="font-medium text-gray-900">{Math.min(currentPage * ITEMS_PER_PAGE, filteredCities.length)}</span>
                    {' sur '}
                    <span className="font-medium text-gray-900">{filteredCities.length}</span>
                    {' villes'}
                  </div>
                  <div className="flex items-center justify-center gap-2">
                    <button
                      onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                      disabled={currentPage === 1}
                      className="w-10 h-10 rounded-lg flex items-center justify-center bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                    >
                      <ChevronLeft className="w-4 h-4" />
                    </button>
                    {Array.from({ length: Math.min(totalPages, 3) }, (_, i) => {
                      let page;
                      if (totalPages <= 3) {
                        page = i + 1;
                      } else if (currentPage === 1) {
                        page = i + 1;
                      } else if (currentPage === totalPages) {
                        page = totalPages - 2 + i;
                      } else {
                        page = currentPage - 1 + i;
                      }
                      return (
                        <button
                          key={page}
                          onClick={() => setCurrentPage(page)}
                          className={`w-10 h-10 rounded-lg text-sm font-medium transition-all ${
                            currentPage === page
                              ? 'bg-[#3A4A9C] text-white shadow-md'
                              : 'bg-white border border-gray-200 text-gray-700 hover:bg-gray-50'
                          }`}
                        >
                          {page}
                        </button>
                      );
                    })}
                    <button
                      onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                      disabled={currentPage === totalPages}
                      className="w-10 h-10 rounded-lg flex items-center justify-center bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                    >
                      <ChevronRight className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </Card>
            )}
          </motion.div>
        </Container>
      </section>
    </div>
  );
}
