import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ChevronRight, Plus, SquarePen } from "lucide-react";
import { useProfile } from "../context/ProfileContext";
import { getCachedProfile } from "../../services/profileService";
import { getProfileImageUrl } from "../../services/feedService";
import logoImage from "figma:asset/0a77244cc5b7dea0bea10275d45df2915d5170ca.png";
import coinImage from "../../assets/coin-star.png";
import profileFallbackImage from "../../assets/image 5.png";

interface AppHeaderProps {
  showBack?: boolean;
  onBack?: () => void;
  centerTitle?: string;
  centerSubtitle?: string;
  useNewChatAction?: boolean;
  onNewChatClick?: () => void;
}

const toPersianNumber = (num: number | null | undefined): string => {
  if (num === null || num === undefined) return "۰";
  const persianDigits = "۰۱۲۳۴۵۶۷۸۹";
  return String(num).replace(/\d/g, (digit) => persianDigits[parseInt(digit, 10)]);
};

export function AppHeader({
  showBack = false,
  onBack,
  centerTitle,
  centerSubtitle,
  useNewChatAction = false,
  onNewChatClick,
}: AppHeaderProps) {
  const navigate = useNavigate();
  const { profile } = useProfile();

  const [displayCoins, setDisplayCoins] = useState<number>(() => {
    const cachedProfile = getCachedProfile();
    return cachedProfile?.coin_count ?? 0;
  });

  useEffect(() => {
    if (profile?.coin_count !== null && profile?.coin_count !== undefined) {
      setDisplayCoins(profile.coin_count);
    }
  }, [profile]);

  const hasCustomAvatar = Boolean(profile?.image && profile?.user_stage_id);
  const avatarUrl = useMemo(() => {
    if (hasCustomAvatar) {
      return getProfileImageUrl(profile.image, profile.user_stage_id);
    }
    return profileFallbackImage;
  }, [hasCustomAvatar, profile?.image, profile?.user_stage_id]);

  const displayName = `${profile?.name || ""} ${profile?.family || ""}`.trim() || profile?.username || "همراه";
  const displayGrade = profile?.base ? `پایه ${profile.base}` : profile?.education_level || "";

  const navLikePanelStyle = {
    backgroundImage: `
      linear-gradient(180deg, #2E1B3D 0%, #23183E 100%),
      linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)
    `,
    backgroundOrigin: "border-box",
    backgroundClip: "padding-box, border-box",
    boxShadow:
      "0 -7px 20px rgba(7, 0, 18, 0.5), 0 6px 14px rgba(5, 2, 12, 0.26), inset 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 2px 5px rgba(255, 222, 255, 0.09), inset 0 -2px 0 rgba(12, 7, 27, 0.72), inset 0 -8px 14px rgba(8, 4, 18, 0.34), inset 0 0 0 1px rgba(255, 255, 255, 0.045), inset 0 0 0 2px rgba(17, 10, 35, 0.32)",
    backdropFilter: "blur(14px)",
    WebkitBackdropFilter: "blur(14px)",
  } as const;

  return (
    <div className="relative z-20 h-[68px] min-h-[68px] px-4" dir="rtl">
      {useNewChatAction ? (
        <button
          type="button"
          onClick={onNewChatClick}
          className="absolute left-4 top-1/2 z-20 flex h-10 w-fit -translate-y-1/2 items-center gap-1.5 rounded-full border-[0.5px] border-transparent px-2.5 text-xs font-bold text-white"
          style={navLikePanelStyle}
          aria-label="چت جدید"
        >
          <SquarePen size={15} color="#facc15" />
          <span className="leading-none">چت جدید</span>
        </button>
      ) : (
        <div
          className="absolute left-4 top-1/2 z-20 flex h-10 w-fit -translate-y-1/2 items-center gap-[6px] rounded-full border-[0.5px] border-transparent px-2.5"
          style={navLikePanelStyle}
        >
          <div
            className="flex h-5 w-5 items-center justify-center rounded-full border-[0.5px] border-transparent"
            style={navLikePanelStyle}
          >
            <Plus size={11} color="#ffd6f0" strokeWidth={2.25} />
          </div>
          <span
            className="font-semibold leading-none text-white tracking-tight"
            style={{ fontSize: 16 }}
          >
            {toPersianNumber(displayCoins)}
          </span>
          <img src={coinImage} alt="سکه" className="-my-0.5 h-7 w-7 object-contain" />
        </div>
      )}

      {showBack ? (
        <button
          onClick={onBack}
          className="absolute right-4 top-1/2 z-20 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full border-[0.5px] border-transparent"
          aria-label="بازگشت"
          style={navLikePanelStyle}
        >
          <ChevronRight size={22} color="#ffffff" />
        </button>
      ) : (
        <button
          onClick={() => navigate("/profile")}
          className="absolute right-4 top-1/2 z-20 flex max-w-[148px] -translate-y-1/2 items-center gap-2 text-right"
          aria-label="پروفایل"
        >
          <span
            className="h-12 w-12 shrink-0 overflow-hidden rounded-full border-[0.5px] border-transparent p-[2px]"
            style={navLikePanelStyle}
          >
            {hasCustomAvatar ? (
              <img
                src={avatarUrl}
                alt="پروفایل"
                className="h-full w-full rounded-full object-cover"
                onError={(event) => {
                  event.currentTarget.src = profileFallbackImage;
                }}
              />
            ) : (
              <span
                className="flex h-full w-full items-center justify-center rounded-full"
                style={navLikePanelStyle}
              >
                <img
                  src={profileFallbackImage}
                  alt="پروفایل پیش‌فرض"
                  className="rounded-full object-cover"
                />
              </span>
            )}
          </span>

          <span className="min-w-0 leading-none">
            <span className="block max-w-[86px] truncate text-[12px] font-extrabold leading-4 text-[#FBE7F5]">
              {displayName}
            </span>
            {displayGrade && (
              <span className="mt-0.5 block max-w-[86px] truncate text-[10px] font-medium leading-3 text-[#F2DFF0]/72">
                {displayGrade}
              </span>
            )}
          </span>
        </button>
      )}

      <div
        className="pointer-events-none absolute left-1/2 top-1/2 z-10 flex w-[min(170px,42vw)] -translate-x-1/2 -translate-y-1/2 items-center justify-center text-center"
      >
        {centerTitle ? (
          <div className="w-full">
            <div
              className="mx-auto max-w-full truncate font-extrabold text-[18px] leading-6"
              style={{
                display: "inline-block",
                background:
                  "linear-gradient(90deg, #F6D8A5 0%, #F3A599 20%, #DB7EB2 48%, #AA6798 72%, #CB75AB 100%)",
                WebkitBackgroundClip: "text",
                backgroundClip: "text",
                WebkitTextFillColor: "transparent",
                color: "transparent",
                textShadow: "0 2px 10px rgba(255, 119, 202, 0.4)",
              }}
            >
              {centerTitle}
            </div>
            {centerSubtitle && (
              <div
                className="-mt-2 text-[11px] font-medium"
                style={{
                  color: "#ffb7dd",
                  textShadow: "0 1px 6px rgba(255, 119, 202, 0.35)",
                }}
              >
                {centerSubtitle}
              </div>
            )}
          </div>
        ) : (
          <img
            src={logoImage}
            alt="مدرسه"
            className="h-12 object-contain"
            style={{ filter: "drop-shadow(0 2px 6px rgba(192, 132, 252, 0.55))" }}
          />
        )}
      </div>
    </div>
  );
}
