import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Search, MessageSquare, Clock, Filter, User } from "lucide-react"
import { Input } from "@/components/ui/input"
import { fetchApi } from "@/lib/api-client"
import { CreateInsightButton } from "@/components/create-insight-button"
import Link from "next/link"

interface Article {
  id: number;
  title: string;
  excerpt: string;
  category: string;
  image_url: string;
  read_time: string;
  created_at: string;
  author: {
    first_name: string;
    last_name: string;
  };
}

export default async function InsightsPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; category?: string }>
}) {
  const { q: searchQuery = "", category: activeTab = "all" } = await searchParams
  
  let articles: Article[] = []
  let content: any = {}
  try {
    articles = await fetchApi(`insights.php?q=${encodeURIComponent(searchQuery)}&category=${encodeURIComponent(activeTab)}`)
    content = await fetchApi('content.php?page=insights')
  } catch (error) {
    console.error("Failed to fetch insights:", error)
  }

  const categories = content.navigation?.categories ? JSON.parse(content.navigation.categories) : ["treatment", "lifestyle", "mental-health", "nutrition"];

  return (
    <main className="flex-1">
      {/* Header Section */}
      <section className="bg-primary/5 py-16 border-b">
        <div className="container mx-auto px-4">
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
            <div className="max-w-3xl space-y-4">
              <h1 className="text-4xl font-extrabold tracking-tight">Trusted Medical Knowledge</h1>
              <p className="text-lg text-muted-foreground text-pretty">
                Deep dives into oncology advancements, lifestyle management, and peer-reviewed articles written by
                verified healthcare professionals.
              </p>
            </div>
            <CreateInsightButton />
          </div>
        </div>
      </section>

      <section className="container mx-auto px-4 py-12">
        <Tabs defaultValue={activeTab} className="space-y-8">
          <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6">
            <TabsList className="bg-muted/50 p-1">
              <TabsTrigger value="all">All Articles</TabsTrigger>
              {categories.map((cat: string) => (
                <TabsTrigger key={cat} value={cat} className="capitalize">
                  {cat.replace('-', ' ')}
                </TabsTrigger>
              ))}
            </TabsList>

            <form className="flex items-center gap-3 w-full lg:w-auto">
              <div className="relative flex-1 lg:w-64">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input name="q" placeholder="Search articles..." className="pl-9 h-10" defaultValue={searchQuery} />
              </div>
              <Button variant="outline" size="icon" type="submit" className="shrink-0 bg-transparent">
                <Filter className="h-4 w-4" />
              </Button>
            </form>
          </div>

          <TabsContent value={activeTab} className="space-y-12">
            {articles && articles.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                {articles.map((article: Article) => (
                    <Link href={`/insights/${article.id}`} className="flex flex-col h-full border-none shadow-lg ring-1 ring-primary/5 hover:shadow-xl transition-all group">
                      <div className="aspect-video relative overflow-hidden rounded-t-xl bg-muted">
                        <img
                          src={article.image_url || "/placeholder.svg"}
                          alt={article.title}
                          className="object-cover w-full h-full group-hover:scale-105 transition-transform duration-500"
                        />
                        <span className="absolute top-4 left-4 bg-background/90 text-foreground border px-2 py-1 rounded text-xs font-medium">
                          {article.category}
                        </span>
                      </div>
                      <div className="flex-1 p-6">
                        <div className="flex items-center gap-4 text-xs text-muted-foreground mb-3">
                          <span className="flex items-center gap-1">
                            <Clock className="h-3 w-3" />
                            {article.read_time}
                          </span>
                          <span>{new Date(article.created_at).toLocaleDateString()}</span>
                        </div>
                        <h2 className="text-xl group-hover:text-primary transition-colors line-clamp-2 leading-snug">
                          {article.title}
                        </h2>
                        <p className="line-clamp-3 text-pretty mt-2 text-sm text-muted-foreground">{article.excerpt}</p>
                      </div>
                      <div className="pt-0 border-t mt-auto p-6">
                        <div className="flex items-center justify-between mb-4">
                          <div className="flex items-center gap-2">
                            <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden">
                              <User className="h-4 w-4 text-muted-foreground" />
                            </div>
                            <span className="text-xs font-bold">
                              {article.author?.first_name} {article.author?.last_name}
                            </span>
                          </div>
                        </div>
                        <div className="flex items-center justify-between gap-2">
                          <span className="font-bold text-primary group-hover:translate-x-1 transition-transform text-sm">
                            Read More →
                          </span>
                          <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-xs text-muted-foreground">
                             <MessageSquare className="h-3.5 w-3.5" />
                             Discuss
                           </Button>
                        </div>
                      </div>
                    </Link>
                ))}
              </div>
            ) : (
              <div className="text-center py-20 border-2 border-dashed rounded-xl">
                <p className="text-muted-foreground italic">No articles found matching your criteria.</p>
              </div>
            )}
          </TabsContent>
        </Tabs>
      </section>

      {/* Newsletter / Call to Action */}
      <section className="bg-secondary/10 py-20 mt-12">
        <div className="container mx-auto px-4 text-center space-y-8">
          <div className="max-w-2xl mx-auto space-y-4">
            <h2 className="text-3xl font-bold">Stay Updated with Oncology Insights</h2>
            <p className="text-muted-foreground">
              Get the latest peer-reviewed research and treatment guides delivered to your inbox once a month.
            </p>
          </div>
          <div className="flex flex-col sm:flex-row gap-3 max-w-md mx-auto">
            <Input placeholder="Enter your email" className="h-12 bg-background border-none shadow-inner" />
            <Button size="lg" className="px-8 font-bold h-12 shadow-lg">
              Subscribe
            </Button>
          </div>
          <p className="text-[10px] text-muted-foreground uppercase tracking-widest font-bold">
            We never share your data. Unsubscribe at any time.
          </p>
        </div>
      </section>
    </main>
  )
}
