import { useQuery } from "@tanstack/react-query";
import { News } from "@shared/schema";
import { format } from "date-fns";
import { Loader2 } from "lucide-react";
import { useLanguage } from "@/hooks/use-language";
import { useParams } from "wouter";

export default function NewsSinglePage() {
  const { id } = useParams<{ id: string }>();
  const { language } = useLanguage();

  console.log("News ID from params:", id);

  const { data: news, isLoading } = useQuery<News[]>({
    queryKey: ["/api/news"],
  });

  console.log("Fetched news:", news);

  if (isLoading) {
    return (
      <div className="flex justify-center">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  const newsItem = news?.find(n => n.id === Number(id));
  console.log("Found news item:", newsItem);

  if (!newsItem) {
    return (
      <div className="text-center py-8">
        <h2 className="text-2xl font-bold">
          {language === 'en' ? 'News not found' : 'الخبر غير موجود'}
        </h2>
      </div>
    );
  }

  return (
    <article className={`max-w-3xl mx-auto space-y-6 ${language === 'ar' ? 'rtl' : 'ltr'}`}>
      <header className="space-y-4">
        <h1 className="text-4xl font-bold">
          {language === 'en' ? newsItem.title : newsItem.titleAr}
        </h1>
        <time className="block text-muted-foreground">
          {format(new Date(newsItem.publishDate), 
            language === 'ar' ? 'dd MMMM yyyy, HH:mm' : 'MMMM dd, yyyy, HH:mm'
          )}
        </time>
      </header>

      {newsItem.image && (
        <img
          src={newsItem.image}
          alt={language === 'en' ? newsItem.title : newsItem.titleAr}
          className="w-full aspect-video object-cover rounded-lg"
        />
      )}

      <div className="prose prose-lg dark:prose-invert max-w-none">
        <p className="whitespace-pre-wrap">
          {language === 'en' ? newsItem.content : newsItem.contentAr}
        </p>
      </div>
    </article>
  );
}