import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { ArrowRight, MessageSquare, BookOpen, Search, Clock, User, CheckCircle2 } from "lucide-react"
import Link from "next/link"
import { fetchApi } from "@/lib/api-client"

interface Question {
  id: number;
  title: string;
}

interface News {
  id: number;
  title: string;
  source: string;
  published_at: string;
}

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

interface Trial {
  id: number;
  title: string;
  phase: string;
  status: string;
  cancer_type: string;
  locations: string;
}

export default async function Home() {
  let trendingQuestions: Question[] = [];
  let latestNews: News[] = [];
  let featuredInsight: Insight | null = null;
  let featuredTrial: Trial | null = null;
  let content: any = {};

  try {
    const questionsData = await fetchApi('forum.php');
    trendingQuestions = Array.isArray(questionsData) ? questionsData.slice(0, 4) : [];

    const newsData = await fetchApi('news.php');
    latestNews = Array.isArray(newsData) ? newsData.slice(0, 3) : [];

    const insightsData = await fetchApi('insights.php');
    featuredInsight = Array.isArray(insightsData) && insightsData.length > 0 ? insightsData[0] : null;

    const trialsData = await fetchApi('trials.php');
    featuredTrial = Array.isArray(trialsData) && trialsData.length > 0 ? trialsData[0] : null;

    content = await fetchApi('content.php?page=home');
  } catch (error) {
    console.error("Failed to fetch home data:", error);
  }

  return (
    <div className="flex min-h-screen flex-col">
      {/* Hero Section */}
      <section className="relative overflow-hidden bg-primary/5 py-20 lg:py-32">
        <div className="container relative z-10 mx-auto px-4">
          <div className="max-w-3xl space-y-8">
            <div className="space-y-4">
              <Badge variant="secondary" className="px-3 py-1">
                {content.hero?.badge || "Community & Support"}
              </Badge>
              <h1 className="text-4xl font-extrabold tracking-tight sm:text-6xl text-balance">
                {content.hero?.title || "You're not alone. Find information, support, and community."}
              </h1>
              <p className="text-xl text-muted-foreground text-pretty max-w-2xl">
                {content.hero?.description || "OncoConnect bridges medical expertise and personal experience to help you navigate your cancer journey with confidence."}
              </p>
            </div>
            <div className="flex flex-col sm:flex-row gap-4">
              <Button size="lg" className="text-lg px-8 py-6 rounded-xl shadow-lg hover:shadow-xl transition-all" asChild>
                <Link href="/forum">Ask the Community</Link>
              </Button>
              <Button
                size="lg"
                variant="outline"
                className="text-lg px-8 py-6 rounded-xl bg-background/50 backdrop-blur"
                asChild
              >
                <Link href="/insights">Browse Expert Articles</Link>
              </Button>
            </div>
          </div>
        </div>

        {/* Decorative background element */}
        <div className="absolute right-0 top-1/2 -translate-y-1/2 w-1/3 h-full bg-gradient-to-l from-primary/10 to-transparent blur-3xl rounded-full" />
      </section>

      <main className="flex-1">
        <section className="container mx-auto px-4 py-16">
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
            {/* Left Column: Dynamic Content */}
            <div className="lg:col-span-3 space-y-8">
              <div className="space-y-4">
                <h3 className="text-lg font-bold flex items-center gap-2">
                  <MessageSquare className="h-5 w-5 text-primary" />
                  Trending Questions
                </h3>
                <div className="space-y-3">
                  {trendingQuestions.length > 0 ? trendingQuestions.map((q) => (
                    <Link
                      key={q.id}
                      href={`/forum/${q.id}`}
                      className="block p-3 rounded-lg hover:bg-muted transition-colors border text-sm font-medium"
                    >
                      {q.title}
                    </Link>
                  )) : (
                    <p className="text-sm text-muted-foreground italic">No questions yet.</p>
                  )}
                </div>
              </div>

              <div className="space-y-4">
                <h3 className="text-lg font-bold flex items-center gap-2">
                  <BookOpen className="h-5 w-5 text-secondary" />
                  Oncology News
                </h3>
                <div className="space-y-4">
                  {latestNews.length > 0 ? latestNews.map((n) => (
                    <div key={n.id} className="space-y-1">
                      <Link href="/news" className="text-sm font-semibold hover:underline line-clamp-2">
                        {n.title}
                      </Link>
                      <p className="text-xs text-muted-foreground">{n.source} • {new Date(n.published_at).toLocaleDateString()}</p>
                    </div>
                  )) : (
                    <p className="text-sm text-muted-foreground italic">No news yet.</p>
                  )}
                </div>
              </div>
            </div>

            {/* Center Column: Primary Focus */}
            <div className="lg:col-span-6 space-y-12">
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <h2 className="text-2xl font-bold">Featured Expert Article</h2>
                  <Button variant="ghost" className="text-primary font-bold gap-1" asChild>
                    <Link href="/insights">
                      View all <ArrowRight className="h-4 w-4" />
                    </Link>
                  </Button>
                </div>

                {featuredInsight ? (
                  <Card className="group overflow-hidden border-none shadow-xl ring-1 ring-primary/5">
                    <div className="aspect-[21/9] relative overflow-hidden bg-muted">
                      <img
                        src={featuredInsight.image_url || "https://images.unsplash.com/photo-1579684385127-1ef15d508118?auto=format&fit=crop&q=80&w=1200"}
                        alt={featuredInsight.title}
                        className="object-cover w-full h-full group-hover:scale-105 transition-transform duration-700"
                      />
                      <Badge className="absolute top-4 left-4 bg-primary/90 hover:bg-primary">
                        {featuredInsight.category}
                      </Badge>
                    </div>
                    <CardContent className="p-8 space-y-4">
                      <div className="flex items-center gap-4 text-xs font-medium text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Clock className="h-3 w-3" />
                          {featuredInsight.read_time}
                        </span>
                        <span className="flex items-center gap-1">
                          <User className="h-3 w-3" />
                          Dr. {featuredInsight.author?.last_name}
                        </span>
                      </div>
                      <h3 className="text-3xl font-bold group-hover:text-primary transition-colors leading-tight">
                        {featuredInsight.title}
                      </h3>
                      <p className="text-muted-foreground leading-relaxed text-lg line-clamp-3">
                        {featuredInsight.excerpt}
                      </p>
                      <Button className="w-full sm:w-auto px-8 h-12 text-lg rounded-xl mt-4" asChild>
                        <Link href={`/insights/${featuredInsight.id}`}>Read Full Article</Link>
                      </Button>
                    </CardContent>
                  </Card>
                ) : (
                  <div className="p-12 text-center bg-background rounded-xl border">
                    <p className="text-muted-foreground italic">No featured articles found.</p>
                  </div>
                )}
              </div>

              {/* Clinical Trial Highlight */}
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <h2 className="text-2xl font-bold">Clinical Trial Highlight</h2>
                  <Button variant="ghost" className="text-primary font-bold gap-1" asChild>
                    <Link href="/trials">
                      View all <ArrowRight className="h-4 w-4" />
                    </Link>
                  </Button>
                </div>
                
                {featuredTrial ? (
                  <Card className="border-secondary/20 bg-secondary/5">
                    <CardHeader>
                      <div className="flex justify-between items-start">
                        <Badge variant="outline" className="border-secondary text-secondary-foreground mb-2">
                          {featuredTrial.phase}
                        </Badge>
                        <Badge className="bg-secondary text-secondary-foreground">{featuredTrial.status}</Badge>
                      </div>
                      <CardTitle className="text-xl">
                        {featuredTrial.title}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4 text-xs">
                        <div>
                          <span className="block font-bold uppercase tracking-wider text-muted-foreground mb-1">Location</span>
                          <span className="font-medium">{featuredTrial.locations}</span>
                        </div>
                        <div>
                          <span className="block font-bold uppercase tracking-wider text-muted-foreground mb-1">Cancer Type</span>
                          <span className="font-medium">{featuredTrial.cancer_type}</span>
                        </div>
                      </div>
                      <Button variant="outline" className="w-full bg-white/50" asChild>
                        <Link href={`/trials?q=${encodeURIComponent(featuredTrial.cancer_type)}`}>Learn More</Link>
                      </Button>
                    </CardContent>
                  </Card>
                ) : (
                  <div className="p-12 text-center bg-background rounded-xl border">
                    <p className="text-muted-foreground italic">No trials found.</p>
                  </div>
                )}
              </div>
            </div>

            {/* Right Column: Community & Support */}
            <div className="lg:col-span-3 space-y-8">
              <Card className="bg-primary text-primary-foreground border-none shadow-lg">
                <CardHeader>
                  <CardTitle>Need Support?</CardTitle>
                  <CardDescription className="text-primary-foreground/80">
                    Connect with others who understand.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <Button variant="secondary" className="w-full font-bold shadow-sm" asChild>
                    <Link href="/forum">Join Discussions</Link>
                  </Button>
                  <Button variant="outline" className="w-full bg-white/10 border-white/20 hover:bg-white/20 text-white font-bold" asChild>
                    <Link href="/guides">Patient Guides</Link>
                  </Button>
                </CardContent>
              </Card>

              <div className="p-6 rounded-2xl bg-muted/50 border space-y-4">
                <h3 className="font-bold flex items-center gap-2">
                  <CheckCircle2 className="h-5 w-5 text-green-500" />
                  Verified Experts
                </h3>
                <p className="text-sm text-muted-foreground leading-relaxed">
                  {content.verified?.text || "All articles and medical insights are written by board-certified oncologists and specialized healthcare professionals."}
                </p>
              </div>
            </div>
          </div>
        </section>
      </main>
    </div>
  )
}
