import { createFileRoute, Link } from "@tanstack/react-router";
import { ArrowRight, Layers, Store, Users } from "lucide-react";
import { useEffect, useState } from "react";
import { Composer } from "@/components/feed/composer";
import { PostCard } from "@/components/feed/post-card";
import { AppShell } from "@/components/layout/app-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { useCurrentUserState } from "@/lib/auth/use-current-user";
import { listFeed, listMyCards } from "@/lib/server/api";
import type { CardItem, PostItem } from "@/lib/types";

export const Route = createFileRoute("/")({
  component: HomePage,
});

function HomePage() {
  const { user, isPending } = useCurrentUserState();
  const [posts, setPosts] = useState<PostItem[] | null>(null);
  const [myCards, setMyCards] = useState<CardItem[]>([]);

  useEffect(() => {
    let cancelled = false;
    void listFeed()
      .then((p) => {
        if (!cancelled) setPosts(p);
      })
      .catch(() => {
        if (!cancelled) setPosts([]);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (!user) {
      setMyCards([]);
      return;
    }
    let cancelled = false;
    void listMyCards()
      .then((c) => {
        if (!cancelled) setMyCards(c);
      })
      .catch(() => {
        if (!cancelled) setMyCards([]);
      });
    return () => {
      cancelled = true;
    };
  }, [user?.id]);

  return (
    <AppShell>
      {!isPending && !user ? <Landing /> : null}

      <div className="mx-auto max-w-xl space-y-4">
        {user && (
          <>
            <div className="flex items-end justify-between gap-3">
              <div>
                <h1 className="font-display text-4xl tracking-wide">Feed</h1>
                <p className="text-sm text-muted">Minting, pulls, and trade talk.</p>
              </div>
              <Button asChild variant="secondary" size="sm">
                <Link to="/create">Mint card</Link>
              </Button>
            </div>
            <Composer
              myCards={myCards}
              onPosted={(post) => setPosts((prev) => [post, ...(prev ?? [])])}
            />
          </>
        )}

        {posts === null ? (
          <div className="space-y-3">
            <Skeleton className="h-40 w-full" />
            <Skeleton className="h-40 w-full" />
          </div>
        ) : posts.length === 0 ? (
          <Card>
            <CardContent className="py-12 text-center space-y-3">
              <p className="font-medium">The feed is quiet</p>
              <p className="text-sm text-muted max-w-sm mx-auto">
                {user
                  ? "Mint a card or post something — every new card can announce to the feed."
                  : "Sign in to mint cards, post, and start trading with collectors."}
              </p>
              {user ? (
                <Button asChild>
                  <Link to="/create">Create your first card</Link>
                </Button>
              ) : (
                <Button asChild>
                  <Link to="/signup">Join Dugout</Link>
                </Button>
              )}
            </CardContent>
          </Card>
        ) : (
          posts.map((p) => <PostCard key={p.id} post={p} signedIn={Boolean(user)} />)
        )}
      </div>
    </AppShell>
  );
}

function Landing() {
  return (
    <section className="mb-10 overflow-hidden rounded-[var(--radius-2xl)] border border-border bg-surface relative">
      <div
        className="absolute inset-0 opacity-40"
        style={{
          background:
            "radial-gradient(ellipse 80% 60% at 20% 0%, color-mix(in oklab, var(--color-accent) 35%, transparent), transparent 60%), radial-gradient(ellipse 50% 40% at 90% 80%, color-mix(in oklab, var(--color-diamond) 20%, transparent), transparent 50%)",
        }}
      />
      <div className="relative px-6 py-10 sm:px-10 sm:py-14 grid gap-8 lg:grid-cols-[1.2fr_1fr] lg:items-center">
        <div className="space-y-5">
          <p className="text-xs font-semibold uppercase tracking-[0.2em] text-accent">
            Social card platform
          </p>
          <h1 className="font-display text-5xl sm:text-6xl md:text-7xl leading-[0.95] tracking-wide text-balance">
            Collect. Post. Trade.
          </h1>
          <p className="text-muted max-w-md text-base leading-relaxed">
            Dugout is a social network built around digital baseball cards. Create your account,
            upload player photos, mint cards, share them on the feed, and trade with other
            collectors.
          </p>
          <div className="flex flex-wrap gap-3">
            <Button asChild size="lg">
              <Link to="/signup">
                Get started <ArrowRight className="h-4 w-4" />
              </Link>
            </Button>
            <Button asChild variant="secondary" size="lg">
              <Link to="/marketplace">Browse market</Link>
            </Button>
          </div>
        </div>
        <div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-1">
          <Feature
            icon={<Layers className="h-5 w-5 text-accent" />}
            title="Mint cards"
            body="Upload a photo, set team, position, rarity, and stats."
          />
          <Feature
            icon={<Users className="h-5 w-5 text-accent" />}
            title="Social feed"
            body="Post pulls, like, comment, and follow other collectors."
          />
          <Feature
            icon={<Store className="h-5 w-5 text-accent" />}
            title="Peer trades"
            body="Propose card-for-card swaps and accept deals in-app."
          />
        </div>
      </div>
    </section>
  );
}

function Feature({
  icon,
  title,
  body,
}: {
  icon: React.ReactNode;
  title: string;
  body: string;
}) {
  return (
    <div className="rounded-[var(--radius-lg)] border border-border bg-bg/50 p-4 backdrop-blur-sm">
      <div className="mb-2">{icon}</div>
      <h3 className="font-semibold text-sm">{title}</h3>
      <p className="text-xs text-muted mt-1 leading-relaxed">{body}</p>
    </div>
  );
}
