"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import api from "@/api/axios";
import { toast } from "sonner";
import AppLoader from "@/components/Loading";

type Country = {
  id: number;
  name: string;
  phone_code: string;
  iso2: string;
};

export default function ProfilePage() {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [mobile, setMobile] = useState("");
  const [countryId, setCountryId] = useState<number | null>(null);
  const [isCountryOpen, setIsCountryOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const [countries, setCountries] = useState<Country[]>([]);
  const [selectedCountry, setSelectedCountry] = useState<Country | null>(null);

  /* =====================
     Load LocalStorage
  ====================== */
  useEffect(() => {
    if (typeof window !== "undefined") {
    setFirstName(localStorage.getItem("user_fName") || "");
    setLastName(localStorage.getItem("user_lName") || "");
    setEmail(localStorage.getItem("user_email") || "");
    setMobile(localStorage.getItem("user_mobile") || "");}
  }, []);

  /* =====================
     Fetch Countries
  ====================== */
  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const res = await api.get("/countries");
        if (res.data.success) {
          setCountries(res.data.data.countries);

          // افتراضياً السعودية
          const defaultCountry = res.data.data.countries.find(
            (c: Country) => c.iso2 === "SA"
          );
          if (defaultCountry) {
            setSelectedCountry(defaultCountry);
            setCountryId(defaultCountry.id);
          }
        }
      } catch (error) {
        console.error(error);
      } finally {
        setLoading(false);
      }
    };

    fetchCountries();
  }, []);

  /* =====================
     Submit
  ====================== */
  const handleSubmit = async () => {
    try {
      setLoading(true);
      const res = await api.post("auth/profile/update", {
        first_name: firstName,
        last_name: lastName,
        country_id: countryId,
        mobile,
        email,
      });

      if (res.data.success) {
        toast.success("تم حفظ التعديلات بنجاح");
        if (typeof window !== "undefined" && res?.data?.data) {
        localStorage.setItem("user_fName", firstName);
        localStorage.setItem("user_lName", lastName);
        localStorage.setItem("user_email", email);
        localStorage.setItem("user_mobile", mobile);}
      }
    } catch (error) {
      toast.error("حدث خطأ أثناء حفظ التعديلات");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-white flex justify-center px-4 mt-[100px]">
      <div className="w-full max-w-md pt-8">
        {loading ? (
          <AppLoader variant="card" />
        ) : (
          <>
            <h1 className="text-right font-book text-[18px] text-basic-color mb-6">
              تعديل معلومات الملف الشخصي
            </h1>
            {/* Avatar */}
            <div className="flex items-center justify-right gap-3 mb-6">
              <Image
                src="/images/user2.svg"
                alt="User"
                width={48}
                height={48}
              />
              <span className="text-sm text-gray-600">صورة الملف الشخصي</span>
            </div>
            <div className="flex flex-col gap-4">
              {/* First Name */}
              <div className="mb-2">
                <label className="text-xs text-gray-500 mb-1 block">
                  الاسم الأول
                </label>
                <input
                  className="input-style w-full"
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  placeholder="اكتب اسمك الأول"
                />
              </div>
              {/* Last Name */}
              <div className="mb-2">
                <label className="text-xs text-gray-500 mb-2 block">
                  الاسم الأخير
                </label>
                <input
                  className="input-style w-full"
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  placeholder="اكتب اسمك الأخير"
                />
              </div>
              {/* Mobile */}
              <div className="mb-2">
                <label className="text-xs text-gray-500 mb-1 block">
                  رقم الموبايل
                </label>

                <div className="flex gap-2">
                  {/* Country Dropdown */}
                  <div className="relative w-[110px]">
                    <button
                      type="button"
                      onClick={() => setIsCountryOpen(!isCountryOpen)}
                      className="w-full bg-gray-100 rounded-md px-2 py-3 flex items-center gap-2
                   text-sm focus:outline-none"
                    >
                      {selectedCountry && (
                        <>
                          <img
                            src={`https://flagcdn.com/w20/${selectedCountry.iso2.toLowerCase()}.png`}
                            alt={selectedCountry.iso2}
                            className="w-5 h-4 object-cover"
                          />
                          <span>+{selectedCountry.phone_code}</span>
                        </>
                      )}
                    </button>

                    {isCountryOpen && (
                      <div
                        className="absolute z-50 mt-1 w-full max-h-56 overflow-y-auto
                        bg-white rounded-md shadow-lg"
                      >
                        {countries.map((c) => (
                          <button
                            key={c.id}
                            type="button"
                            onClick={() => {
                              setSelectedCountry(c);
                              setCountryId(c.id);
                              setIsCountryOpen(false);
                            }}
                            className="flex items-center gap-2 px-3 py-2 text-sm w-full
                         hover:bg-gray-100 text-right"
                          >
                            <img
                              src={`https://flagcdn.com/w20/${c.iso2.toLowerCase()}.png`}
                              alt={c.iso2}
                              className="w-5 h-4 object-cover"
                            />
                            <span>+{c.phone_code}</span>
                          </button>
                        ))}
                      </div>
                    )}
                  </div>

                  {/* Mobile Input */}
                  <input
                    className="input-style flex-1"
                    value={mobile}
                    onChange={(e) => setMobile(e.target.value)}
                    placeholder="رقم الموبايل"
                  />
                </div>
              </div>

              {/* Email */}
              <div className="mb-2">
                <label className="text-xs text-gray-500 mb-1 block">
                  البريد الإلكتروني
                </label>
                <input
                  className="input-style w-full"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="أدخل بريدك الإلكتروني"
                />
              </div>

              {/* Save */}
              <button
                onClick={handleSubmit}
                disabled={loading}
                className="w-full bg-[#FF2B77] text-white py-3 rounded-md font-medium hover:opacity-90 transition"
              >
                {loading ? "جاري حفظ التعديل" : "حفظ التعديل"}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
