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'

export function ArchiveComponent() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['articles'],
    queryFn: () => api.fetchArticles({ status: 'published' }),
  })

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-lg">Loading articles...</div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-lg text-red-500">Error loading articles</div>
      </div>
    )
  }

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-3xl font-bold">Articles</h1>
        <p className="text-muted-foreground">Latest news and articles</p>
      </div>

       <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
         {data?.data.map((article) => (
           <div
             key={article.id}
             className="p-6 rounded-xl border bg-card hover:shadow-lg transition-shadow"
           >
             <Link
                to="/articles/$id"
                params={{ id: article.id }}
                className="block mb-4"
              >
               <h2 className="text-xl font-semibold mb-2 line-clamp-2">
                 {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} 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>

      {data?.data.length === 0 && (
        <div className="text-center py-12">
          <p className="text-muted-foreground text-lg">
            No articles published yet. Check back soon!
          </p>
        </div>
      )}
    </div>
  )
}