import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import * as api from '@/lib/api'
import { SocialShareButtons } from '@/components/features/social-share'
import { PinnedLiveBlogsSidebar } from '@/components/home/PinnedLiveBlogsSidebar'

interface CategoryPageProps {
  categorySlug: string
  categoryName: string
  categoryDescription?: string
}

export function CategoryPage({ categorySlug, categoryName, categoryDescription }: CategoryPageProps) {
  const { data: articlesData, isLoading: articlesLoading, error: articlesError } = useQuery({
    queryKey: ['category-articles', categorySlug],
    queryFn: () => api.fetchArticles({ category: categorySlug, status: 'published' }),
  })

  const { data: heroData, isLoading: heroLoading } = useQuery({
    queryKey: ['category-hero', categorySlug],
    queryFn: () => api.fetchArticles({ category: categorySlug, status: 'published', limit: 1 }),
    enabled: !!categorySlug,
  })

  const heroArticle = heroData?.data?.[0]
  const articles = articlesData?.data || []

  if (articlesLoading || heroLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-lg">Вчитување...</div>
      </div>
    )
  }

  if (articlesError) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-lg text-red-500">Грешка при вчитување на статии</div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Category Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold">{categoryName}</h1>
        {categoryDescription && (
          <p className="text-muted-foreground mt-2">{categoryDescription}</p>
        )}
      </div>

      {/* Hero Section with Pinned Live Blogs Sidebar */}
      {heroArticle && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-12">
          {/* Hero Article - 2/3 width */}
          <div className="lg:col-span-2">
            <div className="rounded-xl border bg-card overflow-hidden group hover:shadow-lg transition-shadow">
                <Link to="/articles/$id" params={{ id: heroArticle.id }} className="block">
                {heroArticle.featuredImage ? (
                  <div className="relative h-64 md:h-80 overflow-hidden">
                    <img
                      src={heroArticle.featuredImage}
                      alt={heroArticle.title}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent" />
                  </div>
                ) : (
                  <div className="h-64 md:h-80 bg-gradient-to-br from-primary/10 to-primary/5 flex items-center justify-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" className="text-primary/30">
                      <path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2" />
                      <path d="M18 14h-8" />
                      <path d="M15 18h-5" />
                      <path d="M10 6h8v4h-8V6Z" />
                    </svg>
                  </div>
                )}
              </Link>
              
              <div className="p-6">
              <Link to="/articles/$id" params={{ id: heroArticle.id }} className="block">
                  <h2 className="text-2xl font-bold mb-3 group-hover:text-primary transition-colors">
                    {heroArticle.title}
                  </h2>
                  {heroArticle.excerpt && (
                    <p className="text-muted-foreground mb-4 line-clamp-3">
                      {heroArticle.excerpt}
                    </p>
                  )}
                </Link>
                
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <div className="flex items-center space-x-4">
                    <span>
                      {new Date(heroArticle.createdAt).toLocaleDateString('mk-MK', {
                        day: 'numeric',
                        month: 'short',
                        year: 'numeric',
                      })}
                    </span>
                    <span>•</span>
                    <span>{heroArticle.views} прегледи</span>
                  </div>
                  
                  <SocialShareButtons
                     articleId={heroArticle.id}
                     title={heroArticle.title}
                     url={`${window.location.origin}/articles/${heroArticle.id}`}
                     excerpt={heroArticle.excerpt ?? undefined}
                     image={heroArticle.featuredImage}
                     tags={heroArticle.tags}
                     variant="compact"
                   />
                </div>
              </div>
            </div>
          </div>
          
          {/* Pinned Live Blogs Sidebar - 1/3 width */}
          <div className="lg:col-span-1">
            <PinnedLiveBlogsSidebar />
          </div>
        </div>
      )}

      {/* Articles Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {articles
          .filter(article => article.id !== heroArticle?.id) // Exclude hero article from grid
          .map((article) => (
            <div
              key={article.id}
              className="p-6 rounded-xl border bg-card hover:shadow-lg transition-shadow group"
            >
              <Link
                 to="/articles/$id"
                 params={{ id: article.id }}
                 className="block mb-4"
              >
                <h2 className="text-xl font-semibold mb-2 line-clamp-2 group-hover:text-primary transition-colors">
                  {article.title}
                </h2>
                {article.excerpt && (
                  <p className="text-muted-foreground text-sm mb-4 line-clamp-3">
                    {article.excerpt}
                  </p>
                )}
              </Link>
              
              <div className="flex items-center justify-between text-sm text-muted-foreground">
                <div className="flex items-center space-x-4">
                  <span>
                    {new Date(article.createdAt).toLocaleDateString('mk-MK', {
                      day: 'numeric',
                      month: 'short',
                      year: 'numeric',
                    })}
                  </span>
                  <span>•</span>
                  <span>{article.views} прегледи</span>
                </div>
                
                <SocialShareButtons
                   articleId={article.id}
                   title={article.title}
                   url={`${window.location.origin}/articles/${article.id}`}
                   excerpt={article.excerpt ?? undefined}
                   image={article.featuredImage}
                   tags={article.tags}
                   variant="compact"
                 />
              </div>
            </div>
          ))}
      </div>

      {articles.length === 0 && (
        <div className="text-center py-12">
          <p className="text-muted-foreground text-lg">
            Нема објавени статии во оваа категорија. Проверете подоцна!
          </p>
        </div>
      )}
    </div>
  )
}