import { ChevronDown, CreditCard, Settings, LogOut } from "lucide-react";
import { useEffect, useState, type Dispatch, type SetStateAction } from "react";
import { useNavStore } from "../store";
import type { contentType } from "../content/content";
import Cookies from "js-cookie";
import { getBalance, type UserBalance } from "../getBalance";

const refreshBalance = async (
  setBalance: Dispatch<SetStateAction<UserBalance | null>>
) => {
  try {
    const data = await getBalance();
    setBalance(data);
  } catch (err) {
    console.log("error", err);
  }
};

export function Profile({ content }: { content: contentType["profile"] }) {
  const [profileOpen, setProfileOpen] = useState(false);
  const { user, logout, selectedLang } = useNavStore();

  const [balance, setBalance] = useState<UserBalance | null>(null);

  useEffect(() => {
    refreshBalance(setBalance);
  }, []);

  if (!user) return null;

  // Check if profilePicture is a URL or a color
  const isImageUrl =
    user.profilePicture.startsWith("http") ||
    user.profilePicture.startsWith("/avatars/");
  const firstLetter = user.username.charAt(0).toUpperCase();

  return (
    <div className="relative">
      <button
        onClick={() => setProfileOpen(!profileOpen)}
        className="flex cursor-pointer items-center gap-2 px-3 py-2 rounded-lg hover:bg-gray-50 transition-colors"
      >
        <div
          className="w-8 h-8 rounded-full flex items-center justify-center text-white font-semibold text-sm overflow-hidden"
          style={{
            backgroundColor: isImageUrl ? undefined : user.profilePicture,
          }}
        >
          {isImageUrl ? (
            <img
              src={user.profilePicture}
              alt={user.username}
              className="w-full h-full object-cover"
            />
          ) : (
            firstLetter
          )}
        </div>
        <ChevronDown
          className={`w-4 h-4 text-gray-500 transition-transform ${
            profileOpen ? "rotate-180" : ""
          }`}
        />
      </button>

      {profileOpen && (
        <div
          className="fixed inset-0 z-10"
          onClick={() => setProfileOpen(false)}
        />
      )}
      <div
        className={`absolute mt-2 w-72 bg-white rounded-lg shadow-lg border border-gray-100 z-20 transition-all duration-200 ease-out ${
          selectedLang.code === "ar" ? "left-0" : "right-0"
        } ${
          profileOpen
            ? "opacity-100 scale-100"
            : "opacity-0 scale-95 pointer-events-none"
        }`}
      >
        {/* User Info Section */}
        <div className="p-4 border-b border-gray-100">
          <div className="flex items-center gap-3 mb-3">
            <div
              className="w-12 h-12 rounded-full flex items-center justify-center text-white font-semibold text-lg overflow-hidden"
              style={{
                backgroundColor: isImageUrl ? undefined : user.profilePicture,
              }}
            >
              {isImageUrl ? (
                <img
                  src={user.profilePicture}
                  alt={user.username}
                  className="w-full h-full object-cover"
                />
              ) : (
                firstLetter
              )}
            </div>
            <div className="flex-1">
              <p className="font-semibold text-gray-900">{user.username}</p>
              <p className="text-sm text-gray-500">{user.email}</p>
            </div>
          </div>

          {/* Credits Display */}
          <div className="bg-gray-50 rounded-lg p-3 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <CreditCard className="w-4 h-4 text-gray-600" />
              <span className="text-sm text-gray-600">{content.credits}</span>
            </div>
            <span className="font-semibold text-gray-900">
              ${balance?.credits}
            </span>
          </div>
        </div>

        {/* Menu Items */}
        <div className="py-2">
          <a
            href="/settings"
            className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-gray-50 transition-colors"
          >
            <Settings className="w-4 h-4 text-gray-600" />
            <span className="text-sm text-gray-700">
              {content.accountSettings}
            </span>
          </a>
        </div>

        {/* Sign Out */}
        <div className="border-t border-gray-100 py-2">
          <button
            onClick={(e) => {
              e.preventDefault();
              logout();
              if (typeof window !== "undefined") {
                Cookies.remove("userInfo");
              }
              setProfileOpen(false);
            }}
            className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-gray-50 transition-colors text-red-600"
          >
            <LogOut className="w-4 h-4" />
            <span className="text-sm font-medium">{content.signOut}</span>
          </button>
        </div>
      </div>
    </div>
  );
}
