'use client';

import { useState, useMemo, useEffect } from 'react';
import { Calendar, Tag, ExternalLink, ChevronLeft, ChevronRight } from 'lucide-react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter, usePathname } from 'next/navigation';
import { BlogPost } from '@/lib/blog';
import { SearchBar } from './SearchBar';
import { CategoryFilter } from './CategoryFilter';

const POSTS_PER_PAGE = 12;

// Placeholder image for posts without cover images
const PLACEHOLDER_IMAGE = 'data:image/svg+xml,' + encodeURIComponent(`
  <svg width="1792" height="1024" xmlns="http://www.w3.org/2000/svg">
    <rect width="100%" height="100%" fill="#181C14"/>
    <rect x="40%" y="35%" width="20%" height="30%" rx="8" fill="#697565" opacity="0.3"/>
    <circle cx="50%" cy="45%" r="8%" fill="#697565" opacity="0.2"/>
    <rect x="30%" y="65%" width="40%" height="4%" rx="2" fill="#465B50" opacity="0.3"/>
    <rect x="35%" y="72%" width="30%" height="3%" rx="2" fill="#465B50" opacity="0.2"/>
  </svg>
`);

// Known existing images (from public/images/posts/)
const EXISTING_IMAGES = new Set([
  '/images/posts/erp-integration-breuninger/cover.avif',
  '/images/posts/fullstack-development-timetracking/cover.avif',
  '/images/posts/rfid-automation/cover.avif',
  '/images/posts/automated-ad-creatives/cover.avif',
]);

