import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { MapPin, Users, Ruler, Mountain, Landmark, ArrowRight, Newspaper } from 'lucide-react';
import { getDistrictBySlug, VAN_DISTRICTS, District } from '@/lib/districts';
import prisma from '@/lib/db';
import { SITE_CONFIG } from '@/lib/constants';

export const dynamic = 'force-dynamic';
export const revalidate = 0;

// Metadata
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const district = getDistrictBySlug(slug);

  if (!district) {
    return { title: 'İlçe Bulunamadı | Van Son Dakika' };
  }

  return {
    title: `${district.name} Haberleri | Van Son Dakika`,
    description: `${district.name} ilçesinden son dakika haberleri, yerel gelişmeler ve gündem. ${district.description.substring(0, 100)}`,
    openGraph: {
      title: `${district.name} - Van İlçe Haberleri`,
      description: district.description,
      images: [{ url: district.image }],
    },
  };
}

// İlçe haberlerini getir
async function getDistrictNews(districtSlug: string, districtName: string) {
  try {
    // Önce district alanından, sonra içerikten ara
    const articles = await prisma.article.findMany({
      where: {
        isPublished: true,
        OR: [
          { district: districtSlug }, // Direkt ilçe alanından
          { title: { contains: districtName } },
          { content: { contains: districtName } },
        ],
      },
      orderBy: { publishedAt: 'desc' },
      take: 10,
      select: {
        id: true,
        title: true,
        slug: true,
        summary: true,
        imageUrl: true,
        category: true,
        publishedAt: true,
      },
    });
    return articles;
  } catch {
    return [];
  }
}

// İlçe kartı komponenti
function DistrictInfoCard({ district }: { district: District }) {
  return (
    <div className="bg-gradient-to-br from-red-600 to-red-700 rounded-2xl p-6 text-white relative overflow-hidden">
      {/* Dekoratif arka plan */}
      <div className="absolute right-0 top-0 w-32 h-32 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2" />
      <div className="absolute left-0 bottom-0 w-24 h-24 bg-white/10 rounded-full translate-y-1/2 -translate-x-1/2" />

      <div className="relative z-10">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
            <MapPin size={24} />
          </div>
          <div>
            <h2 className="text-2xl font-black">{district.name}</h2>
            <p className="text-red-100 text-sm">Van İli - {district.isCenter ? 'Merkez İlçe' : 'İlçe'}</p>
          </div>
        </div>

        <p className="text-red-50 text-sm leading-relaxed mb-6">
          {district.description}
        </p>

        <div className="grid grid-cols-2 gap-4">
          <div className="bg-white/10 rounded-xl p-3">
            <div className="flex items-center gap-2 text-red-100 text-xs mb-1">
              <Users size={14} />
              Nüfus
            </div>
            <p className="text-xl font-bold">{district.population.toLocaleString('tr-TR')}</p>
          </div>
          <div className="bg-white/10 rounded-xl p-3">
            <div className="flex items-center gap-2 text-red-100 text-xs mb-1">
              <Ruler size={14} />
              Yüzölçümü
            </div>
            <p className="text-xl font-bold">{district.area.toLocaleString('tr-TR')} km²</p>
          </div>
        </div>
      </div>
    </div>
  );
}

// Özellikler kartı
function FeaturesCard({ district }: { district: District }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-100 p-6">
      <h3 className="flex items-center gap-2 font-bold text-gray-900 mb-4">
        <Mountain size={20} className="text-red-600" />
        Öne Çıkan Özellikler
      </h3>
      <div className="flex flex-wrap gap-2">
        {district.features.map((feature, i) => (
          <span
            key={i}
            className="px-3 py-1.5 bg-gray-100 text-gray-700 rounded-full text-sm font-medium"
          >
            {feature}
          </span>
        ))}
      </div>
    </div>
  );
}

