"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useAppSelector } from "@/store/hooks";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { API_ENDPOINTS } from "@/lib/constants/apiEndpoints";
import type { FeedItem, FeedContentItem } from "@/types/api/feeds.types";

// ── Helpers ───────────────────────────────────────────────────────────────────
function isValidImg(u?: string) { return !!u && !u.includes("no_img"); }
function fmtTime(d: string) {
  const diff = Date.now() - new Date(d).getTime();
  const m = Math.floor(diff / 60_000);
  const h = Math.floor(m / 60);
  if (m < 1) return "just now";
  if (m < 60) return `${m}m ago`;
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}
function fmtDate(d: string) {
  return new Date(d).toLocaleDateString("en-IN", { month: "short", year: "numeric" });
}
function getInitial(name: string) { return (name || "U").charAt(0).toUpperCase(); }

// ── Media Grid ────────────────────────────────────────────────────────────────
function MediaGrid({ items }: { items: FeedContentItem[] }) {
  if (!items.length) return null;
  const visible = items.slice(0, 4);
  const count = visible.length;
  const cols = count === 1 ? "1fr" : "1fr 1fr";
  return (
    <div style={{ display: "grid", gridTemplateColumns: cols, gap: 3, borderRadius: 10, overflow: "hidden", marginTop: "0.875rem" }}>
      {visible.map((item, idx) => (
        <div key={item.id} style={{
          position: "relative", overflow: "hidden", background: "#111",
          minHeight: count === 1 ? 260 : count === 3 && idx === 0 ? 190 : 140,
          gridColumn: count === 3 && idx === 0 ? "1 / span 2" : undefined,
        }}>
          {item.content_type === 2 && item.video
            ? <video src={item.video} controls playsInline style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
            : isValidImg(item.image)
              ? <Image src={item.image} alt="" fill sizes="400px" style={{ objectFit: "cover" }} unoptimized />
              : <div style={{ position: "absolute", inset: 0, background: "linear-gradient(135deg,#1e1e2e,#111)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="8.5" cy="8.5" r="1.5" /><path d="M21 15l-5-5L5 21" /></svg>
                </div>
          }
          {idx === 3 && items.length > 4 && (
            <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.65)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ color: "#fff", fontWeight: 800, fontSize: "1.5rem", fontFamily: "var(--mono)" }}>+{items.length - 4}</span>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// ── Feed Post Card ────────────────────────────────────────────────────────────
function PostCard({ feed, loggedInUserId }: { feed: FeedItem; loggedInUserId: number }) {
  const [liked, setLiked] = useState(feed.is_user_like === 1);
  const [likeCount, setLikeCount] = useState(feed.total_like);

  async function handleLike() {
    if (!loggedInUserId) return;
    const next = !liked;
    setLiked(next);
    setLikeCount((c) => c + (next ? 1 : -1));
    try {
      const { default: api } = await import("@/services/api.client");
      await api.post(API_ENDPOINTS.LIKE_UNLIKE, { user_id: loggedInUserId, type: 6, content_id: feed.id, video_id: 0 });
    } catch {
      setLiked(!next);
      setLikeCount((c) => c + (!next ? 1 : -1));
    }
  }

  return (
    <article style={{
      background: "#fff",
      border: "1px solid #e8e8e8",
      borderRadius: 14,
      padding: "1.125rem 1.25rem",
      marginBottom: "1rem",
      boxShadow: "0 1px 3px rgba(0,0,0,0.04)",
      transition: "box-shadow 0.2s",
    }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", gap: "0.625rem", marginBottom: "0.625rem" }}>
        <div style={{
          width: 36, height: 36, borderRadius: "50%", overflow: "hidden",
          background: "rgba(193,39,45,0.07)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, position: "relative",
        }}>
          {isValidImg(feed.user_image)
            ? <Image src={feed.user_image!} alt="" fill style={{ objectFit: "cover" }} unoptimized />
            : <span style={{ fontWeight: 800, fontSize: 13, color: "var(--brand, #C1272D)" }}>{getInitial(feed.user_name ?? "")}</span>
          }
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: "0.875rem", color: "#0e0e11", lineHeight: 1.2 }}>
            {feed.user_name ?? "User"}
            {feed.is_verified === 1 && (
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 4, verticalAlign: "middle" }}>
                <circle cx="12" cy="12" r="12" fill="#C1272D" />
                <path d="M7 12l3 3 7-7" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" />
              </svg>
            )}
          </div>
          <div style={{ fontFamily: "var(--mono, monospace)", fontSize: "0.6875rem", color: "#9ca3af", marginTop: 1 }}>{fmtTime(feed.created_at)}</div>
        </div>
      </div>

      {/* Title + body */}
      {feed.title && <p style={{ margin: "0 0 0.375rem", fontWeight: 700, fontSize: "0.9375rem", color: "#0e0e11", lineHeight: 1.4 }}>{feed.title}</p>}
      {feed.description && <p style={{ margin: 0, fontSize: "0.875rem", color: "#4b5563", lineHeight: 1.55 }}>{feed.description}</p>}

      {/* Hashtags */}
      {feed.hasteg?.length > 0 && (
        <div style={{ display: "flex", flexWrap: "wrap", gap: "0.375rem", marginTop: "0.5rem" }}>
          {feed.hasteg.map((h) => (
            <span key={h.id} style={{ fontSize: "0.75rem", fontWeight: 600, color: "var(--brand, #C1272D)", background: "rgba(193,39,45,0.07)", padding: "2px 8px", borderRadius: 20 }}>
              #{h.name}
            </span>
          ))}
        </div>
      )}

      {/* Media */}
      <MediaGrid items={feed.feed_content} />

      {/* Actions */}
      <div style={{ display: "flex", alignItems: "center", gap: "1.25rem", marginTop: "0.875rem", paddingTop: "0.75rem", borderTop: "1px solid #f3f4f6" }}>
        <button
          onClick={handleLike}
          style={{ display: "flex", alignItems: "center", gap: "0.375rem", background: "none", border: "none", cursor: "pointer", padding: 0, fontSize: "0.8125rem", fontWeight: 600, color: liked ? "var(--brand, #C1272D)" : "#6b7280", transition: "color 0.15s" }}
        >
          <svg width="15" height="15" viewBox="0 0 24 24" fill={liked ? "currentColor" : "none"} stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
          </svg>
          <span style={{ fontFamily: "var(--mono, monospace)", fontSize: "0.75rem" }}>{likeCount}</span>
        </button>
        <div style={{ display: "flex", alignItems: "center", gap: "0.375rem", fontSize: "0.8125rem", color: "#6b7280" }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
          </svg>
          <span style={{ fontFamily: "var(--mono, monospace)", fontSize: "0.75rem" }}>{feed.total_comment}</span>
        </div>
      </div>
    </article>
  );
}

// ── Main Shell ────────────────────────────────────────────────────────────────
interface UserInfo {
  id: number;
  user_name?: string;
  full_name?: string;
  image?: string;
  bio?: string;
  created_at?: string;
  total_feed?: number;
  is_follow?: number;
  is_verified?: number;
}

interface Props {
  targetUserId: number;
}

export default function UserProfileShell({ targetUserId }: Props) {
  const [loggedInUserId, setLoggedInUserId] = useState(0);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [feeds, setFeeds] = useState<FeedItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [following, setFollowing] = useState(false);
  const [followLoading, setFollowLoading] = useState(false);
  const fetchedRef = useRef(false);

  useEffect(() => {
    const uid = getStoredUser()?.id ?? 0;
    setLoggedInUserId(uid);
  }, []);

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;

    async function load() {
      try {
        const { default: api } = await import("@/services/api.client");
        const { data } = await api.post<{
          status: number;
          result: FeedItem[];
          to_user_info?: UserInfo[];
        }>(API_ENDPOINTS.GET_USER_FEED, {
          to_user_id: targetUserId,
          user_id: getStoredUser()?.id ?? 0,
        });

        setFeeds(data.result ?? []);

        // Extract user info from first feed item or to_user_info
        if (data.to_user_info?.[0]) {
          const u = data.to_user_info[0];
          setUserInfo(u);
          setFollowing((u.is_follow ?? 0) === 1);
        } else if (data.result?.[0]) {
          const f = data.result[0];
          setUserInfo({
            id: f.user_id,
            user_name: f.user_name,
            full_name: f.user_name,
            image: f.user_image,
            is_verified: f.is_verified,
            is_follow: f.is_follow,
          });
          setFollowing(f.is_follow === 1);
        }
      } finally {
        setLoading(false);
      }
    }
    load();
  }, [targetUserId]);

  async function handleFollow() {
    if (!loggedInUserId) { window.location.href = "/login"; return; }
    setFollowLoading(true);
    const next = !following;
    setFollowing(next);
    try {
      const { default: api } = await import("@/services/api.client");
      await api.post(API_ENDPOINTS.FOLLOW_UNFOLLOW, {
        to_user_id: targetUserId,
        type: 1,
        user_id: loggedInUserId,
      });
    } catch {
      setFollowing(!next);
    } finally {
      setFollowLoading(false);
    }
  }

  const displayName = userInfo?.full_name || userInfo?.user_name || `User #${targetUserId}`;
  const initial = getInitial(displayName);

  return (
    <>
      <style>{`
        @keyframes up-fade {
          from { opacity: 0; transform: translateY(18px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .up-fade { animation: up-fade 0.45s ease both; }
        .up-fade-1 { animation-delay: 0.08s; }
        .up-fade-2 { animation-delay: 0.16s; }
        .up-fade-3 { animation-delay: 0.24s; }
        .post-card:hover { box-shadow: 0 4px 18px rgba(0,0,0,0.09) !important; }
      `}</style>

      <main style={{ minHeight: "80vh", background: "#f8f7f5" }}>

        {/* ── Hero header ─────────────────────────────────── */}
        <div style={{
          background: "#0e0e11",
          position: "relative",
          overflow: "hidden",
          paddingBottom: "2.5rem",
        }}>
          {/* Subtle grid texture */}
          <div style={{
            position: "absolute", inset: 0, opacity: 0.04,
            backgroundImage: "repeating-linear-gradient(0deg,transparent,transparent 39px,#fff 39px,#fff 40px),repeating-linear-gradient(90deg,transparent,transparent 39px,#fff 39px,#fff 40px)",
          }} />
          {/* Brand red glow behind avatar */}
          <div style={{ position: "absolute", top: "30%", left: "50%", transform: "translate(-50%,-50%)", width: 320, height: 320, borderRadius: "50%", background: "radial-gradient(circle,rgba(193,39,45,0.18) 0%,transparent 70%)", pointerEvents: "none" }} />

          <div className="wrap" style={{ maxWidth: 680, margin: "0 auto", padding: "3rem 1.25rem 0", position: "relative" }}>
            {/* Back */}
            <Link href="/feeds" style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "rgba(255,255,255,0.5)", textDecoration: "none", fontSize: "0.8125rem", fontWeight: 600, marginBottom: "2rem" }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M19 12H5M12 5l-7 7 7 7" /></svg>
              Back to Feeds
            </Link>

            {loading ? (
              /* Skeleton */
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "0.875rem", paddingBottom: "2rem" }}>
                <div style={{ width: 88, height: 88, borderRadius: "50%", background: "rgba(255,255,255,0.08)" }} />
                <div style={{ height: 14, width: 160, background: "rgba(255,255,255,0.08)", borderRadius: 4 }} />
                <div style={{ height: 10, width: 100, background: "rgba(255,255,255,0.06)", borderRadius: 4 }} />
              </div>
            ) : (
              <div className="up-fade" style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: "0.75rem", paddingBottom: "2rem" }}>
                {/* Avatar */}
                <div style={{
                  width: 88, height: 88, borderRadius: "50%",
                  border: "3px solid rgba(193,39,45,0.7)",
                  overflow: "hidden", position: "relative",
                  background: "rgba(193,39,45,0.12)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  boxShadow: "0 0 0 6px rgba(193,39,45,0.12)",
                }}>
                  {isValidImg(userInfo?.image)
                    ? <Image src={userInfo!.image!} alt={displayName} fill style={{ objectFit: "cover" }} unoptimized />
                    : <span style={{ fontSize: "2rem", fontWeight: 800, color: "#C1272D", fontFamily: "var(--italic, Georgia, serif)", fontStyle: "italic" }}>{initial}</span>
                  }
                </div>

                {/* Name */}
                <div>
                  <h1 style={{
                    margin: "0 0 0.25rem",
                    fontFamily: "var(--italic, Georgia, serif)",
                    fontStyle: "italic",
                    fontWeight: 400,
                    fontSize: "clamp(1.5rem, 4vw, 2.25rem)",
                    color: "#fff",
                    letterSpacing: "-0.02em",
                    lineHeight: 1.1,
                    display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                  }}>
                    {displayName}
                    {userInfo?.is_verified === 1 && (
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                        <circle cx="12" cy="12" r="12" fill="#C1272D" />
                        <path d="M7 12l3 3 7-7" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" />
                      </svg>
                    )}
                  </h1>
                  {userInfo?.user_name && (
                    <div style={{ fontFamily: "var(--mono, monospace)", fontSize: "0.8125rem", color: "rgba(255,255,255,0.45)", letterSpacing: "0.02em" }}>
                      @{userInfo.user_name}
                    </div>
                  )}
                </div>

                {/* Bio */}
                {userInfo?.bio && (
                  <p style={{ margin: 0, maxWidth: 440, fontSize: "0.9rem", color: "rgba(255,255,255,0.6)", lineHeight: 1.55 }}>
                    {userInfo.bio}
                  </p>
                )}

                {/* Stats row */}
                <div style={{ display: "flex", gap: "2rem", marginTop: "0.25rem" }}>
                  <div style={{ textAlign: "center" }}>
                    <div style={{ fontFamily: "var(--mono, monospace)", fontSize: "1.125rem", fontWeight: 700, color: "#fff" }}>{userInfo?.total_feed ?? feeds.length}</div>
                    <div style={{ fontSize: "0.6875rem", color: "rgba(255,255,255,0.4)", textTransform: "uppercase", letterSpacing: "0.08em", marginTop: 2 }}>Posts</div>
                  </div>
                  {userInfo?.created_at && (
                    <div style={{ textAlign: "center" }}>
                      <div style={{ fontFamily: "var(--mono, monospace)", fontSize: "1.125rem", fontWeight: 700, color: "#fff" }}>{fmtDate(userInfo.created_at)}</div>
                      <div style={{ fontSize: "0.6875rem", color: "rgba(255,255,255,0.4)", textTransform: "uppercase", letterSpacing: "0.08em", marginTop: 2 }}>Joined</div>
                    </div>
                  )}
                </div>

                {/* Follow button */}
                {loggedInUserId !== targetUserId && (
                  <button
                    onClick={handleFollow}
                    disabled={followLoading}
                    style={{
                      marginTop: "0.25rem",
                      padding: "0.5rem 2rem",
                      borderRadius: 24,
                      border: following ? "1.5px solid rgba(255,255,255,0.25)" : "1.5px solid #C1272D",
                      background: following ? "transparent" : "#C1272D",
                      color: following ? "rgba(255,255,255,0.8)" : "#fff",
                      fontWeight: 700,
                      fontSize: "0.875rem",
                      cursor: followLoading ? "default" : "pointer",
                      letterSpacing: "0.02em",
                      transition: "all 0.18s",
                      opacity: followLoading ? 0.6 : 1,
                    }}
                  >
                    {following ? "Following" : "Follow"}
                  </button>
                )}
              </div>
            )}
          </div>
        </div>

        {/* ── Feed posts ──────────────────────────────────── */}
        <div className="wrap" style={{ maxWidth: 580, margin: "0 auto", padding: "1.75rem 1.25rem 3rem" }}>

          {/* Section label */}
          <div className="up-fade up-fade-1" style={{ display: "flex", alignItems: "center", gap: "0.75rem", marginBottom: "1.25rem" }}>
            <span style={{ fontFamily: "var(--italic, Georgia, serif)", fontStyle: "italic", fontWeight: 400, fontSize: "1.125rem", color: "#0e0e11" }}>Posts</span>
            {!loading && (
              <span style={{ fontFamily: "var(--mono, monospace)", fontSize: "0.75rem", color: "#9ca3af", background: "#f3f4f6", padding: "2px 8px", borderRadius: 20 }}>
                {feeds.length}
              </span>
            )}
            <div style={{ flex: 1, height: 1, background: "#e5e7eb" }} />
          </div>

          {loading ? (
            /* Skeleton posts */
            Array.from({ length: 3 }).map((_, i) => (
              <div key={i} style={{ background: "#fff", borderRadius: 14, padding: "1.125rem 1.25rem", marginBottom: "1rem", border: "1px solid #e8e8e8" }}>
                <div style={{ display: "flex", gap: "0.625rem", marginBottom: "0.75rem" }}>
                  <div style={{ width: 36, height: 36, borderRadius: "50%", background: "#f3f4f6", flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ height: 11, width: "40%", background: "#f3f4f6", borderRadius: 4, marginBottom: 6 }} />
                    <div style={{ height: 9, width: "25%", background: "#f3f4f6", borderRadius: 4 }} />
                  </div>
                </div>
                <div style={{ height: 10, background: "#f3f4f6", borderRadius: 4, marginBottom: 6 }} />
                <div style={{ height: 10, width: "75%", background: "#f3f4f6", borderRadius: 4 }} />
              </div>
            ))
          ) : feeds.length === 0 ? (
            <div className="up-fade up-fade-2" style={{ textAlign: "center", padding: "4rem 1rem", color: "#9ca3af" }}>
              <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.25" style={{ opacity: 0.3, marginBottom: "0.75rem" }}>
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
              </svg>
              <p style={{ margin: 0, fontWeight: 600, fontSize: "0.9375rem" }}>No posts yet</p>
              <p style={{ margin: "0.25rem 0 0", fontSize: "0.8125rem" }}>This user hasn&apos;t shared anything yet.</p>
            </div>
          ) : (
            <div className="up-fade up-fade-2">
              {feeds.map((feed) => (
                <PostCard key={feed.id} feed={feed} loggedInUserId={loggedInUserId} />
              ))}
            </div>
          )}
        </div>
      </main>
    </>
  );
}