function getFormattedDate(date: string, locale: string) {
  const languageMap: Record<string, string> = {
    de: 'de-DE',
    en: 'en-US',
    sr: 'sr-RS',
  };

  return new Date(date).toLocaleDateString(languageMap[locale] || 'de-DE', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}

function getImagePath(coverImage: string) {
  if (coverImage.startsWith('http')) {
    return coverImage;
  }
  return coverImage.replace('/blog/', '/images/posts/');
}

// Blog image component with fallback
function BlogImage({ src, alt, fallback }: { src: string; alt: string; fallback: string }) {
  const imageSrc = EXISTING_IMAGES.has(src) ? src : fallback;

  return (
    <Image
      src={imageSrc}
      alt={alt}
      fill
      sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
      className="object-cover transition-transform duration-700 group-hover:scale-110"
      unoptimized={imageSrc.startsWith('data:')}
    />
  );
}

function BlogPostCard({ post, locale }: { post: BlogPost; locale: string }) {
  return (
    <Link
      href={`/${locale}/blog/${post.slug}`}
      className="group relative block bg-background/50 backdrop-blur-sm
               rounded-xl shadow-lg hover:shadow-2xl
               ring-1 ring-border hover:ring-border
               transition-all duration-500 focus:outline-none focus:ring-2
               focus:ring-ring focus:ring-offset-2 focus:ring-offset-background
               transform hover:-translate-y-1"
    >
      <div className="relative overflow-hidden rounded-xl">
        {/* Image Container */}
        <div className="aspect-[16/9] w-full relative overflow-hidden bg-background">
          <BlogImage
            src={getImagePath(post.coverImage)}
            alt={post.title}
            fallback={PLACEHOLDER_IMAGE}
          />
          <div className="absolute inset-x-0 -bottom-20 top-0 bg-gradient-to-t from-background via-background/70 to-transparent opacity-95" />
        </div>

        {/* Content */}
        <div className="relative -mt-2 p-6 bg-background z-10">
          <div className="flex items-center gap-4 mb-4 text-muted-foreground">
            <div className="flex items-center gap-2 text-sm">
              <Calendar className="h-4 w-4" />
              <span>{getFormattedDate(post.date, locale)}</span>
            </div>
            {post.tags && post.tags.length > 0 && (
              <div className="flex items-center gap-2 text-sm">
                <Tag className="h-4 w-4" />
                <span>{post.tags.length} Tags</span>
              </div>
            )}
          </div>

          <h3 className="text-xl font-semibold text-foreground mb-3
                       group-hover:text-foreground/90 transition-colors duration-300">
            {post.title}
          </h3>
          <p className="text-muted-foreground text-sm line-clamp-2 mb-4
                      group-hover:text-foreground/80 transition-colors duration-300">
            {post.excerpt}
          </p>

          {/* Tags */}
          <div className="flex flex-wrap gap-2">
            {post.tags?.slice(0, 3).map((tag, index) => (
              <span
                key={index}
                className="px-3 py-1 bg-card/50
                         text-sm text-muted-foreground rounded-full
                         ring-1 ring-border/50 group-hover:ring-ring/50
                         group-hover:bg-card/70 group-hover:text-foreground/80
                         transition-all duration-300"
              >
                {tag}
              </span>
            ))}
            {post.tags && post.tags.length > 3 && (
              <span className="text-sm text-muted-foreground/60">
                +{post.tags.length - 3} more
              </span>
            )}
          </div>

          {/* Link Icon */}
          <div className="absolute top-6 right-6 p-2.5 rounded-full
                        bg-card/60 backdrop-blur-sm ring-1 ring-border/50
                        opacity-0 group-hover:opacity-100
                        transform translate-y-2 group-hover:translate-y-0
                        transition-all duration-300">
            <ExternalLink className="h-4 w-4 text-muted-foreground" />
          </div>
        </div>
      </div>
    </Link>
  );
}

// Pagination component
function Pagination({
  currentPage,
  totalPages,
  onPageChange,
  t,
}: {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  t: (key: string) => string;
}) {
  const getPageNumbers = () => {
    const pages: (number | 'ellipsis')[] = [];

    if (totalPages <= 7) {
      // Show all pages if 7 or fewer
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      // Always show first page
      pages.push(1);

      if (currentPage > 3) {
        pages.push('ellipsis');
      }

      // Show pages around current
      const start = Math.max(2, currentPage - 1);
      const end = Math.min(totalPages - 1, currentPage + 1);

      for (let i = start; i <= end; i++) {
        pages.push(i);
      }

      if (currentPage < totalPages - 2) {
        pages.push('ellipsis');
      }

      // Always show last page
      pages.push(totalPages);
    }

    return pages;
  };

  if (totalPages <= 1) return null;

  return (
    <nav className="flex items-center justify-center gap-2 mt-12 sm:mt-16" aria-label="Pagination">
      {/* Previous button */}
      {currentPage > 1 ? (
        <button
          onClick={() => onPageChange(currentPage - 1)}
          className="flex items-center gap-1 px-3 py-2 text-sm text-muted-foreground hover:text-foreground
                     bg-card/50 hover:bg-card rounded-lg ring-1 ring-border/50
                     hover:ring-ring transition-all duration-200"
          aria-label={t('ui.pagination.previous')}
        >
          <ChevronLeft className="h-4 w-4" />
          <span className="hidden sm:inline">{t('ui.pagination.previous')}</span>
        </button>
      ) : (
        <span
          className="flex items-center gap-1 px-3 py-2 text-sm text-muted-foreground/60
                     bg-card/30 rounded-lg ring-1 ring-border/50 cursor-not-allowed"
          aria-disabled="true"
        >
          <ChevronLeft className="h-4 w-4" />
          <span className="hidden sm:inline">{t('ui.pagination.previous')}</span>
        </span>
      )}

      {/* Page numbers */}
      <div className="flex items-center gap-1">
        {getPageNumbers().map((page, index) => {
          if (page === 'ellipsis') {
            return (
              <span key={`ellipsis-${index}`} className="px-2 text-muted-foreground/60">
                ...
              </span>
            );
          }

          const isCurrentPage = page === currentPage;

          return (
            <button
              key={page}
              onClick={() => onPageChange(page)}
              className={`min-w-[44px] h-11 flex items-center justify-center text-sm rounded-lg
                         ring-1 transition-all duration-200
                         ${isCurrentPage
                           ? 'bg-[#697565] text-foreground ring-[#697565] font-medium'
                           : 'text-muted-foreground hover:text-foreground bg-card/50 hover:bg-card ring-border/50 hover:ring-ring'
                         }`}
              aria-current={isCurrentPage ? 'page' : undefined}
            >
              {page}
            </button>
          );
        })}
      </div>

      {/* Next button */}
      {currentPage < totalPages ? (
        <button
          onClick={() => onPageChange(currentPage + 1)}
          className="flex items-center gap-1 px-3 py-2 text-sm text-muted-foreground hover:text-foreground
                     bg-card/50 hover:bg-card rounded-lg ring-1 ring-border/50
                     hover:ring-ring transition-all duration-200"
          aria-label={t('ui.pagination.next')}
        >
          <span className="hidden sm:inline">{t('ui.pagination.next')}</span>
          <ChevronRight className="h-4 w-4" />
        </button>
      ) : (
        <span
          className="flex items-center gap-1 px-3 py-2 text-sm text-muted-foreground/60
                     bg-card/30 rounded-lg ring-1 ring-border/50 cursor-not-allowed"
          aria-disabled="true"
        >
          <span className="hidden sm:inline">{t('ui.pagination.next')}</span>
          <ChevronRight className="h-4 w-4" />
        </span>
      )}
    </nav>
  );
}

interface BlogListProps {
  posts: BlogPost[];
  locale: string;
  initialSearch?: string;
  initialCategory?: string | null;
  translations: {
    searchPlaceholder: string;
    showingText: (start: number, end: number, total: number) => string;
    noPostsText: string;
    paginationPrevious: string;
    paginationNext: string;
  };
}

export function BlogList({ posts, locale, initialSearch = '', initialCategory = null, translations }: BlogListProps) {
  const router = useRouter();
  const pathname = usePathname();

  const [searchQuery, setSearchQuery] = useState(initialSearch);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(initialCategory);
  const [currentPage, setCurrentPage] = useState(1);

  // Update URL when filters change
  useEffect(() => {
    const params = new URLSearchParams();

    if (searchQuery.trim()) {
      params.set('search', searchQuery.trim());
    }

    if (selectedCategory) {
      params.set('category', selectedCategory);
    }

    const queryString = params.toString();
    const newUrl = queryString ? `${pathname}?${queryString}` : pathname;

    router.push(newUrl, { scroll: false });
  }, [searchQuery, selectedCategory, pathname, router]);

  // Extract unique categories from all posts
  const allCategories = useMemo(() => {
    const categories = new Set(
      posts.map(post => post.category).filter((c): c is string => Boolean(c))
    );
    return Array.from(categories).sort();
  }, [posts]);

  // Filter posts based on search query and category
  const filteredPosts = useMemo(() => {
    let filtered = posts;

    // Apply search filter (case-insensitive search in title, excerpt, and tags)
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(post => {
        const titleMatch = post.title.toLowerCase().includes(query);
        const excerptMatch = post.excerpt.toLowerCase().includes(query);
        const tagsMatch = post.tags?.some(tag => tag.toLowerCase().includes(query)) || false;
        return titleMatch || excerptMatch || tagsMatch;
      });
    }

    // Apply category filter
    if (selectedCategory) {
      filtered = filtered.filter(post => post.category === selectedCategory);
    }

    return filtered;
  }, [posts, searchQuery, selectedCategory]);

  // Reset to first page when filters change
  useMemo(() => {
    setCurrentPage(1);
  }, [searchQuery, selectedCategory]);

  // Paginate filtered posts
  const totalPages = Math.ceil(filteredPosts.length / POSTS_PER_PAGE);
  const validPage = Math.min(Math.max(1, currentPage), totalPages || 1);

  const startIndex = (validPage - 1) * POSTS_PER_PAGE;
  const endIndex = startIndex + POSTS_PER_PAGE;
  const paginatedPosts = filteredPosts.slice(startIndex, endIndex);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    // Scroll to top of the page
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div>
      {/* Search and Filter Section */}
      <div className="mb-8 sm:mb-12 space-y-6">
        {/* Search Bar */}
        <SearchBar
          value={searchQuery}
          onChange={setSearchQuery}
          placeholder={translations.searchPlaceholder}
        />

        {/* Category Filter */}
        <CategoryFilter
          categories={allCategories}
          selectedCategory={selectedCategory}
          onCategoryChange={setSelectedCategory}
        />
      </div>

      {/* Results count */}
      <p className="text-sm text-muted-foreground mb-6">
        {translations.showingText(
          startIndex + 1,
          Math.min(endIndex, filteredPosts.length),
          filteredPosts.length
        )}
      </p>

      {/* Blog Posts Grid */}
      {paginatedPosts.length > 0 ? (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 md:gap-8">
            {paginatedPosts.map((post) => (
              <BlogPostCard key={post.slug} post={post} locale={locale} />
            ))}
          </div>

          {/* Pagination */}
          <Pagination
            currentPage={validPage}
            totalPages={totalPages}
            onPageChange={handlePageChange}
            t={(key) => {
              if (key === 'ui.pagination.previous') return translations.paginationPrevious;
              if (key === 'ui.pagination.next') return translations.paginationNext;
              return '';
            }}
          />
        </>
      ) : (
        /* Empty State */
        <div className="text-center py-12">
          <p className="text-muted-foreground">{translations.noPostsText}</p>
        </div>
      )}
    </div>
  );
}