// Gezilecek yerler kartı (detaylı)
function MustVisitCard({ district }: { district: District }) {
  return (
    <div className="bg-white rounded-2xl border border-gray-100 p-6">
      <h3 className="flex items-center gap-2 font-bold text-gray-900 mb-4">
        <Landmark size={20} className="text-red-600" />
        Mutlaka Görülmesi Gereken Yerler
      </h3>
      <div className="space-y-4">
        {district.mustVisit.map((place, i) => (
          <div key={i} className="border-l-4 border-red-500 pl-4">
            <h4 className="font-semibold text-gray-900 mb-1">
              {i + 1}. {place.name}
            </h4>
            <p className="text-sm text-gray-600 leading-relaxed">
              {place.description}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}

// Haber kartı
function NewsCard({ article }: { article: { id: number; title: string; slug: string; summary: string | null; imageUrl: string | null; category: string; publishedAt: Date } }) {
  return (
    <Link
      href={`/haber/${article.slug}`}
      className="group flex gap-4 p-4 bg-white rounded-xl border border-gray-100 hover:border-red-200 hover:shadow-md transition-all"
    >
      {article.imageUrl && (
        <div className="relative w-24 h-24 flex-shrink-0 rounded-lg overflow-hidden bg-gray-100">
          <Image
            src={article.imageUrl}
            alt={article.title}
            fill
            className="object-cover group-hover:scale-105 transition-transform"
          />
        </div>
      )}
      <div className="flex-1 min-w-0">
        <span className="text-xs font-semibold text-red-600 uppercase">
          {article.category}
        </span>
        <h3 className="font-bold text-gray-900 group-hover:text-red-600 transition-colors line-clamp-2 mt-1">
          {article.title}
        </h3>
        <p className="text-sm text-gray-500 mt-1">
          {new Date(article.publishedAt).toLocaleDateString('tr-TR', {
            day: 'numeric',
            month: 'long',
            year: 'numeric',
          })}
        </p>
      </div>
    </Link>
  );
}

// Diğer ilçeler kartı
function OtherDistrictsCard({ currentSlug }: { currentSlug: string }) {
  const otherDistricts = VAN_DISTRICTS.filter(d => d.slug !== currentSlug).slice(0, 6);

  return (
    <div className="bg-white rounded-2xl border border-gray-100 p-6">
      <h3 className="flex items-center gap-2 font-bold text-gray-900 mb-4">
        <MapPin size={20} className="text-red-600" />
        Diğer İlçeler
      </h3>
      <div className="grid grid-cols-2 gap-2">
        {otherDistricts.map((district) => (
          <Link
            key={district.id}
            href={`/ilce/${district.slug}`}
            className="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-50 transition-colors group"
          >
            <span className="w-8 h-8 bg-gray-100 text-gray-600 rounded-full flex items-center justify-center text-xs font-bold group-hover:bg-red-100 group-hover:text-red-600 transition-colors">
              {district.name.charAt(0)}
            </span>
            <span className="text-sm text-gray-600 group-hover:text-gray-900 truncate">
              {district.name}
            </span>
          </Link>
        ))}
      </div>
      <Link
        href="/ilceler"
        className="flex items-center justify-center gap-1 mt-4 pt-4 border-t border-gray-100 text-sm font-semibold text-red-600 hover:text-red-700"
      >
        Tüm İlçeler
        <ArrowRight size={16} />
      </Link>
    </div>
  );
}

export default async function DistrictPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const district = getDistrictBySlug(slug);

  if (!district) {
    notFound();
  }

  const news = await getDistrictNews(district.slug, district.name);

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Breadcrumb */}
      <nav className="flex items-center gap-2 text-sm text-gray-500 mb-6">
        <Link href="/" className="hover:text-red-600 transition-colors">
          Ana Sayfa
        </Link>
        <span>/</span>
        <Link href="/ilceler" className="hover:text-red-600 transition-colors">
          İlçeler
        </Link>
        <span>/</span>
        <span className="text-gray-900 font-medium">{district.name}</span>
      </nav>

      {/* Hero Image */}
      <div className="relative h-64 md:h-96 rounded-2xl overflow-hidden mb-8">
        <Image
          src={district.image}
          alt={district.name}
          fill
          className="object-cover"
          priority
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/30 to-transparent" />
        <div className="absolute bottom-0 left-0 right-0 p-6 md:p-8">
          <div className="flex items-center gap-2 text-red-400 text-sm font-semibold mb-2">
            <MapPin size={16} />
            VAN İLİ
          </div>
          <h1 className="text-3xl md:text-5xl font-black text-white mb-2">
            {district.name}
          </h1>
          <p className="text-gray-200 max-w-2xl">
            {district.isCenter ? 'Merkez İlçe' : 'İlçe'} • {district.population.toLocaleString('tr-TR')} nüfus • {district.area.toLocaleString('tr-TR')} km²
          </p>
        </div>
      </div>

      <div className="flex flex-col lg:flex-row gap-8">
        {/* Sol Kolon - Haberler */}
        <div className="lg:w-2/3">
          {/* Detaylı Açıklama */}
          <section className="mb-8 bg-white rounded-2xl border border-gray-100 p-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">
              {district.name} Hakkında
            </h2>
            <p className="text-gray-600 leading-relaxed">
              {district.detailedDescription}
            </p>
          </section>

          {/* İlçe Haberleri */}
          <section className="mb-8">
            <div className="flex items-center justify-between mb-6">
              <h2 className="flex items-center gap-2 text-xl font-bold text-gray-900">
                <Newspaper size={24} className="text-red-600" />
                {district.name} Haberleri
              </h2>
            </div>

            {news.length > 0 ? (
              <div className="space-y-4">
                {news.map((article) => (
                  <NewsCard key={article.id} article={article} />
                ))}
              </div>
            ) : (
              <div className="bg-gray-50 rounded-2xl p-8 text-center">
                <Newspaper size={48} className="mx-auto text-gray-300 mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  Henüz Haber Yok
                </h3>
                <p className="text-gray-500">
                  {district.name} ilçesinden henüz haber eklenmemiş. Yakında yeni haberler eklenecek.
                </p>
              </div>
            )}
          </section>
        </div>

        {/* Sağ Kolon - Bilgiler */}
        <aside className="lg:w-1/3 space-y-6">
          <DistrictInfoCard district={district} />
          <FeaturesCard district={district} />
          <MustVisitCard district={district} />
          <OtherDistrictsCard currentSlug={slug} />
        </aside>
      </div>
    </div>
  );
}
