import { useParams, Link, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { FiArrowLeft, FiSettings, FiUser, FiCalendar, FiMapPin } from "react-icons/fi";
import { useQuery } from "@tanstack/react-query";
import { useApiSocialPostsList } from "@/api/generated/private/posts/posts";
import { useAuth } from "@/hooks/useAuth";
import { privateApi } from "@/api/privateClient";
import Avatar from "@/components/ui/Avatar";
import { mediaUrl } from "@/utils/mediaUrl";
import Post from "@/components/social/posts/Post";
import Spinner from "@/components/ui/Spinner";
import EmptyState from "@/components/ui/EmptyState";

function formatJoined(dateVal: Date | string | undefined): string {
  if (!dateVal) return "";
  const d = new Date(dateVal as string);
  return d.toLocaleDateString("cs-CZ", { year: "numeric", month: "long" });
}

export default function UserProfilePage() {
  const { username } = useParams<{ username: string }>();
  const { user: me } = useAuth();
  const { t } = useTranslation("social");
  const navigate = useNavigate();

  const { data: profile, isLoading: profileLoading } = useQuery({
    queryKey: ["account", "users", username],
    queryFn: () =>
      privateApi
        .get(`/api/account/users/`, { params: { username } })
        .then((r) => r.data?.results?.[0] ?? null),
    enabled: !!username,
  });

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

  const { data: postsData, isLoading: postsLoading } = useApiSocialPostsList(
    { author: profile?.id },
    { query: { enabled: !!profile?.id } },
  );

  const posts = postsData?.results ?? [];
  const p = profile as any;
  return (
    <div>
      {/* Sticky back-nav */}
      <header className="sticky top-0 z-20 flex items-center gap-3 bg-brand-bg/70 px-4 py-3 backdrop-blur">
        <button
          type="button"
          onClick={() => navigate(-1)}
          className="rounded-full p-1 text-brand-text hover:bg-brand-lines/10"
          aria-label={t("profile.back")}
        >
          <FiArrowLeft size={20} />
        </button>
        <h1 className="text-lg font-bold text-brand-text">
          {profileLoading ? "…" : profile ? `@${profile.username}` : t("profile.notFound")}
        </h1>
      </header>

      {profileLoading ? (
        <div className="flex justify-center py-12"><Spinner size={28} /></div>
      ) : !profile ? (
        <EmptyState icon={<FiUser />} title={t("profile.notFound")} />
      ) : (
        <>
          {/* Banner + avatar */}
          <div className="relative">
            {/* Banner */}
            <div className="h-36 w-full overflow-hidden bg-gradient-to-br from-brand-bgLight to-brand-lines/20">
              {p?.banner && (
                <img
                  src={mediaUrl(p.banner) ?? p.banner}
                  alt=""
                  className="h-full w-full object-cover"
                />
              )}
            </div>

            {/* Avatar — overlaps banner */}
            <div className="absolute -bottom-10 left-4">
              <div className="rounded-full ring-4 ring-brand-bg">
                <Avatar name={`${profile.first_name} ${profile.last_name}`} src={p?.avatar ?? null} size={80} />
              </div>
            </div>

            {/* Action buttons — top-right of banner area */}
            {isOwnProfile && (
              <div className="absolute bottom-3 right-4 flex items-center gap-2">
                <Link
                  to="/social/account/settings"
                  className="inline-flex items-center gap-1.5 rounded-full border border-brand-lines/30 bg-brand-bg/80 px-3 py-1.5 text-sm text-brand-text/80 backdrop-blur hover:bg-brand-lines/10 transition-colors"
                >
                  <FiSettings size={16} /> {t("profile.editProfile")}
                </Link>
              </div>
            )}
          </div>

          {/* Profile info */}
          <div className="border-b border-brand-lines/10 px-4 pb-4 pt-12">
            <div className="text-xl font-bold text-brand-text">{profile.first_name} {profile.last_name}</div>
            <div className="text-sm text-brand-text/50">@{profile.username}</div>

            <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-brand-text/40">
              {p?.city && (
                <span className="flex items-center gap-1">
                  <FiMapPin size={12} /> {p.city}
                </span>
              )}
              {p?.create_time && (
                <span className="flex items-center gap-1">
                  <FiCalendar size={12} />
                  {t("profile.joined", { date: formatJoined(p.create_time) })}
                </span>
              )}
            </div>
          </div>

          {/* Posts */}
          <div>
            {postsLoading ? (
              <div className="flex justify-center py-8"><Spinner size={22} /></div>
            ) : posts.length === 0 ? (
              <EmptyState message={t("profile.noPosts")} />
            ) : (
              posts.map((post) => (
                <Post
                  key={post.id}
                  post={post}
                  onReplyClick={() => navigate(`/social/post/${post.id}`)}
                />
              ))
            )}
          </div>
        </>
      )}
    </div>
  );
}
