"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import MaleIcon from "@/public/images/male.svg";
import FemaleIcon from "@/public/images/female.svg";
import {
  User,
  Mail,
  Phone,
  MapPin,
  Edit,
  Camera,
  Building2,
  Map,
  Globe2,
  Calendar,
} from "lucide-react";
import { DEFAULT_LANGUAGE, getStoredLanguage, Language } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useToast } from "@/hooks/use-toast";
import { updateProfile } from "@/lib/api/apis";
import { uploadImageToBackend } from "@/lib/uploadImage";
import { notifyAuthChange } from "@/lib/authEvents";
import ImageUploadGuidelinesModal from "@/components/ImageUploadGuidelinesModal";
import Image from "next/image";

interface UserData {
  name: string;
  email: string;
  mobile: string;
  country?: string;
  state?: string;
  city?: string;
  avatar?: string;
  profile_picture?: string;
  id?: string;
  c_code?: string;
  gender?: string;
  date_of_birth?: string;
}

export default function ProfilePage() {
  const [user, setUser] = useState<UserData | null>(null);
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [mounted, setMounted] = useState(false);
  const [lang, setLang] = useState<Language>(DEFAULT_LANGUAGE);
  const { toast } = useToast();
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string>("");
  const [avatarUrl, setAvatarUrl] = useState<string>(""); // final uploaded URL
  const [loading, setLoading] = useState(false);
  const [showProfilePhotoModal, setShowProfilePhotoModal] = useState(false);

  const showErrorToast = (message: string) => {
    toast({
      // title: "Validation Error",
      description: message,
      variant: "destructive", // if your toast supports variants
    });
  };

  useEffect(() => {
    const storedData = localStorage.getItem("register_details");
    const stored = localStorage.getItem("user_data");

    if (storedData) {
      const parsed = JSON.parse(storedData);

      if (parsed?.country) {
        setUser(parsed);
        return;
      }
    }
    if (stored) {
      setUser(JSON.parse(stored));
    } else {
      router.push("/login");
    }
  }, [router]);

  useEffect(() => {
    const scrollToTop = (smooth: boolean = true) => {
      if (typeof window === "undefined") return;

      const scrollTopValue = 0; // 👈 step 3 scroll little down

      window.scrollTo({
        top: scrollTopValue,
        behavior: "smooth",
      });
    };
    scrollToTop();
  }, []);

  useEffect(() => {
    const handleProfile = async () => {
      const formData = new FormData();
      formData.append("user_id", user?.id || "");
      formData.append("name", user?.name || "");

      try {
        const res = await updateProfile(formData);
        if (res?.data) {
          setUser(res.data);
          localStorage.setItem("user_data", JSON.stringify(res.data));
          localStorage.setItem("register_details", JSON.stringify(res.data));
        }
      } catch (error) {
        console.error("Error fetching profile:", error);
      }
    };

    if (user?.id) {
      handleProfile();
    }
  }, [user?.id]);

  const handleAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !user) return;

    const allowedTypes = ["image/jpeg", "image/png"];

    if (!allowedTypes.includes(file.type)) {
      showErrorToast(t.profile.onlyJpgPng);
      e.target.value = "";
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      showErrorToast(t.profile.uploadUnder5mb);
      e.target.value = "";
      return;
    }

    // preview instantly
    const preview = URL.createObjectURL(file);
    setAvatarPreview(preview);

    try {
      setLoading(true);

      // upload to backend
      const uploadedUrl = await uploadImageToBackend(file);

      // save to backend
      const formData = new FormData();
      formData.append("user_id", user.id || "");
      formData.append("profile_picture", uploadedUrl);

      const res = await updateProfile(formData);

      if (res?.data) {
        toast({
          title: t.profile.photoSuccessTitle,
          description: t.profile.photoSuccess,
        });

        const updatedUser = {
          ...user,
          avatar: uploadedUrl,
          profile_picture: uploadedUrl,
        };
        setUser(updatedUser);
        localStorage.setItem("user_data", JSON.stringify(updatedUser));
        // Keep register_details in sync so the header shows the new photo
        if (localStorage.getItem("register_details")) {
          localStorage.setItem("register_details", JSON.stringify(updatedUser));
        }

        setAvatarUrl(uploadedUrl);
        // Let the header update its avatar immediately
        notifyAuthChange();
      } else {
        toast({
          description: res?.message || t.profile.photoFailed,
          variant: "destructive",
        });
      }
    } catch (error: any) {
      toast({
        description: error?.message || "Something went wrong",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
      e.target.value = ""; // allow selecting same file again
    }
  };

  const getGender = (gender: any) => {
    switch (String(gender)) {
      case "1":
        return t.profile.male;
      case "2":
        return t.profile.female;
      default:
        return t.profile.other;
    }
  };
  const formatDate = (date: string) => {
    if (!date) return "";
    return new Date(date).toLocaleDateString("en-GB");
  };

  useEffect(() => {
    setLang(getStoredLanguage());
    setMounted(true);
  }, []);

  if (!mounted) return null;

  const t = getTranslation(lang);

  if (!user) {
    return (
      <div className="text-center mt-20 text-gray-500">{t.profile.loading}</div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-orange-50 pt-28 pb-20">
      <div className="container mx-auto max-w-3xl px-4">
        <Card className="shadow-xl border border-orange-100">
          <CardContent className="p-8">
            <div className="flex flex-col items-center">
              <div className="relative w-24 h-24 mb-4">
                {avatarPreview || user?.profile_picture || user?.avatar ? (
                  <>
                    <img
                      src={
                        avatarPreview || user?.profile_picture || user?.avatar
                      }
                      alt="Profile"
                      className="w-24 h-24 rounded-full object-cover shadow-md"
                    />

                    {/* Loading Overlay */}
                    {loading && (
                      <div className="absolute inset-0 rounded-full bg-black/40 flex items-center justify-center">
                        <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      </div>
                    )}
                  </>
                ) : (
                  <div className="w-24 h-24 rounded-full bg-[#FFF4E4] flex items-center justify-center shadow-md overflow-hidden">
                    {String(user?.gender) === "1" ? (
                      <Image src={MaleIcon} alt="Male" className="h-24 w-24" />
                    ) : String(user?.gender) === "2" ? (
                      <Image
                        src={FemaleIcon}
                        alt="Female"
                        className="h-24 w-24"
                      />
                    ) : (
                      <span className="text-[#FAA631] text-3xl font-bold">
                        {user?.name?.charAt(0)?.toUpperCase() || "U"}
                      </span>
                    )}
                  </div>
                )}

                {/* Camera Icon */}
                <button
                  type="button"
                  onClick={() => setShowProfilePhotoModal(true)}
                  className="absolute bottom-0 right-0 w-8 h-8 rounded-full bg-white text-[#FAA631] flex items-center justify-center shadow border hover:bg-[#FFF4E4] transition"
                >
                  <Camera size={16} />
                </button>

                {/* Hidden Input */}
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/png,image/jpeg"
                  className="hidden"
                  onChange={handleAvatarChange}
                />
              </div>

              <h1 className="text-2xl font-semibold text-gray-800 mb-2">
                {user.name}
              </h1>
              <p className="text-gray-600 mb-6">{t.profile.welcome}</p>

              <div className="space-y-4 w-full">
                {user?.name && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <User className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">{user.name}</span>
                  </div>
                )}
                {user?.email && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <Mail className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">{user.email}</span>
                  </div>
                )}
                {user?.mobile && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <Phone className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">
                      {user.c_code} {user.mobile}
                    </span>
                  </div>
                )}

                {user?.gender && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <User className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">
                      {getGender(user.gender)}
                    </span>
                  </div>
                )}

                {user?.date_of_birth && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <Calendar className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">
                      {formatDate(user.date_of_birth)}
                    </span>
                  </div>
                )}

                {user?.city && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <Building2 className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">{user.city}</span>
                  </div>
                )}

                {user?.state && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <Map className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">{user.state}</span>
                  </div>
                )}

                {user?.country && (
                  <div className="flex items-center space-x-3 border-b border-gray-200 pb-2">
                    <Globe2 className="text-[#FAA631]" size={18} />
                    <span className="text-gray-700">{user.country}</span>
                  </div>
                )}
              </div>

              {/* ✏️ Edit Button */}
              <div className="mt-8">
                <Button
                  onClick={() => router.push("/profile/edit")}
                  className="bg-[#FAA631] hover:bg-[#e6972c] text-white text-lg px-6"
                >
                  <Edit className="mr-2" size={18} />
                  {t.profile.editProfile}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Image Upload Guidelines Modal */}
      <ImageUploadGuidelinesModal
        isOpen={showProfilePhotoModal}
        onConfirm={() => {
          setShowProfilePhotoModal(false);
          fileInputRef.current?.click();
        }}
        onCancel={() => setShowProfilePhotoModal(false)}
        title="Image Upload Guidelines"
      />
    </div>
  );
}
