import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { ExternalLink, TrendingUp, Calendar, ArrowRight } from "lucide-react"
import Link from "next/link"
import { cn } from "@/lib/utils"

import { fetchApi } from "@/lib/api-client"

import { NewsletterSubscription } from "@/components/newsletter-subscription"

interface NewsArticle {
  id: number;
  title: string;
  source: string;
  published_at: string;
  category: string;
  summary: string;
  url?: string;
}

export default async function NewsPage({
  searchParams,
}: {
  searchParams: Promise<{ source?: string }>
}) {
  const { source: activeSource = "" } = await searchParams
  
  let newsArticles: NewsArticle[] = [];
  let content: any = {};
  try {
    const query = activeSource ? `?source=${encodeURIComponent(activeSource)}` : '';
    newsArticles = await fetchApi(`news.php${query}`);
    content = await fetchApi('content.php?page=news');
  } catch (error) {
    console.error("Failed to fetch news:", error);
  }

  const topSources = content.sidebar?.top_sources ? JSON.parse(content.sidebar.top_sources) : ["ASCO", "National Cancer Institute", "ESMO", "Nature Medicine"];

  return (
    <main className="flex-1 bg-muted/20">
      <section className="container mx-auto px-4 py-12">
        <div className="flex items-center justify-between mb-8">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-primary flex items-center justify-center">
              <TrendingUp className="h-6 w-6 text-primary-foreground" />
            </div>
            <h1 className="text-3xl font-bold">
              {activeSource ? `News from ${activeSource}` : "Trending in Oncology"}
            </h1>
          </div>
          {activeSource && (
            <Button variant="ghost" size="sm" asChild>
              <Link href="/news">View All News</Link>
            </Button>
          )}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-6">
            {newsArticles.length > 0 ? newsArticles.map((item) => (
              <Card key={item.id} className="group hover:shadow-md transition-all border-none ring-1 ring-border overflow-hidden">
                <Link href={`/news/${item.id}`}>
                  <CardContent className="p-6">
                    <div className="flex flex-col md:flex-row gap-6">
                      <div className="flex-1 space-y-3">
                        <div className="flex items-center gap-2">
                          <Badge variant="outline" className="text-[10px] font-bold uppercase tracking-wider">
                            {item.category}
                          </Badge>
                          <span className="text-xs text-muted-foreground flex items-center gap-1">
                            <Calendar className="h-3 w-3" />
                            {new Date(item.published_at).toLocaleDateString()}
                          </span>
                        </div>
                        <h3 className="text-xl font-bold group-hover:text-primary transition-colors">{item.title}</h3>
                        <p className="text-sm text-muted-foreground leading-relaxed line-clamp-2">{item.summary}</p>
                        <div className="pt-2 flex items-center justify-between">
                          <span className="text-xs font-bold text-muted-foreground uppercase">Source: {item.source}</span>
                          <span className="text-primary font-bold text-sm flex items-center gap-1">
                            Read More <ArrowRight className="h-3 w-3 group-hover:translate-x-1 transition-transform" />
                          </span>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Link>
              </Card>
            )) : (
              <div className="p-12 text-center bg-background rounded-xl border">
                <p className="text-muted-foreground italic">No news articles found {activeSource ? `for ${activeSource}` : ""}.</p>
                {activeSource && (
                  <Button variant="link" asChild className="mt-2">
                    <Link href="/news">Clear filter</Link>
                  </Button>
                )}
              </div>
            )}
          </div>

          <aside className="space-y-6">
            <Card className="bg-primary text-primary-foreground overflow-hidden">
              <NewsletterSubscription />
            </Card>

            <div className="space-y-4">
              <h3 className="font-bold px-1">Top Sources</h3>
              <div className="space-y-2">
                {topSources.map((source: string) => (
                  <Link
                    key={source}
                    href={`/news?source=${encodeURIComponent(source)}`}
                    className={cn(
                      "flex items-center justify-between p-3 rounded-lg border text-sm font-medium transition-colors group",
                      activeSource === source 
                        ? "bg-primary text-primary-foreground border-primary" 
                        : "bg-background hover:bg-muted border-border"
                    )}
                  >
                    {source}
                    <ArrowRight className={cn(
                      "h-4 w-4 transition-transform group-hover:translate-x-1",
                      activeSource === source ? "text-primary-foreground" : "text-muted-foreground"
                    )} />
                  </Link>
                ))}
              </div>
            </div>
          </aside>
        </div>
      </section>
    </main>
  )
}

