"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 } from "@/lib/api";
import { toast } from "sonner";
import { useAuth } from "@/hooks/use-auth";

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

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

  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 isOwnProfile = me?.username === actor.handle;

  const authorDetails = new Map<string, { avatarUrl?: string | null }>();
  initialPosts.forEach((t) => {
    authorDetails.set(t.author.username, { avatarUrl: actor.avatarUrl });
  });

  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">
                <h1 className="text-2xl font-bold">
                  {actor.displayName ?? actor.handle}
                </h1>
                <p className="text-sm text-muted-foreground">{actor.handle}</p>
              </div>

              {actor.bio && (
                <p className="mt-4 text-sm whitespace-pre-wrap">{actor.bio}</p>
              )}

              <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 && (
                <table className="mt-4 w-full text-sm border-collapse">
                  <tbody>
                    {actor.attachment.map((field) => (
                      <tr key={field.name} className="border-t">
                        <td className="py-1 pr-2 font-medium text-muted-foreground">
                          {field.name}
                        </td>
                        <td
                          className="py-1"
                          dangerouslySetInnerHTML={{ __html: field.value }}
                        />
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </Card>
          </div>
        </aside>

        <div className="col-span-1 lg:col-span-3 space-y-4">
          {initialPosts.length > 0 ? (
            <ThoughtList
              thoughts={initialPosts}
              authorDetails={authorDetails}
              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>
          )}
        </div>
      </main>
    </div>
  );
}
