"use client";

import React, { useMemo, useState } from "react";
import {
  useGetAnswerListQuery,
  useGetQuestionListQuery,
} from "@/api/seaqa.api";
import { useGetFollowersQuery, useGetFollowingQuery } from "@/api/auth.api";
import type {
  IFollowUser,
  IFollowerItem,
  IFollowingItem,
  IUserProfile,
} from "@/api/types/auth";
import Avatar from "@/components/common/Avatar";
import UserCard from "@/components/Connections/UserCard";
import ConnectionCardSkeleton from "@/components/skeleton/ConnectionCardSkeleton";
import {
  AnswerRow,
  EmptyState,
  Paginator,
  QuestionRow,
  SkeletonList,
} from "@/components/MyContent/contentShared";

interface UserPublicProfileProps {
  userId: number;
  userProfile: IUserProfile;
}

const PER_PAGE = 10;
const CONNECTIONS_PER_PAGE = 12;

type Tab = "questions" | "answers" | "followers" | "following";

// Public, read-only view of another member's profile: their approved questions
// and published answers, plus their followers / following connection lists (no
// drafts, no bookmarks, no edit controls).
const UserPublicProfile = ({ userId, userProfile }: UserPublicProfileProps) => {
  const [tab, setTab] = useState<Tab>("questions");
  const [questionPage, setQuestionPage] = useState(1);
  const [answerPage, setAnswerPage] = useState(1);
  const [followerPage, setFollowerPage] = useState(1);
  const [followingPage, setFollowingPage] = useState(1);

  const refetchOpts = { refetchOnMountOrArgChange: true } as const;

  const { data: questionData, isLoading: isQuestionLoading } =
    useGetQuestionListQuery(
      {
        userId,
        status: "approved",
        page: questionPage,
        perPage: PER_PAGE,
        sortBy: "id",
        sortDirection: "desc",
      },
      refetchOpts,
    );

  const { data: answerData, isLoading: isAnswerLoading } =
    useGetAnswerListQuery(
      {
        userId,
        status: "published",
        includeQuestion: true,
        page: answerPage,
        perPage: PER_PAGE,
        sortBy: "id",
        sortDirection: "desc",
      },
      refetchOpts,
    );

  const { data: followerData, isLoading: isFollowerLoading } =
    useGetFollowersQuery(
      { id: userId, page: followerPage, perPage: CONNECTIONS_PER_PAGE },
      { skip: tab !== "followers" },
    );

  const { data: followingData, isLoading: isFollowingLoading } =
    useGetFollowingQuery(
      { id: userId, page: followingPage, perPage: CONNECTIONS_PER_PAGE },
      { skip: tab !== "following" },
    );

  const questions = questionData?.data ?? [];
  const answers = answerData?.data ?? [];

  const followers = useMemo<IFollowUser[]>(
    () => (followerData?.data ?? []).map((i: IFollowerItem) => i.follower),
    [followerData],
  );
  const following = useMemo<IFollowUser[]>(
    () => (followingData?.data ?? []).map((i: IFollowingItem) => i.following),
    [followingData],
  );

  const questionCount = questionData?.totalRecords ?? 0;
  const answerCount = answerData?.totalRecords ?? 0;
  // Counts on the profile object are always available; fall back to the live
  // list totals once the tab has loaded.
  const followerCount =
    followerData?.totalRecords ?? userProfile.followersCount ?? 0;
  const followingCount =
    followingData?.totalRecords ?? userProfile.followingCount ?? 0;

  const TABS: { key: Tab; label: string; count: number }[] = [
    { key: "questions", label: "Questions", count: questionCount },
    { key: "answers", label: "Answers", count: answerCount },
    { key: "followers", label: "Followers", count: followerCount },
    { key: "following", label: "Following", count: followingCount },
  ];

  const subtitle = [userProfile.rank?.name, userProfile.presentCompany]
    .filter(Boolean)
    .join(" · ");

  return (
    <div className="flex flex-col gap-5 font-system">
      {/* Profile card + tabs (read-only — no Edit Profile) */}
      <div className="bg-white rounded-2xl border border-[#E2E2E2] overflow-hidden">
        <div className="p-6 space-y-4">
          <div className="flex items-center gap-4">
            <Avatar
              src={userProfile.profileImage?.filePath}
              name={userProfile.name || "User"}
              size="2xl"
            />
            <div className="flex-1 min-w-0">
              <p className="text-lg font-bold text-coolgray-900 leading-tight truncate">
                {userProfile.name}
              </p>
              {subtitle && (
                <p className="text-sm text-coolgray-500 mt-0.5 truncate">
                  {subtitle}
                </p>
              )}
            </div>
          </div>

          {userProfile.aboutMe && (
            <p className="text-sm text-coolgray-500 leading-relaxed whitespace-pre-line">
              {userProfile.aboutMe}
            </p>
          )}
        </div>

        <div className="border-t border-gray-100" />

        <div className="flex">
          {TABS.map((t) => {
            const active = tab === t.key;
            return (
              <button
                key={t.key}
                type="button"
                onClick={() => setTab(t.key)}
                className={`flex-1 flex flex-col items-center py-3 text-xs font-semibold transition-all border-b-2 ${
                  active
                    ? "border-blue-light text-coolgray-900"
                    : "border-transparent text-coolgray-500 hover:text-coolgray-700"
                }`}
              >
                <span className="text-base font-bold text-coolgray-900">
                  {t.count}
                </span>
                <span className="leading-tight text-center">{t.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Lists */}
      {tab === "questions" &&
        (isQuestionLoading ? (
          <SkeletonList />
        ) : questions.length === 0 ? (
          <EmptyState label="questions" />
        ) : (
          <>
            <div className="bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-gray-100 overflow-hidden">
              {questions.map((q) => (
                <QuestionRow key={q.id} q={q} />
              ))}
            </div>
            <Paginator
              totalPages={questionData?.totalPages ?? 1}
              currentPage={questionPage}
              onChange={setQuestionPage}
            />
          </>
        ))}

      {tab === "answers" &&
        (isAnswerLoading ? (
          <SkeletonList />
        ) : answers.length === 0 ? (
          <EmptyState label="answers" />
        ) : (
          <>
            <div className="bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-gray-100 overflow-hidden">
              {answers.map((a) => (
                <AnswerRow key={a.id} answer={a} />
              ))}
            </div>
            <Paginator
              totalPages={answerData?.totalPages ?? 1}
              currentPage={answerPage}
              onChange={setAnswerPage}
            />
          </>
        ))}

      {tab === "followers" &&
        (isFollowerLoading ? (
          <ConnectionGridSkeleton />
        ) : followers.length === 0 ? (
          <EmptyState label="followers" message="No followers yet" cta={null} />
        ) : (
          <>
            <div className="grid md:grid-cols-2 gap-4">
              {followers.map((u) => (
                <UserCard key={u.id} user={u} />
              ))}
            </div>
            <Paginator
              totalPages={followerData?.totalPages ?? 1}
              currentPage={followerPage}
              onChange={setFollowerPage}
            />
          </>
        ))}

      {tab === "following" &&
        (isFollowingLoading ? (
          <ConnectionGridSkeleton />
        ) : following.length === 0 ? (
          <EmptyState
            label="following"
            message="Not following anyone yet"
            cta={null}
          />
        ) : (
          <>
            <div className="grid md:grid-cols-2 gap-4">
              {following.map((u) => (
                <UserCard key={u.id} user={u} />
              ))}
            </div>
            <Paginator
              totalPages={followingData?.totalPages ?? 1}
              currentPage={followingPage}
              onChange={setFollowingPage}
            />
          </>
        ))}
    </div>
  );
};

// Two-column skeleton grid that mirrors the followers/following card layout.
const ConnectionGridSkeleton = () => (
  <div className="grid grid-cols-2 gap-4">
    {Array.from({ length: 4 }).map((_, i) => (
      <ConnectionCardSkeleton key={i} />
    ))}
  </div>
);

export default UserPublicProfile;
