'use client';

import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Search, Menu, X, Bell, MapPin, ChevronDown, Loader2 } from 'lucide-react';
import { CATEGORIES } from '@/lib/constants';
import { VAN_DISTRICTS, getCenterDistricts, getOtherDistricts } from '@/lib/districts';

// Türkçe karakterleri SEO uyumlu slug'a çevir
function toSlug(text: string): string {
  const turkishMap: Record<string, string> = {
    'ç': 'c', 'Ç': 'c', 'ğ': 'g', 'Ğ': 'g', 'ı': 'i', 'İ': 'i',
    'ö': 'o', 'Ö': 'o', 'ş': 's', 'Ş': 's', 'ü': 'u', 'Ü': 'u'
  };
  let slug = text.toLowerCase();
  for (const [tr, en] of Object.entries(turkishMap)) {
    slug = slug.replace(new RegExp(tr, 'g'), en);
  }
  return slug;
}

export default function Header() {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isDistrictsOpen, setIsDistrictsOpen] = useState(false);
  const [isMobileDistrictsOpen, setIsMobileDistrictsOpen] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearching, setIsSearching] = useState(false);
  
  const pathname = usePathname();
  const router = useRouter();
  const dropdownRef = useRef<HTMLDivElement>(null);
  const searchRef = useRef<HTMLDivElement>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);

  const centerDistricts = getCenterDistricts();
  const otherDistricts = getOtherDistricts();

  // Dropdown dışına tıklanınca kapat
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDistrictsOpen(false);
      }
      if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
        setIsSearchOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Arama açıldığında input'a fokuslan
  useEffect(() => {
    if (isSearchOpen && searchInputRef.current) {
      searchInputRef.current.focus();
    }
  }, [isSearchOpen]);

  // ESC ile kapatma
  useEffect(() => {
    const handleEsc = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setIsSearchOpen(false);
        setIsDistrictsOpen(false);
      }
    };
    document.addEventListener('keydown', handleEsc);
    return () => document.removeEventListener('keydown', handleEsc);
  }, []);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim().length >= 2) {
      setIsSearching(true);
      router.push(`/ara?q=${encodeURIComponent(searchQuery.trim())}`);
      setIsSearchOpen(false);
      setSearchQuery('');
      setIsSearching(false);
    }
  };

  const isActive = (category: string) => {
    if (category === 'Tümü') return pathname === '/';
    return pathname === `/kategori/${toSlug(category)}`;
  };

  const isDistrictActive = () => pathname.startsWith('/ilce/');

  return (
    <>
      <header className="sticky top-0 z-50 bg-white shadow-sm border-b border-gray-200">
        {/* Top Bar - Sadece Desktop */}
        <div className="hidden md:flex items-center justify-between px-6 py-2 bg-gray-900 text-white text-xs">
          <div className="flex gap-4">
            <span>
              {new Date().toLocaleDateString('tr-TR', {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric',
              })}
            </span>
            <span className="border-l border-gray-700 pl-4">Van, 18°C / Güneşli</span>
          </div>
          <div className="flex gap-4 items-center">
            <Link href="/iletisim" className="hover:text-red-500 transition-colors">
              Bize Ulaşın
            </Link>
            <Link href="/kunye" className="hover:text-red-500 transition-colors">
              Künye
            </Link>
            <Link href="/reklam" className="hover:text-red-500 transition-colors font-bold">
              Reklam
            </Link>
          </div>
        </div>

        {/* Main Nav */}
        <div className="max-w-7xl mx-auto px-4 h-16 md:h-20 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <button
              className="lg:hidden p-2 hover:bg-gray-100 rounded-md"
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              aria-label="Menü"
            >
              {isMobileMenuOpen ? <X size={24} /> : <Menu size={24} />}
            </button>

            <Link href="/" className="flex flex-col group">
              <span className="text-xl md:text-3xl font-extrabold tracking-tighter text-red-600 group-hover:text-red-700">
                VAN<span className="text-gray-900">SONDAKİKA</span>
              </span>
              <span className="text-[8px] md:text-[10px] font-bold text-gray-500 uppercase tracking-widest mt-[-2px] md:mt-[-4px]">
                Şehrin En Hızlı Haber Portalı
              </span>
            </Link>
          </div>

          {/* Desktop Categories */}
          <nav className="hidden lg:flex items-center gap-5">
            <Link
              href="/"
              className={`text-sm font-semibold transition-colors relative py-1 ${
                pathname === '/' ? 'text-red-600' : 'text-gray-700 hover:text-red-600'
              }`}
            >
              Tümü
              {pathname === '/' && (
                <span className="absolute bottom-0 left-0 w-full h-0.5 bg-red-600" />
              )}
            </Link>

            {/* İlçeler Dropdown */}
            <div className="relative" ref={dropdownRef}>
              <button
                onClick={() => setIsDistrictsOpen(!isDistrictsOpen)}
                className={`flex items-center gap-1 text-sm font-semibold transition-colors py-1 ${
                  isDistrictActive() ? 'text-red-600' : 'text-gray-700 hover:text-red-600'
                }`}
              >
                <MapPin size={14} />
                İlçeler
                <ChevronDown size={14} className={`transition-transform ${isDistrictsOpen ? 'rotate-180' : ''}`} />
              </button>

              {isDistrictsOpen && (
                <div className="absolute top-full left-0 mt-2 w-[400px] bg-white rounded-xl shadow-2xl border border-gray-100 p-4 z-50 animate-fade-in">
                  <div className="grid grid-cols-2 gap-4">
                    {/* Merkez İlçeler */}
                    <div>
                      <h3 className="text-xs font-bold text-red-600 uppercase tracking-wider mb-2 pb-1 border-b border-red-100">
                        Merkez İlçeler
                      </h3>
                      <div className="space-y-1">
                        {centerDistricts.map((district) => (
                          <Link
                            key={district.id}
                            href={`/ilce/${district.slug}`}
                            onClick={() => setIsDistrictsOpen(false)}
                            className="flex items-center gap-2 p-2 rounded-lg hover:bg-red-50 transition-colors group"
                          >
                            <span className="w-6 h-6 bg-red-100 text-red-600 rounded-full flex items-center justify-center text-xs font-bold group-hover:bg-red-600 group-hover:text-white transition-colors">
                              {district.name.charAt(0)}
                            </span>
                            <span className="text-sm font-medium text-gray-700 group-hover:text-red-600">
                              {district.name}
                            </span>
                          </Link>
                        ))}
                      </div>
                    </div>

                    {/* Diğer İlçeler */}
                    <div>
                      <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-2 pb-1 border-b border-gray-100">
                        Diğer İlçeler
                      </h3>
                      <div className="space-y-1 max-h-[300px] overflow-y-auto">
                        {otherDistricts.map((district) => (
                          <Link
                            key={district.id}
                            href={`/ilce/${district.slug}`}
                            onClick={() => setIsDistrictsOpen(false)}
                            className="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-50 transition-colors group"
                          >
                            <span className="w-6 h-6 bg-gray-100 text-gray-600 rounded-full flex items-center justify-center text-xs font-bold group-hover:bg-gray-600 group-hover:text-white transition-colors">
                              {district.name.charAt(0)}
                            </span>
                            <span className="text-sm font-medium text-gray-600 group-hover:text-gray-900">
                              {district.name}
                            </span>
                          </Link>
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* Tüm İlçeler Linki */}
                  <Link
                    href="/ilceler"
                    onClick={() => setIsDistrictsOpen(false)}
                    className="block mt-4 pt-3 border-t border-gray-100 text-center text-sm font-semibold text-red-600 hover:text-red-700"
                  >
                    Tüm İlçeleri Gör →
                  </Link>
                </div>
              )}
            </div>

            {CATEGORIES.slice(0, 6).map((cat) => (
              <Link
                key={cat}
                href={`/kategori/${toSlug(cat)}`}
                className={`text-sm font-semibold transition-colors relative py-1 ${
                  isActive(cat) ? 'text-red-600' : 'text-gray-700 hover:text-red-600'
                }`}
              >
                {cat}
                {isActive(cat) && (
                  <span className="absolute bottom-0 left-0 w-full h-0.5 bg-red-600" />
                )}
              </Link>
            ))}
          </nav>

          {/* Desktop Right Side */}
          <div className="hidden md:flex items-center gap-2">
            <div className="relative" ref={searchRef}>
              <button 
                onClick={() => setIsSearchOpen(!isSearchOpen)}
                className={`p-2 rounded-full transition-colors ${isSearchOpen ? 'bg-red-100 text-red-600' : 'text-gray-600 hover:bg-gray-100'}`}
              >
                <Search size={20} />
              </button>

              {/* Arama Dropdown */}
              {isSearchOpen && (
                <div className="absolute right-0 top-full mt-2 w-80 bg-white rounded-xl shadow-2xl border border-gray-100 p-4 animate-fade-in">
                  <form onSubmit={handleSearch}>
                    <div className="relative">
                      <input
                        ref={searchInputRef}
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="Haber ara..."
                        className="w-full px-4 py-3 pr-12 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent"
                        minLength={2}
                      />
                      <button
                        type="submit"
                        disabled={searchQuery.length < 2 || isSearching}
                        className="absolute right-2 top-1/2 -translate-y-1/2 w-8 h-8 bg-red-600 text-white rounded-lg flex items-center justify-center hover:bg-red-700 transition-colors disabled:bg-gray-300"
                      >
                        {isSearching ? <Loader2 size={16} className="animate-spin" /> : <Search size={16} />}
                      </button>
                    </div>
                  </form>
                  <div className="mt-3 pt-3 border-t border-gray-100">
                    <p className="text-xs text-gray-400 mb-2">Popüler Aramalar</p>
                    <div className="flex flex-wrap gap-2">
                      {['Van', 'Vanspor', 'Deprem', 'Ekonomi'].map((term) => (
                        <button
                          key={term}
                          onClick={() => {
                            setSearchQuery(term);
                            router.push(`/ara?q=${encodeURIComponent(term)}`);
                            setIsSearchOpen(false);
                          }}
                          className="px-3 py-1 bg-gray-100 rounded-full text-xs font-medium text-gray-600 hover:bg-red-100 hover:text-red-600 transition-colors"
                        >
                          {term}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>
            <button className="p-2 text-gray-600 hover:bg-gray-100 rounded-full transition-colors">
              <Bell size={20} />
            </button>
          </div>

          {/* Mobile Right Side */}
          <div className="flex md:hidden items-center">
            <Link 
              href="/ara" 
              className="p-2 text-gray-600 hover:bg-gray-100 rounded-full transition-colors"
            >
              <Search size={20} />
            </Link>
          </div>
        </div>

        {/* Mobile Menu */}
        {isMobileMenuOpen && (
          <div className="lg:hidden bg-white border-t border-gray-100 shadow-xl animate-fade-in">
            {/* Mobil Arama */}
            <div className="p-4 border-b border-gray-100">
              <form onSubmit={handleSearch}>
                <div className="relative">
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Haber ara..."
                    className="w-full px-4 py-3 pr-12 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-red-500"
                    minLength={2}
                  />
                  <button
                    type="submit"
                    disabled={searchQuery.length < 2}
                    className="absolute right-2 top-1/2 -translate-y-1/2 w-8 h-8 bg-red-600 text-white rounded-lg flex items-center justify-center disabled:bg-gray-300"
                  >
                    <Search size={16} />
                  </button>
                </div>
              </form>
            </div>

            {/* İlçeler Accordion */}
            <div className="border-b border-gray-100">
              <button
                onClick={() => setIsMobileDistrictsOpen(!isMobileDistrictsOpen)}
                className="w-full flex items-center justify-between p-4 text-left"
              >
                <span className="flex items-center gap-2 font-semibold text-gray-800">
                  <MapPin size={18} className="text-red-600" />
                  İlçeler
                </span>
                <ChevronDown
                  size={18}
                  className={`text-gray-400 transition-transform ${isMobileDistrictsOpen ? 'rotate-180' : ''}`}
                />
              </button>

              {isMobileDistrictsOpen && (
                <div className="px-4 pb-4 grid grid-cols-3 gap-2">
                  {VAN_DISTRICTS.map((district) => (
                    <Link
                      key={district.id}
                      href={`/ilce/${district.slug}`}
                      onClick={() => {
                        setIsMobileMenuOpen(false);
                        setIsMobileDistrictsOpen(false);
                      }}
                      className={`p-2 text-center rounded-lg text-xs font-medium ${
                        district.isCenter
                          ? 'bg-red-50 text-red-600 hover:bg-red-100'
                          : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                      }`}
                    >
                      {district.name}
                    </Link>
                  ))}
                </div>
              )}
            </div>

            {/* Kategoriler */}
            <div className="p-4 grid grid-cols-2 gap-2">
              <Link
                href="/"
                onClick={() => setIsMobileMenuOpen(false)}
                className={`p-3 text-left rounded-lg text-sm font-medium ${
                  pathname === '/' ? 'bg-red-50 text-red-600' : 'hover:bg-gray-50'
                }`}
              >
                Tümü
              </Link>
              {CATEGORIES.map((cat) => (
                <Link
                  key={cat}
                  href={`/kategori/${toSlug(cat)}`}
                  onClick={() => setIsMobileMenuOpen(false)}
                  className={`p-3 text-left rounded-lg text-sm font-medium ${
                    isActive(cat) ? 'bg-red-50 text-red-600' : 'hover:bg-gray-50'
                  }`}
                >
                  {cat}
                </Link>
              ))}
            </div>
          </div>
        )}
      </header>
    </>
  );
}
