import { useParams } from "react-router-dom";
import { ArrowRight, LogOut, Edit2 } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { motion } from "motion/react";
import profileIcon from "figma:asset/888154c80a51a82379dca3e77681cd851d702bf1.png";
import { logout, getUserInfo } from "../../utils/auth";
import { useEffect, useState } from "react";
import { getUserProfile, getCachedProfile, type UserProfile } from "../../services/profileService";

// Remove the FeedPage from here as it's now in its own file
export function ProfilePage() {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<{ Name: string; Family: string; Username: string } | null>(null);
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const [isLoadingProfile, setIsLoadingProfile] = useState(true);

  useEffect(() => {
    const info = getUserInfo();
    setUserInfo(info);
    
    // بارگذاری اطلاعات پروفایل
    loadProfile();
  }, []);

  const loadProfile = async () => {
    setIsLoadingProfile(true);
    try {
      // ابتدا از cache بخوانیم
      const cachedProfile = getCachedProfile();
      if (cachedProfile) {
        setUserProfile(cachedProfile);
      }
      
      // سپس از سرور بگیریم (به صورت silent - بدون نمایش خطا)
      const profile = await getUserProfile();
      if (profile) {
        setUserProfile(profile);
      }
    } catch (error) {
      // خطا را فقط در console نمایش می‌دهیم
      console.warn("عدم دسترسی به سرور - از داده‌های کش استفاده می‌شود");
    } finally {
      setIsLoadingProfile(false);
    }
  };

  const handleLogout = async () => {
    setIsLoggingOut(true);
    try {
      await logout();
      navigate("/login", { state: { error: "شما با موفقیت از سیستم خارج شدید" } });
    } catch (error) {
      console.error("خطا در خروج:", error);
      // حتی در صورت خطا، به صفحه لاگین هدایت می‌شویم
      navigate("/login", { state: { error: "شما با موفقیت از سیستم خارج شدید" } });
    } finally {
      setIsLoggingOut(false);
    }
  };

  // تبدیل اعداد انگلیسی به فارسی
  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)]);
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-[60vh] px-6 text-center" dir="rtl">
      {/* Avatar */}
      <motion.div
        initial={{ scale: 0 }}
        animate={{ scale: 1 }}
        transition={{ type: "spring", duration: 0.5 }}
        className="w-32 h-32 rounded-full flex items-center justify-center mb-6"
        style={{
          background: "linear-gradient(135deg, rgba(138, 206, 224, 0.3) 0%, rgba(76, 127, 137, 0.3) 100%)",
          border: "3px solid rgba(138, 206, 224, 0.5)",
          boxShadow: "0 8px 24px rgba(138, 206, 224, 0.4), inset 0 -4px 12px rgba(0, 0, 0, 0.3), inset 0 2px 8px rgba(255, 255, 255, 0.1)",
        }}
      >
        {userProfile?.image ? (
          <img
            src={userProfile.image}
            alt="پروفایل"
            className="w-full h-full rounded-full object-cover"
            style={{
              filter: "drop-shadow(0 4px 8px rgba(138, 206, 224, 0.6))",
            }}
          />
        ) : (
          <img
            src={profileIcon}
            alt="پروفایل"
            className="w-20 h-20 object-contain"
            style={{
              filter: "drop-shadow(0 4px 8px rgba(138, 206, 224, 0.6))",
            }}
          />
        )}
      </motion.div>

      {/* Name */}
      <motion.h2
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.2 }}
        className="text-white text-2xl font-bold mb-2"
        style={{
          textShadow: "0 4px 12px rgba(138, 206, 224, 0.6), 0 2px 4px rgba(0, 0, 0, 0.8)",
        }}
      >
        {isLoadingProfile 
          ? "در حال بارگذاری..." 
          : userProfile 
            ? `${userProfile.name} ${userProfile.family}` 
            : userInfo 
              ? `${userInfo.Name} ${userInfo.Family}` 
              : "کاربر گرامی"}
      </motion.h2>

      <motion.p
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.3 }}
        style={{ color: "rgba(180, 220, 240, 0.6)" }}
        className="text-sm mb-2"
      >
        @{userProfile?.username || userInfo?.Username || "user123"}
      </motion.p>

      {/* Education Info */}
      {userProfile && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.35 }}
          style={{ color: "rgba(138, 206, 224, 0.8)" }}
          className="text-xs mb-8"
        >
          {userProfile.education_level} - پایه {userProfile.base}
        </motion.div>
      )}

      {/* Stats */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.4 }}
        className="flex gap-4 mb-8"
      >
        {[
          { label: "ماموریت‌ها", value: userProfile?.user_stage_id ? toPersianNumber(parseInt(userProfile.user_stage_id)) : "۰" },
          { label: "سکه‌ها", value: toPersianNumber(userProfile?.coin_count) },
          { label: "دنبال‌کنندگان", value: "۲۸" },
        ].map((stat, index) => (
          <div
            key={index}
            className="px-6 py-3 rounded-2xl"
            style={{
              background: "linear-gradient(135deg, rgba(32, 76, 106, 0.6) 0%, rgba(20, 40, 60, 0.6) 100%)",
              border: "2px solid rgba(138, 206, 224, 0.3)",
              boxShadow: "inset 0 2px 8px rgba(0, 0, 0, 0.4), 0 4px 12px rgba(0, 0, 0, 0.3)",
            }}
          >
            <div className="text-white font-bold text-lg mb-1">{stat.value}</div>
            <div style={{ color: "#8ACEE0" }} className="text-xs">
              {stat.label}
            </div>
          </div>
        ))}
      </motion.div>

      {/* Edit Profile Button - نمایش فقط در صورتی که user_workflowID موجود باشد */}
      {userProfile?.user_workflowID && (
        <motion.button
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.45 }}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          onClick={() => navigate("/edit-profile")}
          className="flex items-center gap-3 px-8 py-3 rounded-2xl font-bold text-base mb-4"
          style={{
            background: "linear-gradient(135deg, rgba(76, 175, 80, 0.9) 0%, rgba(56, 142, 60, 0.9) 100%)",
            boxShadow: "0 8px 24px rgba(76, 175, 80, 0.4), 0 4px 12px rgba(0, 0, 0, 0.4)",
            color: "#FFFFFF",
            textShadow: "0 2px 4px rgba(0, 0, 0, 0.5)",
          }}
        >
          <Edit2 size={20} />
          <span>ویرایش پروفایل</span>
        </motion.button>
      )}

      {/* Complete Profile Button - نمایش فقط در صورتی که user_workflowID موجود نباشد */}
      {!isLoadingProfile && !userProfile?.user_workflowID && (
        <motion.button
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.45 }}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          onClick={() => navigate("/edit-profile")}
          className="flex items-center gap-3 px-8 py-3 rounded-2xl font-bold text-base mb-4"
          style={{
            background: "linear-gradient(135deg, rgba(255, 193, 7, 0.9) 0%, rgba(255, 160, 0, 0.9) 100%)",
            boxShadow: "0 8px 24px rgba(255, 193, 7, 0.4), 0 4px 12px rgba(0, 0, 0, 0.4)",
            color: "#FFFFFF",
            textShadow: "0 2px 4px rgba(0, 0, 0, 0.5)",
          }}
        >
          <Edit2 size={20} />
          <span>تکمیل پروفایل</span>
        </motion.button>
      )}

      {/* Logout Button */}
      <motion.button
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.5 }}
        whileHover={{ scale: isLoggingOut ? 1 : 1.05 }}
        whileTap={{ scale: isLoggingOut ? 1 : 0.95 }}
        onClick={handleLogout}
        disabled={isLoggingOut}
        className="flex items-center gap-3 px-8 py-4 rounded-2xl font-bold text-lg"
        style={{
          background: isLoggingOut
            ? "linear-gradient(135deg, rgba(120, 30, 40, 0.7) 0%, rgba(96, 24, 32, 0.7) 100%)"
            : "linear-gradient(135deg, rgba(220, 53, 69, 0.9) 0%, rgba(176, 42, 55, 0.9) 100%)",
          boxShadow: "0 12px 32px rgba(220, 53, 69, 0.4), 0 4px 12px rgba(0, 0, 0, 0.4)",
          color: "#FFFFFF",
          textShadow: "0 2px 4px rgba(0, 0, 0, 0.5)",
          opacity: isLoggingOut ? 0.7 : 1,
          cursor: isLoggingOut ? "not-allowed" : "pointer",
        }}
      >
        <LogOut size={24} />
        <span>{isLoggingOut ? "در حال خروج..." : "خروج از حساب کاربری"}</span>
      </motion.button>
    </div>
  );
}