import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { motion } from "motion/react";
import { ArrowRight, Save } from "lucide-react";
import { getUserProfile, saveUserProfile, getCachedProfile, type UserProfile } from "../../services/profileService";
import { getUsername } from "../../utils/auth";
import { usePageTracking } from "../../hooks/usePageTracking";
import { useProfile } from "../context/ProfileContext";

export function EditProfilePage() {
  const navigate = useNavigate();
  const location = useLocation();
  usePageTracking("ویرایش پروفایل");
  const { refreshProfile } = useProfile();
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [successMessage, setSuccessMessage] = useState("");
  
  const [formData, setFormData] = useState({
    name: "",
    family: "",
    education_level: "",
    base: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    loadProfile();
    
    // نمایش پیام از state (در صورت redirect از LoginPage)
    if (location.state?.message) {
      setSuccessMessage(location.state.message);
      // پاک کردن state
      window.history.replaceState({}, document.title);
      
      // پاک کردن پیام بعد از 5 ثانیه
      setTimeout(() => {
        setSuccessMessage("");
      }, 5000);
    }
  }, [location]);

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

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = "نام الزامی است";
    }
    if (!formData.family.trim()) {
      newErrors.family = "نام خانوادگی الزامی است";
    }
    if (!formData.education_level) {
      newErrors.education_level = "مقطع تحصیلی الزامی است";
    }
    if (!formData.base) {
      newErrors.base = "پایه تحصیلی الزامی است";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setIsSaving(true);
    try {
      const username = getUsername();
      if (!username) {
        throw new Error("نام کاربری یافت نشد");
      }

      // ساخت داده برای ارسال
      const userData = {
        username: username,
        name: formData.name,
        family: formData.family,
        education_level: formData.education_level,
        base: formData.base,
      };

      // اگر user_workflowID موجود باشد (حالت ویرایش)، WorkflowID را اضافه می‌کنیم
      // اگر موجود نباشد (حالت ثبت جدید)، فقط user را ارسال می‌کنیم
      const saveData = userProfile?.user_workflowID
        ? {
            WorkflowID: userProfile.user_workflowID,
            user: userData,
          }
        : {
            user: userData,
          };

      console.log("Saving profile data:", JSON.stringify(saveData));

      const success = await saveUserProfile(saveData);
      
      if (success) {
        // بروزرسانی پروفایل در context
        await refreshProfile();
        navigate("/profile");
      } else {
        alert("خطا در ذخیره اطلاعات");
      }
    } catch (error) {
      console.error("خطا در ذخیره:", error);
      alert("خطا در ذخیره اطلاعات");
    } finally {
      setIsSaving(false);
    }
  };

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    // پاک کردن خطای فیلد هنگام تغییر
    if (errors[field]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  // Loading state
  if (isLoading) {
    return (
      <div
        className="min-h-screen flex items-center justify-center"
        style={{
          background:
            "radial-gradient(120% 120% at 50% 0%, rgba(124, 58, 237, 0.32) 0%, rgba(46, 27, 61, 0.98) 52%, rgba(35, 24, 62, 1) 100%)",
        }}
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center"
        >
          <motion.div
            className="w-16 h-16 border-4 rounded-full mx-auto mb-4"
            style={{
              borderColor: "rgba(255, 214, 240, 0.28)",
              borderTopColor: "#ff79cf",
            }}
            animate={{ rotate: 360 }}
            transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
          />
          <p
            className="text-lg font-bold"
            style={{
              color: "#ffd6f0",
              textShadow: "0 2px 4px rgba(0, 0, 0, 0.6)",
            }}
            dir="rtl"
          >
            در حال بارگذاری پروفایل...
          </p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto px-6 py-8" dir="rtl">
      {/* Header */}
      <div className="flex items-center gap-4 mb-8">
        <motion.button
          whileHover={{ scale: 1.1 }}
          whileTap={{ scale: 0.9 }}
          onClick={() => navigate("/profile")}
          className="w-10 h-10 rounded-full flex items-center justify-center"
          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)",
          }}
        >
          <ArrowRight className="text-white" size={20} />
        </motion.button>
        <h1
          className="text-2xl font-bold text-white"
          style={{
            textShadow: "0 4px 12px rgba(138, 206, 224, 0.6), 0 2px 4px rgba(0, 0, 0, 0.8)",
          }}
        >
          {userProfile?.user_workflowID ? "ویرایش پروفایل" : "تکمیل پروفایل"}
        </h1>
      </div>

      {/* Success/Info Message */}
      {successMessage && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-6 p-4 rounded-xl text-center font-bold"
          style={{
            background: "linear-gradient(135deg, rgba(76, 175, 80, 0.2) 0%, rgba(56, 142, 60, 0.2) 100%)",
            border: "2px solid rgba(76, 175, 80, 0.4)",
            color: "#A7F3D0",
            textShadow: "0 2px 4px rgba(0, 0, 0, 0.6)",
          }}
        >
          {successMessage}
        </motion.div>
      )}

      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Name */}
        <div>
          <label className="block text-white mb-2 text-sm font-bold">نام</label>
          <input
            type="text"
            value={formData.name}
            onChange={(e) => handleChange("name", e.target.value)}
            className="w-full px-4 py-3 rounded-xl text-white font-bold"
            style={{
              background: "linear-gradient(135deg, rgba(32, 76, 106, 0.4) 0%, rgba(20, 40, 60, 0.4) 100%)",
              border: errors.name ? "2px solid rgba(220, 53, 69, 0.6)" : "2px solid rgba(138, 206, 224, 0.3)",
              outline: "none",
            }}
            placeholder="نام خود را وارد کنید"
          />
          {errors.name && (
            <p className="text-red-400 text-xs mt-1">{errors.name}</p>
          )}
        </div>

        {/* Family */}
        <div>
          <label className="block text-white mb-2 text-sm font-bold">نام خانوادگی</label>
          <input
            type="text"
            value={formData.family}
            onChange={(e) => handleChange("family", e.target.value)}
            className="w-full px-4 py-3 rounded-xl text-white font-bold"
            style={{
              background: "linear-gradient(135deg, rgba(32, 76, 106, 0.4) 0%, rgba(20, 40, 60, 0.4) 100%)",
              border: errors.family ? "2px solid rgba(220, 53, 69, 0.6)" : "2px solid rgba(138, 206, 224, 0.3)",
              outline: "none",
            }}
            placeholder="نام خانوادگی خود را وارد کنید"
          />
          {errors.family && (
            <p className="text-red-400 text-xs mt-1">{errors.family}</p>
          )}
        </div>

        {/* Education Level */}
        <div>
          <label className="block text-white mb-2 text-sm font-bold">مقطع تحصیلی</label>
          <select
            value={formData.education_level}
            onChange={(e) => handleChange("education_level", e.target.value)}
            className="w-full px-4 py-3 rounded-xl text-white font-bold"
            style={{
              background: "linear-gradient(135deg, rgba(32, 76, 106, 0.4) 0%, rgba(20, 40, 60, 0.4) 100%)",
              border: errors.education_level ? "2px solid rgba(220, 53, 69, 0.6)" : "2px solid rgba(138, 206, 224, 0.3)",
              outline: "none",
            }}
          >
            <option value="">انتخاب کنید</option>
            <option value="ابتدایی">ابتدایی</option>
            <option value="متوسطه اول">متوسطه اول</option>
            <option value="متوسطه دوم">متوسطه دوم</option>
          </select>
          {errors.education_level && (
            <p className="text-red-400 text-xs mt-1">{errors.education_level}</p>
          )}
        </div>

        {/* Base (Grade) */}
        <div>
          <label className="block text-white mb-2 text-sm font-bold">پایه تحصیلی</label>
          <select
            value={formData.base}
            onChange={(e) => handleChange("base", e.target.value)}
            className="w-full px-4 py-3 rounded-xl text-white font-bold"
            style={{
              background: "linear-gradient(135deg, rgba(32, 76, 106, 0.4) 0%, rgba(20, 40, 60, 0.4) 100%)",
              border: errors.base ? "2px solid rgba(220, 53, 69, 0.6)" : "2px solid rgba(138, 206, 224, 0.3)",
              outline: "none",
            }}
          >
            <option value="">انتخاب کنید</option>
            {formData.education_level === "ابتدایی" && (
              <>
                <option value="اول">اول</option>
                <option value="دوم">دوم</option>
                <option value="سوم">سوم</option>
                <option value="چهارم">چهارم</option>
                <option value="پنجم">پنجم</option>
                <option value="ششم">ششم</option>
              </>
            )}
            {formData.education_level === "متوسطه اول" && (
              <>
                <option value="هفتم">هفتم</option>
                <option value="هشتم">هشتم</option>
                <option value="نهم">نهم</option>
              </>
            )}
            {formData.education_level === "متوسطه دوم" && (
              <>
                <option value="دهم">دهم</option>
                <option value="یازدهم">یازدهم</option>
                <option value="دوازدهم">دوازدهم</option>
              </>
            )}
          </select>
          {errors.base && (
            <p className="text-red-400 text-xs mt-1">{errors.base}</p>
          )}
        </div>

        {/* Submit Button */}
        <motion.button
          type="submit"
          disabled={isSaving}
          whileHover={{ scale: isSaving ? 1 : 1.02 }}
          whileTap={{ scale: isSaving ? 1 : 0.98 }}
          className="w-full flex items-center justify-center gap-3 px-8 py-4 rounded-2xl font-bold text-lg"
          style={{
            background: isSaving
              ? "linear-gradient(135deg, rgba(60, 140, 150, 0.7) 0%, rgba(40, 100, 110, 0.7) 100%)"
              : "linear-gradient(135deg, rgba(76, 175, 80, 0.9) 0%, rgba(56, 142, 60, 0.9) 100%)",
            boxShadow: "0 12px 32px 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)",
            opacity: isSaving ? 0.7 : 1,
            cursor: isSaving ? "not-allowed" : "pointer",
          }}
        >
          <Save size={24} />
          <span>{isSaving ? "در حال ذخیره..." : "ذخیره اطلاعات"}</span>
        </motion.button>
      </form>
    </div>
  );
}
