import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { motion } from "motion/react";
import { Save, ChevronDown } 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="flex h-full min-h-0 items-center justify-center" dir="rtl">
        <div className="text-center">
          <div className="mx-auto mb-3 h-10 w-10 animate-spin rounded-full border-4 border-[#ffd6f0]/30 border-t-[#ff79cf]" />
          <p className="text-sm font-bold text-[#FBE7F5]">در حال بارگذاری پروفایل...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="relative h-full min-h-0 overflow-hidden" dir="rtl">
      <main
        className="h-full overflow-y-auto px-4 pb-4 pt-4"
        style={{
          maxHeight: "100%",
        }}
      >
        <div className="mx-auto w-full max-w-md">
          <div className="mb-4 text-center">
            <h1 className="text-[20px] font-extrabold text-[#FBE7F5]">
              {userProfile?.user_workflowID ? "ویرایش پروفایل" : "تکمیل پروفایل"}
            </h1>
            <p className="mt-1 text-xs text-[#EED3EC]/82">اطلاعات پایه حساب کاربری را ثبت یا به‌روزرسانی کنید</p>
          </div>

          {successMessage && (
            <motion.div
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              className="mb-4 rounded-2xl px-4 py-3 text-center text-sm font-bold"
              style={{
                backgroundImage:
                  "linear-gradient(180deg, rgba(24, 67, 46, 0.88) 0%, rgba(16, 56, 39, 0.92) 100%), linear-gradient(120deg, #34d399 0%, #10b981 100%)",
                backgroundOrigin: "border-box",
                backgroundClip: "padding-box, border-box",
                border: "1px solid rgba(167, 243, 208, 0.4)",
                color: "#D1FAE5",
              }}
            >
              {successMessage}
            </motion.div>
          )}

          <form id="edit-profile-form" onSubmit={handleSubmit} className="space-y-4">
            <div
              className="rounded-[22px] border-[0.5px] border-transparent px-4 py-4"
              style={{
                backgroundImage:
                  "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.94) 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.36), 0 8px 16px rgba(5, 2, 12, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.12)",
              }}
            >
              <div className="space-y-4">
                <div>
                  <label className="mb-2 block text-xs font-semibold text-[#FBE7F5]/92">نام</label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => handleChange("name", e.target.value)}
                    className="w-full rounded-xl px-3 py-2.5 text-sm font-bold text-white outline-none"
                    style={{
                      background: "rgba(255,255,255,0.08)",
                      border: errors.name ? "1px solid rgba(248, 113, 113, 0.62)" : "1px solid rgba(255,255,255,0.14)",
                    }}
                    placeholder="نام خود را وارد کنید"
                  />
                  {errors.name && <p className="mt-1 text-xs text-red-300">{errors.name}</p>}
                </div>

                <div>
                  <label className="mb-2 block text-xs font-semibold text-[#FBE7F5]/92">نام خانوادگی</label>
                  <input
                    type="text"
                    value={formData.family}
                    onChange={(e) => handleChange("family", e.target.value)}
                    className="w-full rounded-xl px-3 py-2.5 text-sm font-bold text-white outline-none"
                    style={{
                      background: "rgba(255,255,255,0.08)",
                      border: errors.family ? "1px solid rgba(248, 113, 113, 0.62)" : "1px solid rgba(255,255,255,0.14)",
                    }}
                    placeholder="نام خانوادگی خود را وارد کنید"
                  />
                  {errors.family && <p className="mt-1 text-xs text-red-300">{errors.family}</p>}
                </div>

                <div>
                  <label className="mb-2 block text-xs font-semibold text-[#FBE7F5]/92">مقطع تحصیلی</label>
                  <div className="relative">
                    <select
                      value={formData.education_level}
                      onChange={(e) => handleChange("education_level", e.target.value)}
                      className="w-full appearance-none rounded-xl px-3 py-2.5 pl-10 text-sm font-bold text-white outline-none"
                      style={{
                        background: "rgba(255,255,255,0.08)",
                        border: errors.education_level ? "1px solid rgba(248, 113, 113, 0.62)" : "1px solid rgba(255,255,255,0.14)",
                      }}
                    >
                      <option value="">انتخاب کنید</option>
                      <option value="ابتدایی">ابتدایی</option>
                      <option value="متوسطه اول">متوسطه اول</option>
                      <option value="متوسطه دوم">متوسطه دوم</option>
                    </select>
                    <ChevronDown
                      className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#F2DFF0]/72"
                    />
                  </div>
                  {errors.education_level && <p className="mt-1 text-xs text-red-300">{errors.education_level}</p>}
                </div>

                <div>
                  <label className="mb-2 block text-xs font-semibold text-[#FBE7F5]/92">پایه تحصیلی</label>
                  <div className="relative">
                    <select
                      value={formData.base}
                      onChange={(e) => handleChange("base", e.target.value)}
                      className="w-full appearance-none rounded-xl px-3 py-2.5 pl-10 text-sm font-bold text-white outline-none"
                      style={{
                        background: "rgba(255,255,255,0.08)",
                        border: errors.base ? "1px solid rgba(248, 113, 113, 0.62)" : "1px solid rgba(255,255,255,0.14)",
                      }}
                    >
                      <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>
                    <ChevronDown
                      className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#F2DFF0]/72"
                    />
                  </div>
                  {errors.base && <p className="mt-1 text-xs text-red-300">{errors.base}</p>}
                </div>
              </div>
            </div>
            <motion.button
              type="submit"
              disabled={isSaving}
              whileTap={{ scale: isSaving ? 1 : 0.98 }}
              className="flex h-12 w-full items-center justify-center gap-2 rounded-full text-sm font-bold text-white"
              style={{
                backgroundImage: isSaving
                  ? "linear-gradient(145deg, rgba(72, 58, 105, 0.72) 0%, rgba(42, 35, 77, 0.76) 100%)"
                  : "linear-gradient(90deg, rgba(255,139,91,1) 0%, rgba(238,91,166,1) 45%, rgba(147,78,255,1) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
                backgroundOrigin: "border-box",
                backgroundClip: "padding-box, border-box",
                border: "1px solid transparent",
                boxShadow: isSaving
                  ? "inset 0 1px 0 rgba(255,255,255,0.12)"
                  : "0 10px 24px rgba(196, 87, 255, 0.32), inset 0 1px 0 rgba(255,255,255,0.3)",
                opacity: isSaving ? 0.7 : 1,
                cursor: isSaving ? "not-allowed" : "pointer",
              }}
            >
              <Save size={16} />
              <span>{isSaving ? "در حال ذخیره..." : "ذخیره اطلاعات"}</span>
            </motion.button>
          </form>
        </div>
      </main>
    </div>
  );
}
