"use client";

import { useState } from "react";
import Link from "next/link";
import { UserAvatar } from "@/components/user-avatar";
import { ThoughtList } from "@/components/thought-list";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ExternalLink, UserPlus, UserMinus } from "lucide-react";
import { followUser, unfollowUser, RemoteActor, Thought, Me, getActorFollowers, getActorFollowing, ActorConnection } from "@/lib/api";
import { RemoteUserCard } from "@/components/remote-user-card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import { useAuth } from "@/hooks/use-auth";

interface RemoteUserProfileProps {
  actor: RemoteActor;
  initialPosts: Thought[];
  me: Me | null;
  initialFollowed?: boolean;
}

export function RemoteUserProfile({
  actor,
  initialPosts,
  me,
  initialFollowed = false,
}: RemoteUserProfileProps) {
  const [followed, setFollowed] = useState(initialFollowed);
  const [loading, setLoading] = useState(false);
  const { token } = useAuth();

  type ConnectionTab = "posts" | "followers" | "following";
  const [activeTab, setActiveTab] = useState<ConnectionTab>("posts");
  const [followers, setFollowers] = useState<ActorConnection[]>([]);
  const [following, setFollowing] = useState<ActorConnection[]>([]);
  const [followersPage, setFollowersPage] = useState(1);
  const [followingPage, setFollowingPage] = useState(1);
  const [followersHasMore, setFollowersHasMore] = useState(false);
  const [followingHasMore, setFollowingHasMore] = useState(false);
  const [followersLoaded, setFollowersLoaded] = useState(false);
  const [followingLoaded, setFollowingLoaded] = useState(false);

  const handleFollow = async () => {
    if (!token) {
      toast.error("You must be logged in to follow users.");
      return;
    }
    setLoading(true);
    try {
      if (followed) {
        await unfollowUser(actor.handle, token);
        setFollowed(false);
      } else {
        await followUser(actor.handle, token);
        setFollowed(true);
        toast.success(`Follow request sent to ${actor.handle}`);
      }
    } catch {
      toast.error(
        followed ? "Failed to unfollow." : "Failed to send follow request.",
      );
    } finally {
      setLoading(false);
    }
  };

  const loadFollowers = async (page: number) => {
    const result = await getActorFollowers(actor.handle, page, token).catch(() => null);
    if (!result) return;
    setFollowers((prev) => (page === 1 ? result.items : [...prev, ...result.items]));
    setFollowersHasMore(result.hasMore);
    setFollowersLoaded(true);
    setFollowersPage(page);
  };

  const loadFollowing = async (page: number) => {
    const result = await getActorFollowing(actor.handle, page, token).catch(() => null);
    if (!result) return;
    setFollowing((prev) => (page === 1 ? result.items : [...prev, ...result.items]));
    setFollowingHasMore(result.hasMore);
    setFollowingLoaded(true);
    setFollowingPage(page);
  };

  const handleTabChange = (tab: string) => {
    setActiveTab(tab as ConnectionTab);
    if (tab === "followers" && !followersLoaded) loadFollowers(1);
    if (tab === "following" && !followingLoaded) loadFollowing(1);
  };

  const isOwnProfile = me?.username === actor.handle;

  return (
    <div>
      <div
        className="h-48 bg-muted bg-cover bg-center"
        style={{
          backgroundImage: actor.bannerUrl ? `url(${actor.bannerUrl})` : "none",
        }}
      />

      <main className="container mx-auto max-w-6xl p-4 -mt-16 grid grid-cols-1 lg:grid-cols-4 gap-8">
        <aside className="col-span-1 space-y-6">
          <div className="sticky top-20 space-y-6">
            <Card className="p-6 bg-card/80 backdrop-blur-lg">
              <div className="flex justify-between items-start">
                <div className="w-24 h-24 rounded-full border-4 border-background shrink-0">
                  <UserAvatar
                    src={actor.avatarUrl}
                    alt={actor.displayName}
                    className="w-full h-full"
                  />
                </div>
                {!isOwnProfile && token && (
                  <Button
                    onClick={handleFollow}
                    disabled={loading}
                    variant={followed ? "secondary" : "default"}
                    size="sm"
                  >
                    {followed ? (
                      <>
                        <UserMinus className="mr-2 h-4 w-4" /> Unfollow
                      </>
                    ) : (
                      <>
                        <UserPlus className="mr-2 h-4 w-4" /> Follow
                      </>
                    )}
                  </Button>
                )}
              </div>

              <div className="mt-4 min-w-0">
                <h1 className="text-2xl font-bold truncate">
                  {actor.displayName ?? actor.handle}
                </h1>
                <p className="text-sm text-muted-foreground truncate">
                  {actor.handle}
                </p>
              </div>

              {actor.bio && (
                <div
                  className="mt-4 text-sm [&_a]:underline [&_a]:text-primary [&_p]:mb-2"
                  dangerouslySetInnerHTML={{ __html: actor.bio }}
                />
              )}

              <Button
                asChild
                variant="outline"
                size="sm"
                className="mt-4 w-full"
              >
                <Link
                  href={actor.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center overflow-hidden"
                >
                  <ExternalLink className="mr-2 h-4 w-4 shrink-0" />
                  <span className="truncate">
                    {new URL(actor.url).hostname}
                  </span>
                </Link>
              </Button>

              {actor.alsoKnownAs && (
                <p className="mt-2 text-xs text-muted-foreground">
                  Also known as:{" "}
                  <Link
                    href={actor.alsoKnownAs}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="underline"
                  >
                    {actor.alsoKnownAs}
                  </Link>
                </p>
              )}

              {actor.attachment.length > 0 && (
                <div className="mt-4 space-y-0 text-sm">
                  {actor.attachment.map((field) => (
                    <div
                      key={field.name}
                      className="grid grid-cols-[minmax(0,5rem)_1fr] gap-2 border-t py-1"
                    >
                      <span className="font-medium text-muted-foreground truncate" title={field.name}>
                        {field.name}
                      </span>
                      <span
                        className="break-all min-w-0 [&_a]:underline [&_a]:text-primary"
                        dangerouslySetInnerHTML={{ __html: field.value }}
                      />
                    </div>
                  ))}
                </div>
              )}
            </Card>
          </div>
        </aside>

        <div className="col-span-1 lg:col-span-3">
          <Tabs defaultValue="posts" onValueChange={handleTabChange}>
            <TabsList>
              <TabsTrigger value="posts">Posts</TabsTrigger>
              <TabsTrigger value="followers">Followers</TabsTrigger>
              <TabsTrigger value="following">Following</TabsTrigger>
            </TabsList>

            <TabsContent value="posts" className="space-y-4 mt-4">
              {initialPosts.length > 0 ? (
                <ThoughtList
                  thoughts={initialPosts}
                  currentUser={me}
                />
              ) : (
                <Card className="flex items-center justify-center h-48">
                  <p className="text-center text-muted-foreground">
                    Posts are being fetched — check back soon.
                  </p>
                </Card>
              )}
            </TabsContent>

            <TabsContent value="followers" className="mt-4">
              {!followersLoaded ? (
                <Card className="flex items-center justify-center h-48">
                  <p className="text-center text-muted-foreground">Loading followers…</p>
                </Card>
              ) : followers.length === 0 ? (
                <Card className="flex items-center justify-center h-48">
                  <p className="text-center text-muted-foreground">
                    No followers cached yet — check back soon.
                  </p>
                </Card>
              ) : (
                <div className="space-y-2">
                  {followers.map((f) => (
                    <RemoteUserCard key={f.url} actor={f} />
                  ))}
                  {followersHasMore && (
                    <button
                      onClick={() => loadFollowers(followersPage + 1)}
                      className="w-full text-sm text-muted-foreground hover:text-foreground py-2"
                    >
                      Load more
                    </button>
                  )}
                </div>
              )}
            </TabsContent>

            <TabsContent value="following" className="mt-4">
              {!followingLoaded ? (
                <Card className="flex items-center justify-center h-48">
                  <p className="text-center text-muted-foreground">Loading following…</p>
                </Card>
              ) : following.length === 0 ? (
                <Card className="flex items-center justify-center h-48">
                  <p className="text-center text-muted-foreground">
                    No following cached yet — check back soon.
                  </p>
                </Card>
              ) : (
                <div className="space-y-2">
                  {following.map((f) => (
                    <RemoteUserCard key={f.url} actor={f} />
                  ))}
                  {followingHasMore && (
                    <button
                      onClick={() => loadFollowing(followingPage + 1)}
                      className="w-full text-sm text-muted-foreground hover:text-foreground py-2"
                    >
                      Load more
                    </button>
                  )}
                </div>
              )}
            </TabsContent>
          </Tabs>
        </div>
      </main>
    </div>
  );
}
