"use client";

import React, { useState } from "react";
import Link from "next/link";

import { useFollowUserMutation } from "@/api/auth.api";
import { IFollowUser } from "@/api/types/auth";
import { useAppSelector } from "@/redux/hooks";
import Avatar from "@/components/common/Avatar";

// Shared connection card used by the Connections directory and the
// Followers/Following tabs on a member's profile. Tapping the card opens that
// member's public profile; the Follow button toggles independently.
function UserCard({ user }: { user: IFollowUser }) {
  const [followUser, { isLoading }] = useFollowUserMutation();
  const { user: currentUser } = useAppSelector((state) => state.auth);
  // Never show a Follow button on your own card.
  const isSelf = String(currentUser?.id) === String(user.id);
  // Drive the button purely off the server's `isFollowedByMe` flag, with an
  // optimistic override that flips while the mutation is in flight.
  const [followedOverride, setFollowedOverride] = useState<boolean | null>(
    null,
  );
  const followed = followedOverride ?? user.isFollowedByMe;

  const handleToggle = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    const next = !followed;
    setFollowedOverride(next);
    try {
      await followUser(user.id).unwrap();
    } catch {
      setFollowedOverride(!next);
    }
  };

  const followers = user.userProfile?.followersCount ?? 0;
  const following = user.userProfile?.followingCount ?? 0;

  return (
    <Link
      href={`/user-profile?userId=${user.id}`}
      className="relative bg-white rounded-2xl border border-[#E2E2E2] hover:shadow-md transition-all flex flex-col items-center text-center p-6 gap-3 h-full no-underline"
    >
      {/* Avatar */}
      <Avatar src={user.profileImage?.filePath} name={user.name} size="xl" />

      {/* Name + rank */}
      <div>
        <p className="text-base font-bold text-[#111827] leading-tight">
          {user.name}
        </p>
        {user.userProfile?.rank?.name && (
          <p className="text-sm text-[#6b7280] mt-0.5">
            {user.userProfile.rank.name}
          </p>
        )}
      </div>

      {/* Stats */}
      <div className="mt-auto flex items-center gap-6 py-2 border-t border-b border-[#f3f4f6] w-full justify-center">
        <div className="flex flex-col items-center">
          <span className="text-sm font-bold text-[#111827]">
            {followers.toLocaleString()}
          </span>
          <span className="text-[11px] text-[#9ca3af] uppercase tracking-wide mt-0.5">
            Followers
          </span>
        </div>
        <div className="w-px h-8 bg-[#f3f4f6]" />
        <div className="flex flex-col items-center">
          <span className="text-sm font-bold text-[#111827]">
            {following.toLocaleString()}
          </span>
          <span className="text-[11px] text-[#9ca3af] uppercase tracking-wide mt-0.5">
            Following
          </span>
        </div>
      </div>

      {/* Follow button — hidden on your own card */}
      {!isSelf && (
        <button
          type="button"
          onClick={handleToggle}
          disabled={isLoading}
          className={`px-8 py-1.5 rounded-xl text-sm font-semibold transition-all disabled:opacity-60 ${
            followed
              ? "bg-[#f3f4f6] text-[#4b5563] hover:bg-red-50 hover:text-red-500 border border-[#e5e7eb]"
              : "bg-white border border-blue-500 text-blue-500 hover:bg-blue-50"
          }`}
        >
          {followed ? "Following" : "Follow"}
        </button>
      )}
    </Link>
  );
}

export default UserCard;
