"use client";

import React, { useEffect, useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import ReactPaginate from "react-paginate";
import { ChevronLeft, ChevronRight, Lock, Search } from "lucide-react";
import { useAppSelector } from "@/redux/hooks";
import LoginModal from "@/components/Membership/LoginModal";
import {
  useGetFollowersQuery,
  useGetFollowingQuery,
  useGetExploreUsersQuery,
} from "@/api/auth.api";
import {
  IFollowUser,
  IFollowerItem,
  IFollowingItem,
  IExploreUser,
} from "@/api/types/auth";
import ConnectionCardSkeleton from "@/components/skeleton/ConnectionCardSkeleton";
import UserCard from "@/components/Connections/UserCard";

const PER_PAGE = 20;

type Tab = "followers" | "following" | "explore";

// The explore endpoint returns a leaner user shape; normalise it to the
// IFollowUser the card expects (counts default to 0; `isFollowing` drives the
// follow/unfollow button state).
function mapExploreUser(u: IExploreUser): IFollowUser {
  return {
    id: u.id,
    onlineStatus: 0,
    name: u.userProfile?.name ?? "",
    profileImage: u.userProfile?.profileImage ?? null,
    isFollowedByMe: u.isFollowing ?? false,
    userProfile: {
      name: u.userProfile?.name ?? "",
      followersCount: u.userProfile?.followersCount ?? u.followersCount ?? 0,
      followingCount: u.userProfile?.followingCount ?? u.followingCount ?? 0,
      rank: u.userProfile?.rank ?? null,
    },
  };
}

// ── Main Page ─────────────────────────────────────────────────────────────────────
export default function ConnectionsPage() {
  const [tab, setTab] = useState<Tab>("followers");
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const { user, isAuthenticated } = useAppSelector((state) => state.auth);
  const userId = user?.id ?? "";
  const router = useRouter();
  const pathname = usePathname();
  const [loginModalOpen, setLoginModalOpen] = useState(false);

  // Debounce the input, then reset to the first page so the server-side search
  // starts from the top of the result set.
  useEffect(() => {
    const t = setTimeout(() => {
      setDebouncedSearch(search.trim());
      setPage(1);
    }, 400);
    return () => clearTimeout(t);
  }, [search]);

  const searchText = debouncedSearch || undefined;

  const {
    data: followersData,
    isLoading: loadingFollowers,
    isFetching: fetchingFollowers,
  } = useGetFollowersQuery(
    { id: userId, page, perPage: PER_PAGE, searchText },
    { skip: !isAuthenticated || !userId || tab !== "followers" },
  );

  const {
    data: followingData,
    isLoading: loadingFollowing,
    isFetching: fetchingFollowing,
  } = useGetFollowingQuery(
    { id: userId, page, perPage: PER_PAGE, searchText },
    { skip: !isAuthenticated || !userId || tab !== "following" },
  );

  const {
    data: exploreData,
    isLoading: loadingExplore,
    isFetching: fetchingExplore,
  } = useGetExploreUsersQuery(
    { page, perPage: PER_PAGE, searchText },
    { skip: !isAuthenticated || tab !== "explore" },
  );

  const isLoading =
    tab === "followers"
      ? loadingFollowers
      : tab === "following"
        ? loadingFollowing
        : loadingExplore;
  const isFetching =
    tab === "followers"
      ? fetchingFollowers
      : tab === "following"
        ? fetchingFollowing
        : fetchingExplore;

  const items = useMemo<IFollowUser[]>(() => {
    let list: IFollowUser[];
    if (tab === "followers") {
      list = (followersData?.data ?? []).map((i: IFollowerItem) => i.follower);
    } else if (tab === "following") {
      list = (followingData?.data ?? []).map(
        (i: IFollowingItem) => i.following,
      );
    } else {
      list = (exploreData?.data ?? []).map(mapExploreUser);
    }
    // Never show the currently logged-in user in any listing.
    return list.filter((u) => String(u.id) !== String(userId));
  }, [tab, followersData, followingData, exploreData, userId]);

  const activeData =
    tab === "followers"
      ? followersData
      : tab === "following"
        ? followingData
        : exploreData;
  const totalPages = activeData?.totalPages ?? 1;
  const totalRecords = activeData?.totalRecords ?? 0;

  const handleTabChange = (next: Tab) => {
    if (next === tab) return;
    setTab(next);
    setPage(1);
    setSearch("");
    setDebouncedSearch("");
  };

  const TABS: { key: Tab; label: string }[] = [
    { key: "followers", label: "Followers" },
    { key: "following", label: "Following" },
    { key: "explore", label: "Explore" },
  ];

  // Guests don't get the connections feed — no listing API is fired for them
  // (all queries above are skipped while unauthenticated). Show a sign-in gate
  // instead. "Create account" returns the user here after registering.
  if (!isAuthenticated) {
    return (
      <div className="w-full min-h-180.5 h-screen px-6  flex flex-col justify-center items-center bg-[#efefef]">
        <div className="max-w-96 flex flex-col justify-start items-center gap-5">
          {/* Lock badge */}
          <div className="size-16 bg-blue-50 rounded-full outline outline-1 outline-offset-[-1px] outline-blue-100 inline-flex justify-center items-center">
            <Lock className="size-7 text-blue-400" strokeWidth={2.33} />
          </div>

          {/* Text */}
          <div className="flex flex-col justify-start items-start gap-[2.75px]">
            <div className="self-stretch flex flex-col justify-start items-center">
              <h2 className="text-center text-[#101828] text-xl font-bold leading-7">
                Subscribers Only
              </h2>
            </div>
            <div className="self-stretch flex flex-col justify-start items-center">
              <p className="text-center text-[#6a7282] text-sm font-normal leading-6">
                The Connections section is available to registered
                <br className="hidden sm:block" />
                members only. Sign in or create a free account to explore
                <br className="hidden sm:block" />
                and follow other maritime professionals.
              </p>
            </div>
          </div>

          {/* Actions */}
          <div className="pt-1 flex flex-col justify-start items-start">
            <div className="inline-flex justify-start items-center gap-3">
              <button
                type="button"
                onClick={() => setLoginModalOpen(true)}
                className="px-5 py-2.5 bg-blue-500 rounded-2xl shadow-[0px_1px_3px_0px_rgba(0,0,0,0.10),0px_1px_2px_-1px_rgba(0,0,0,0.10)] text-white text-sm font-semibold leading-5 hover:bg-blue-600 transition-colors cursor-pointer"
              >
                Sign in
              </button>
              <button
                type="button"
                onClick={() =>
                  router.push(
                    `/signup?redirect=${encodeURIComponent(pathname)}`,
                  )
                }
                className="px-5 py-2.5 rounded-2xl outline outline-1 outline-offset-[-1px] outline-[var(--color-gray-235)] text-[#364153] text-sm font-semibold leading-5 hover:bg-gray-50 transition-colors cursor-pointer"
              >
                Create account
              </button>
            </div>
          </div>
        </div>

        <LoginModal
          isOpen={loginModalOpen}
          onClose={() => setLoginModalOpen(false)}
        />
      </div>
    );
  }

  return (
    <div className="min-h-[50vh] lg:min-h-screen">
      {/* ── Tab bar + search ─────────────────────────────────────────────────── */}
      <div
        style={{ maxWidth: 1100, margin: "0 auto" }}
        className="px-6 pt-8 pb-5"
      >
        <div className="flex items-center justify-between gap-4 flex-col md:flex-row">
          {/* Tabs */}
          <div className="flex items-center gap-1 bg-white rounded-xl border border-[#e5e7eb] p-1 shadow-sm">
            {TABS.map((t) => (
              <button
                key={t.key}
                type="button"
                onClick={() => handleTabChange(t.key)}
                className={`px-5 py-2 rounded-lg text-sm font-semibold transition-all ${
                  tab === t.key
                    ? "bg-blue-500 text-white shadow-sm"
                    : "text-[#6b7280] hover:text-[#1f2937]"
                }`}
              >
                {t.label}
                {tab === t.key && totalRecords > 0 && (
                  <span className="ml-1.5 text-xs opacity-80">
                    ({totalRecords})
                  </span>
                )}
              </button>
            ))}
          </div>

          {/* Search */}
          <div className="relative flex-1 w-full md:max-w-xs">
            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-[#9ca3af] pointer-events-none" />
            <input
              type="text"
              placeholder="Search by name"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full text-sm border border-[#e5e7eb] rounded-xl pl-10 pr-4 py-2.5 bg-white focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent placeholder:text-[#d1d5db] transition shadow-sm"
            />
          </div>
        </div>
      </div>

      {/* ── Grid ─────────────────────────────────────────────────────────────── */}
      <div className="px-6 pb-12">
        <div
          className={`grid gap-5 transition-opacity ${
            isFetching ? "opacity-60" : "opacity-100"
          }`}
          style={{
            maxWidth: 1100,
            margin: "0 auto",
            gridTemplateColumns: "repeat(auto-fill, minmax(230px, 1fr))",
          }}
        >
          {isLoading ? (
            Array.from({ length: 8 }).map((_, i) => (
              <ConnectionCardSkeleton key={i} />
            ))
          ) : items.length === 0 ? (
            <div className="col-span-full text-center py-16">
              <p className="text-sm text-[#9ca3af]">
                {debouncedSearch
                  ? "No users match your search."
                  : tab === "explore"
                    ? "No users found."
                    : `No ${tab} yet.`}
              </p>
            </div>
          ) : (
            items.map((u) => <UserCard key={u.id} user={u} />)
          )}
        </div>

        {/* ── Pagination ──────────────────────────────────────────────────── */}
        {!isLoading && totalPages > 1 && (
          <div style={{ maxWidth: 1100, margin: "0 auto" }}>
            <ReactPaginate
              pageCount={totalPages}
              pageRangeDisplayed={3}
              marginPagesDisplayed={1}
              forcePage={page - 1}
              onPageChange={({ selected }) => setPage(selected + 1)}
              previousLabel={<ChevronLeft size={15} strokeWidth={2} />}
              nextLabel={<ChevronRight size={15} strokeWidth={2} />}
              breakLabel="…"
              containerClassName="flex items-center justify-center gap-1.5 mt-8"
              pageClassName="flex"
              pageLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-[#e5e7eb] text-[#6b7280] text-[14px] font-semibold hover:bg-[#f3f4f6] transition-colors cursor-pointer"
              activeClassName="[&>a]:bg-blue-500 [&>a]:text-white [&>a]:border-blue-500"
              previousClassName="flex"
              previousLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-[#e5e7eb] text-[#6b7280] hover:bg-[#f3f4f6] transition-colors cursor-pointer"
              nextClassName="flex"
              nextLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-[#e5e7eb] text-[#6b7280] hover:bg-[#f3f4f6] transition-colors cursor-pointer"
              breakClassName="flex"
              breakLinkClassName="w-8 h-8 flex items-center justify-center text-[#9ca3af] text-[14px]"
              disabledClassName="opacity-40 pointer-events-none"
            />
          </div>
        )}
      </div>
    </div>
  );
}
