'use client';

import { useState, useEffect, useCallback, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { Search, Clock, ChevronRight, Loader2, XCircle } from 'lucide-react';
import { CITY, POPULAR_SEARCHES } from '@/lib/constants';

interface Article {
  id: number;
  slug: string;
  title: string;
  summary: string;
  category: string;
  imageUrl: string | null;
  publishedAt: string;
}

function SearchContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const initialQuery = searchParams.get('q') || '';

  const [query, setQuery] = useState(initialQuery);
  const [articles, setArticles] = useState<Article[]>([]);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [searched, setSearched] = useState(false);

  const handleSearch = useCallback(async (searchQuery: string) => {
    if (!searchQuery.trim() || searchQuery.length < 2) {
      setArticles([]);
      setTotal(0);
      return;
    }

    setIsLoading(true);
    setSearched(true);

    try {
      const res = await fetch(`/api/search?q=${encodeURIComponent(searchQuery)}&limit=30`);
      const data = await res.json();
      setArticles(data.articles || []);
      setTotal(data.total || 0);
    } catch (error) {
      console.error('Arama hatası:', error);
    } finally {
      setIsLoading(false);
    }
  }, []);

  // URL'den gelen query ile arama yap
  useEffect(() => {
    if (initialQuery) {
      handleSearch(initialQuery);
    }
  }, [initialQuery, handleSearch]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (query.trim().length >= 2) {
      router.push(`/ara?q=${encodeURIComponent(query)}`);
      handleSearch(query);
    }
  };

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString('tr-TR', {
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    });
  };

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      {/* Arama Başlığı */}
      <div className="text-center mb-8">
        <h1 className="text-3xl font-black text-gray-900 mb-2">Haber Ara</h1>
        <p className="text-gray-500">{CITY.name} ve çevresinden binlerce haber içinde arayın</p>
      </div>

      {/* Arama Formu */}
      <form onSubmit={handleSubmit} className="mb-8">
        <div className="relative">
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Haber, konu veya anahtar kelime ara..."
            className="w-full px-6 py-4 pr-14 text-lg bg-white border-2 border-gray-200 rounded-2xl focus:outline-none focus:border-red-500 focus:ring-4 focus:ring-red-100 transition-all"
            minLength={2}
          />
          <button
            type="submit"
            disabled={query.length < 2}
            className="absolute right-2 top-1/2 -translate-y-1/2 w-12 h-12 bg-red-600 text-white rounded-xl flex items-center justify-center hover:bg-red-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed"
          >
            {isLoading ? (
              <Loader2 size={20} className="animate-spin" />
            ) : (
              <Search size={20} />
            )}
          </button>
        </div>
        {query.length > 0 && query.length < 2 && (
          <p className="text-sm text-orange-500 mt-2">En az 2 karakter girin</p>
        )}
      </form>

      {/* Sonuçlar */}
      {searched && (
        <div className="mb-6">
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 size={40} className="animate-spin text-red-600" />
            </div>
          ) : articles.length > 0 ? (
            <>
              <div className="flex items-center justify-between mb-4">
                <p className="text-gray-600">
                  <span className="font-bold text-gray-900">&quot;{initialQuery}&quot;</span> için{' '}
                  <span className="font-bold text-red-600">{total}</span> sonuç bulundu
                </p>
              </div>

              <div className="space-y-4">
                {articles.map((article) => (
                  <Link
                    key={article.id}
                    href={`/haber/${article.slug}`}
                    className="flex gap-4 p-4 bg-white rounded-2xl border border-gray-100 hover:border-red-200 hover:shadow-lg transition-all group"
                  >
                    {/* Görsel */}
                    <div className="relative w-32 h-24 md:w-40 md:h-28 flex-shrink-0 rounded-xl overflow-hidden">
                      <Image
                        src={article.imageUrl || '/images/placeholder.jpg'}
                        alt={article.title}
                        fill
                        className="object-cover group-hover:scale-105 transition-transform"
                      />
                    </div>

                    {/* İçerik */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2">
                        <span className="text-[10px] font-bold bg-red-100 text-red-600 px-2 py-1 rounded-full uppercase">
                          {article.category}
                        </span>
                        <span className="text-xs text-gray-400 flex items-center gap-1">
                          <Clock size={12} />
                          {formatDate(article.publishedAt)}
                        </span>
                      </div>
                      <h2 className="font-bold text-gray-900 group-hover:text-red-600 transition-colors line-clamp-2 mb-1">
                        {article.title}
                      </h2>
                      <p className="text-sm text-gray-500 line-clamp-2 hidden md:block">
                        {article.summary}
                      </p>
                    </div>

                    <ChevronRight size={20} className="text-gray-300 group-hover:text-red-600 self-center flex-shrink-0" />
                  </Link>
                ))}
              </div>
            </>
          ) : (
            <div className="text-center py-12">
              <XCircle size={60} className="mx-auto text-gray-300 mb-4" />
              <h3 className="text-xl font-bold text-gray-900 mb-2">Sonuç Bulunamadı</h3>
              <p className="text-gray-500 mb-4">
                &quot;{initialQuery}&quot; için herhangi bir haber bulunamadı.
              </p>
              <p className="text-sm text-gray-400">
                Farklı anahtar kelimeler deneyebilir veya daha genel terimler kullanabilirsiniz.
              </p>
            </div>
          )}
        </div>
      )}

      {/* Popüler Aramalar */}
      {!searched && (
        <div className="bg-gray-50 rounded-2xl p-6">
          <h3 className="font-bold text-gray-900 mb-4">Popüler Aramalar</h3>
          <div className="flex flex-wrap gap-2">
            {POPULAR_SEARCHES.map((term) => (
              <button
                key={term}
                onClick={() => {
                  setQuery(term);
                  router.push(`/ara?q=${encodeURIComponent(term)}`);
                  handleSearch(term);
                }}
                className="px-4 py-2 bg-white border border-gray-200 rounded-full text-sm font-medium text-gray-600 hover:border-red-300 hover:text-red-600 transition-colors"
              >
                {term}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function SearchLoading() {
  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <div className="text-center mb-8">
        <div className="h-10 w-48 bg-gray-200 rounded-lg mx-auto mb-2 animate-pulse" />
        <div className="h-5 w-72 bg-gray-100 rounded mx-auto animate-pulse" />
      </div>
      <div className="h-16 bg-gray-100 rounded-2xl animate-pulse mb-8" />
      <div className="flex items-center justify-center py-12">
        <Loader2 size={40} className="animate-spin text-red-600" />
      </div>
    </div>
  );
}

export default function SearchPage() {
  return (
    <Suspense fallback={<SearchLoading />}>
      <SearchContent />
    </Suspense>
  );
}
