import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Calendar, Clock, User, ArrowLeft, Share2, Bookmark } from "lucide-react"
import Link from "next/link"
import { fetchApi } from "@/lib/api-client"

interface Insight {
  id: number;
  title: string;
  excerpt: string;
  content: string;
  category: string;
  image_url: string;
  read_time: string;
  created_at: string;
  author: {
    first_name: string;
    last_name: string;
    role: string;
    bio: string;
    avatar_url?: string;
  };
}

export default async function InsightDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  
  let insight: Insight | null = null
  let relatedInsights: Insight[] = []

  try {
    // Fetch main insight first
    insight = await fetchApi(`insights.php?id=${id}`)
    
    if (insight) {
      // Fetch related insights in parallel
      const relatedData = await fetchApi(`insights.php?related_id=${id}`).catch(err => {
        console.error("Failed to fetch related insights:", err)
        return []
      })
      relatedInsights = relatedData
    }
  } catch (error) {
    console.error("Failed to fetch insight details:", error)
  }

  if (!insight) {
    return (
      <div className="container mx-auto px-4 py-20 text-center">
        <h1 className="text-3xl font-bold mb-4">Article not found</h1>
        <p className="text-muted-foreground mb-8">We couldn't find the article you're looking for. It might have been moved or removed.</p>
        <Button asChild>
          <Link href="/insights">Back to Insights</Link>
        </Button>
      </div>
    )
  }

  return (
    <main className="flex-1 pb-20">
      {/* Hero Header */}
      <div className="relative h-[400px] w-full bg-muted">
        <img
          src={insight.image_url || "https://images.unsplash.com/photo-1579684385127-1ef15d508118?auto=format&fit=crop&q=80&w=1200"}
          alt={insight.title}
          className="w-full h-full object-cover brightness-50"
        />
        <div className="absolute inset-0 flex items-end">
          <div className="container mx-auto px-4 py-12">
            <div className="max-w-3xl space-y-4">
              <Button variant="ghost" className="text-white hover:bg-white/20 mb-4 gap-2" asChild>
                <Link href="/insights">
                  <ArrowLeft className="h-4 w-4" />
                  Back to Insights
                </Link>
              </Button>
              <Badge className="bg-primary/90 hover:bg-primary border-none">
                {insight.category}
              </Badge>
              <h1 className="text-4xl md:text-5xl font-extrabold text-white tracking-tight leading-tight">
                {insight.title}
              </h1>
              <div className="flex flex-wrap items-center gap-6 text-white/90 text-sm">
                <span className="flex items-center gap-2">
                  <User className="h-4 w-4" />
                  Dr. {insight.author?.first_name} {insight.author?.last_name}
                </span>
                <span className="flex items-center gap-2">
                  <Calendar className="h-4 w-4" />
                  {new Date(insight.created_at).toLocaleDateString()}
                </span>
                <span className="flex items-center gap-2">
                  <Clock className="h-4 w-4" />
                  {insight.read_time}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-4 py-12">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-12">
          {/* Main Content */}
          <article className="lg:col-span-8 space-y-8">
            <div className="flex items-center justify-between py-4 border-y">
              <div className="flex items-center gap-4">
                <Button variant="ghost" size="sm" className="gap-2">
                  <Share2 className="h-4 w-4" />
                  Share
                </Button>
                <Button variant="ghost" size="sm" className="gap-2">
                  <Bookmark className="h-4 w-4" />
                  Save
                </Button>
              </div>
            </div>

            <div className="prose prose-lg prose-slate max-w-none">
              <p className="text-xl font-medium text-muted-foreground leading-relaxed italic mb-8">
                {insight.excerpt}
              </p>
              <div className="space-y-6 leading-relaxed whitespace-pre-wrap">
                {insight.content}
              </div>
            </div>
          </article>

          {/* Sidebar */}
          <aside className="lg:col-span-4 space-y-8">
            <div className="p-6 rounded-2xl bg-muted/50 border space-y-4 sticky top-24">
              <h3 className="font-bold text-lg border-b pb-2">About the Author</h3>
              <div className="flex items-center gap-4">
                <div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold">
                  {insight.author?.first_name?.[0]}
                </div>
                <div>
                  <p className="font-bold">
                    Dr. {insight.author?.first_name} {insight.author?.last_name}
                  </p>
                  <p className="text-xs text-muted-foreground capitalize">
                    {insight.author?.role}
                  </p>
                </div>
              </div>
              <p className="text-sm text-muted-foreground leading-relaxed">
                {insight.author?.bio || "Expert in oncology providing evidence-based insights for the OncoConnect community."}
              </p>
              <Button variant="outline" className="w-full bg-transparent" asChild>
                <Link href={`/profile/${insight.id}`}>View Expert Profile</Link>
              </Button>
            </div>

            {relatedInsights.length > 0 && (
              <div className="space-y-4">
                <h3 className="font-bold text-lg border-b pb-2">Related Articles</h3>
                <div className="space-y-4">
                  {relatedInsights.map((related) => (
                    <Link 
                      key={related.id} 
                      href={`/insights/${related.id}`}
                      className="block p-4 rounded-xl border bg-card hover:shadow-md transition-all group"
                    >
                      <Badge variant="secondary" className="mb-2 text-[10px] h-4">
                        {related.category}
                      </Badge>
                      <h4 className="font-bold group-hover:text-primary transition-colors line-clamp-2">
                        {related.title}
                      </h4>
                      <div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
                        <User className="h-3 w-3" />
                        <span>Dr. {related.author?.first_name} {related.author?.last_name}</span>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            )}
          </aside>
        </div>
      </div>
    </main>
  )
}
