import { PageLayout } from "@/components/layout/PageLayout";
import { useQuery } from "@tanstack/react-query";
import { BlogPostListItem } from "@/lib/types";
import { Link } from "wouter";
import { formatDistanceToNow } from "date-fns";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { useState } from "react";
import { Calendar, Clock, MessageSquare, Search, ThumbsUp, BookOpen, PenSquare } from "lucide-react";

export default function BlogList() {
  const [searchQuery, setSearchQuery] = useState("");
  const [activeTab, setActiveTab] = useState("all");
  
  const { data: posts, isLoading, error } = useQuery<BlogPostListItem[]>({
    queryKey: ['/api/blog'],
  });
  
  // Filter posts based on search query and active tab
  const filteredPosts = posts?.filter(post => {
    const matchesSearch = searchQuery === "" || 
      post.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      post.excerpt?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      post.tags?.some(tag => tag.name.toLowerCase().includes(searchQuery.toLowerCase()));
      
    if (activeTab === "all") return matchesSearch;
    if (activeTab === "popular") return matchesSearch && post.likeCount > 5;
    if (activeTab === "recent") {
      // Consider posts from the last 30 days as recent
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
      return matchesSearch && new Date(post.publishedAt || post.createdAt) >= thirtyDaysAgo;
    }
    
    return matchesSearch;
  });
  
  const formatDate = (date: Date | null) => {
    if (!date) return "";
    return formatDistanceToNow(new Date(date), { addSuffix: true });
  };
  
  return (
    <PageLayout>
      <section className="max-w-5xl mx-auto px-4 py-8">
        <div className="flex justify-between items-center mb-6">
          <div>
            <h1 className="text-3xl font-serif font-bold text-navy dark:text-cream">Literary Blog</h1>
            <p className="text-navy/70 dark:text-cream/70 mt-1">
              Articles, essays, and discussions on literature, translations, and the literary world
            </p>
          </div>
          
          <Link href="/blog/create">
            <Button className="bg-russet text-white hover:bg-russet/90 flex items-center gap-2">
              <PenSquare className="h-4 w-4" />
              <span>Write Article</span>
            </Button>
          </Link>
        </div>
        
        <div className="mb-8 flex flex-col sm:flex-row justify-between gap-4">
          <Tabs defaultValue="all" className="w-full sm:w-auto" onValueChange={setActiveTab}>
            <TabsList>
              <TabsTrigger value="all">All Articles</TabsTrigger>
              <TabsTrigger value="popular">Popular</TabsTrigger>
              <TabsTrigger value="recent">Recent</TabsTrigger>
            </TabsList>
          </Tabs>
          
          <div className="relative w-full sm:w-64">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-navy/50 dark:text-cream/50" />
            <Input 
              type="search" 
              placeholder="Search articles..." 
              className="pl-9 w-full"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)} 
            />
          </div>
        </div>
        
        {isLoading ? (
          <div className="space-y-6">
            {Array.from({ length: 3 }).map((_, i) => (
              <Card key={i} className="relative overflow-hidden">
                <CardHeader className="pb-2">
                  <Skeleton className="h-4 w-20 mb-1" />
                  <Skeleton className="h-7 w-3/4 mb-1" />
                  <Skeleton className="h-5 w-1/3" />
                </CardHeader>
                <CardContent className="pb-2">
                  <Skeleton className="h-24 w-full" />
                </CardContent>
                <CardFooter>
                  <Skeleton className="h-4 w-32" />
                </CardFooter>
              </Card>
            ))}
          </div>
        ) : error ? (
          <div className="text-center py-12">
            <h3 className="text-xl font-medium mb-2">Failed to load blog posts</h3>
            <p className="text-navy/70 dark:text-cream/70 mb-4">
              There was an error retrieving the blog articles. Please try again later.
            </p>
            <Button variant="outline" onClick={() => window.location.reload()}>
              Refresh
            </Button>
          </div>
        ) : filteredPosts?.length === 0 ? (
          <div className="text-center py-12 border border-dashed border-navy/20 dark:border-cream/20 rounded-lg">
            <BookOpen className="h-16 w-16 mx-auto text-navy/30 dark:text-cream/30 mb-4" />
            <h3 className="text-xl font-medium mb-2">No articles found</h3>
            <p className="text-navy/70 dark:text-cream/70 mb-4">
              {searchQuery 
                ? "No articles match your search query. Try different keywords." 
                : "There are no blog posts yet. Be the first to contribute!"}
            </p>
            <Link href="/blog/create">
              <Button className="bg-russet text-white hover:bg-russet/90">
                Write an Article
              </Button>
            </Link>
          </div>
        ) : (
          <div className="space-y-6">
            {filteredPosts?.map((post) => (
              <Link key={post.id} href={`/blog/${post.slug}`}>
                <Card className="hover:shadow-md transition-shadow cursor-pointer relative overflow-hidden group">
                  {post.likeCount > 10 && (
                    <div className="absolute top-0 right-0 bg-russet text-white text-xs py-1 px-2 rounded-bl-md">
                      Popular
                    </div>
                  )}
                  
                  <CardHeader className="pb-2">
                    <div className="flex justify-between">
                      <div className="flex items-center gap-2 text-sm text-navy/60 dark:text-cream/60">
                        <Calendar className="h-3.5 w-3.5" />
                        <span>{formatDate(post.publishedAt || post.createdAt)}</span>
                      </div>
                      
                      <div className="flex items-center gap-4">
                        <div className="flex items-center gap-1 text-sm text-navy/60 dark:text-cream/60">
                          <MessageSquare className="h-3.5 w-3.5" />
                          <span>{post.commentCount}</span>
                        </div>
                        <div className="flex items-center gap-1 text-sm text-navy/60 dark:text-cream/60">
                          <ThumbsUp className="h-3.5 w-3.5" />
                          <span>{post.likeCount}</span>
                        </div>
                      </div>
                    </div>
                    
                    <CardTitle className="text-xl font-serif group-hover:text-russet transition-colors">
                      {post.title}
                    </CardTitle>
                    
                    {post.tags && post.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-1">
                        {post.tags.map((tag) => (
                          <Badge key={tag.id} variant="outline" className="text-xs">
                            {tag.name}
                          </Badge>
                        ))}
                      </div>
                    )}
                  </CardHeader>
                  
                  <CardContent className="pb-2">
                    <CardDescription className="text-navy/70 dark:text-cream/70 line-clamp-3">
                      {post.excerpt || ""}
                    </CardDescription>
                  </CardContent>
                  
                  <CardFooter>
                    <div className="flex items-center gap-2">
                      <Avatar className="h-6 w-6">
                        <AvatarImage src={post.author?.avatar || ""} alt={post.author?.displayName || "Author"} />
                        <AvatarFallback className="text-xs">
                          {post.author?.displayName?.charAt(0) || "A"}
                        </AvatarFallback>
                      </Avatar>
                      <span className="text-sm text-navy/80 dark:text-cream/80">
                        {post.author?.displayName || "Anonymous"}
                      </span>
                    </div>
                  </CardFooter>
                </Card>
              </Link>
            ))}
            
            {posts && posts.length > 0 && (
              <div className="flex justify-center pt-4">
                <Button variant="outline" disabled>
                  <Clock className="mr-2 h-4 w-4" />
                  Load more articles
                </Button>
              </div>
            )}
          </div>
        )}
      </section>
    </PageLayout>
  );
}