import { PageLayout } from "@/components/layout/PageLayout";
import { useQuery } from "@tanstack/react-query";
import { useParams, Link } from "wouter";
import { AuthorWithWorks, WorkWithAuthor } from "@/lib/types";
import { WorkCard } from "@/components/common/WorkCard";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { AuthorTimeline } from "@/components/authors/AuthorTimeline";
import { Skeleton } from "@/components/ui/skeleton";
import { useState } from "react";
import { Heart, Share2, Grid3X3, List } from "lucide-react";

export default function AuthorProfile() {
  const { slug } = useParams();
  const [view, setView] = useState<'list' | 'grid'>('list');

  const { data: author, isLoading: authorLoading } = useQuery<AuthorWithWorks>({
    queryKey: [`/api/authors/${slug}`],
  });

  const { data: works, isLoading: worksLoading } = useQuery<WorkWithAuthor[]>({
    queryKey: [`/api/authors/${slug}/works`],
    enabled: !!author,
  });

  const { data: timeline, isLoading: timelineLoading } = useQuery({
    queryKey: [`/api/authors/${slug}/timeline`],
    enabled: !!author,
  });

  const [following, setFollowing] = useState(false);
  const [followCount, setFollowCount] = useState(Math.floor(Math.random() * 2000));

  const handleFollow = () => {
    if (following) {
      setFollowCount(followCount - 1);
    } else {
      setFollowCount(followCount + 1);
    }
    setFollowing(!following);
  };

  return (
    <PageLayout>
      <section className="bg-paper dark:bg-dark-paper">
        <div className="max-w-[var(--content-width)] mx-auto px-4 md:px-6 py-8 md:py-12">
          {authorLoading ? (
            <div className="flex flex-col md:flex-row md:items-end gap-6 md:gap-8">
              <Skeleton className="flex-shrink-0 w-20 h-20 md:w-32 md:h-32 rounded-full" />
              <div className="flex-1">
                <Skeleton className="h-10 w-1/3 mb-2" />
                <Skeleton className="h-5 w-1/4 mb-2" />
                <Skeleton className="h-20 w-full mb-4" />
                <Skeleton className="h-10 w-40" />
              </div>
            </div>
          ) : author ? (
            <div className="flex flex-col md:flex-row md:items-end gap-6 md:gap-8">
              <div className="flex-shrink-0 w-20 h-20 md:w-32 md:h-32 rounded-full bg-navy/10 dark:bg-navy/20 overflow-hidden">
                <img 
                  src={author.portrait || "https://via.placeholder.com/256"} 
                  alt={`Photo of ${author.name}`} 
                  className="w-full h-full object-cover" 
                />
              </div>
              <div className="flex-1">
                <div className="flex items-center gap-3 mb-1">
                  <h1 className="font-serif text-2xl md:text-4xl font-bold text-navy dark:text-cream">{author.name}</h1>
                  {author.country && (
                    <div className="flex items-center gap-1">
                      <img 
                        src={`https://flagcdn.com/w20/${author.country.toLowerCase()}.png`} 
                        alt={author.country} 
                        className="w-5 h-auto rounded" 
                      />
                    </div>
                  )}
                </div>
                <p className="text-navy/70 dark:text-cream/70 text-sm md:text-base font-serif mb-2">
                  {author.birthYear}–{author.deathYear || 'present'}
                </p>
                <p className="text-navy/80 dark:text-cream/80 max-w-2xl mb-4">
                  {author.biography}
                </p>
                <div className="flex items-center gap-3">
                  <Button
                    variant="outline"
                    className={`btn-feedback flex items-center gap-2 py-1.5 px-4 rounded-full ${
                      following
                        ? 'bg-russet text-white hover:bg-russet/90'
                        : 'bg-russet/10 hover:bg-russet/20 dark:bg-russet/20 dark:hover:bg-russet/30 text-russet dark:text-russet/90'
                    } font-sans font-medium text-sm transition-colors`}
                    onClick={handleFollow}
                  >
                    <Heart className={`h-4 w-4 ${following ? 'fill-white' : ''}`} />
                    <span>{following ? 'Following' : 'Follow'}</span>
                    <span className="text-xs ml-1">({followCount.toLocaleString()})</span>
                  </Button>
                  <Button
                    variant="outline"
                    className="py-1.5 px-4 rounded-full bg-navy/10 hover:bg-navy/20 dark:bg-navy/20 dark:hover:bg-navy/30 text-navy dark:text-cream/90 font-sans font-medium text-sm transition-colors"
                  >
                    <Share2 className="h-4 w-4 mr-2" />
                    Share
                  </Button>
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-8">
              <h1 className="text-2xl font-bold mb-4">Author not found</h1>
              <Link href="/authors">
                <Button>Back to Authors</Button>
              </Link>
            </div>
          )}

          {author && (
            <Tabs defaultValue="works" className="mt-8">
              <div className="border-b border-sage/20 dark:border-sage/10">
                <TabsList className="bg-transparent">
                  <TabsTrigger 
                    value="works"
                    className="data-[state=active]:text-russet data-[state=active]:border-russet data-[state=active]:border-b-2 rounded-none border-b-2 border-transparent bg-transparent"
                  >
                    Works
                  </TabsTrigger>
                  <TabsTrigger 
                    value="translations"
                    className="data-[state=active]:text-russet data-[state=active]:border-russet data-[state=active]:border-b-2 rounded-none border-b-2 border-transparent bg-transparent"
                  >
                    Translations
                  </TabsTrigger>
                  <TabsTrigger 
                    value="timeline"
                    className="data-[state=active]:text-russet data-[state=active]:border-russet data-[state=active]:border-b-2 rounded-none border-b-2 border-transparent bg-transparent"
                  >
                    Timeline
                  </TabsTrigger>
                  <TabsTrigger 
                    value="about"
                    className="data-[state=active]:text-russet data-[state=active]:border-russet data-[state=active]:border-b-2 rounded-none border-b-2 border-transparent bg-transparent"
                  >
                    About
                  </TabsTrigger>
                  <TabsTrigger 
                    value="discussions"
                    className="data-[state=active]:text-russet data-[state=active]:border-russet data-[state=active]:border-b-2 rounded-none border-b-2 border-transparent bg-transparent"
                  >
                    Discussions
                  </TabsTrigger>
                </TabsList>
              </div>

              <TabsContent value="works" className="pt-6">
                <div className="flex justify-between items-center mt-6 mb-4">
                  <h2 className="font-serif text-lg font-medium text-navy dark:text-cream">
                    Works <span className="text-navy/60 dark:text-cream/60">({works?.length || 0})</span>
                  </h2>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-navy/70 dark:text-cream/70 font-sans">View:</span>
                    <Button
                      variant={view === 'list' ? 'default' : 'outline'}
                      size="icon"
                      className="h-8 w-8"
                      onClick={() => setView('list')}
                    >
                      <List className="h-4 w-4" />
                      <span className="sr-only">List view</span>
                    </Button>
                    <Button
                      variant={view === 'grid' ? 'default' : 'outline'}
                      size="icon"
                      className="h-8 w-8"
                      onClick={() => setView('grid')}
                    >
                      <Grid3X3 className="h-4 w-4" />
                      <span className="sr-only">Grid view</span>
                    </Button>
                  </div>
                </div>

                {worksLoading ? (
                  <div className="space-y-4">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Skeleton key={i} className="h-40" />
                    ))}
                  </div>
                ) : works?.length ? (
                  view === 'list' ? (
                    <div className="space-y-3">
                      {works.map(work => (
                        <WorkCard key={work.id} work={work} />
                      ))}
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                      {works.map(work => (
                        <WorkCard key={work.id} work={work} grid />
                      ))}
                    </div>
                  )
                ) : (
                  <p className="text-center py-8 text-navy/70 dark:text-cream/70">
                    No works found for this author.
                  </p>
                )}

                {works && works.length > 5 && (
                  <div className="mt-6 text-center">
                    <Button 
                      variant="outline"
                      className="py-2 px-6 rounded-full bg-navy/10 hover:bg-navy/20 dark:bg-navy/20 dark:hover:bg-navy/30 text-navy dark:text-cream/90 font-sans font-medium text-sm transition-colors"
                    >
                      Load more works
                    </Button>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="translations" className="pt-6">
                <p className="text-center py-8 text-navy/70 dark:text-cream/70">
                  Translations by {author?.name} will appear here.
                </p>
              </TabsContent>

              <TabsContent value="timeline" className="pt-6">
                {timelineLoading ? (
                  <div className="space-y-4 py-8">
                    {Array.from({ length: 4 }).map((_, i) => (
                      <Skeleton key={i} className="h-16" />
                    ))}
                  </div>
                ) : timeline && timeline.length > 0 ? (
                  <AuthorTimeline events={timeline} />
                ) : (
                  <p className="text-center py-8 text-navy/70 dark:text-cream/70">
                    No timeline events available for this author.
                  </p>
                )}
              </TabsContent>

              <TabsContent value="about" className="pt-6">
                <div className="max-w-3xl mx-auto">
                  <h2 className="text-xl font-serif font-semibold mb-4">About {author?.name}</h2>
                  <div className="prose dark:prose-invert">
                    <p>{author?.biography}</p>
                    
                    {/* Additional content would go here in a real application */}
                    <p className="mt-4 text-navy/70 dark:text-cream/70">
                      Additional biographical information and context about the author would be displayed here,
                      including details about their life, work, influence, and literary contributions.
                    </p>
                  </div>
                </div>
              </TabsContent>

              <TabsContent value="discussions" className="pt-6">
                <p className="text-center py-8 text-navy/70 dark:text-cream/70">
                  Discussions about {author?.name} will appear here.
                </p>
              </TabsContent>
            </Tabs>
          )}
        </div>
      </section>
    </PageLayout>
  );
}
