import { IoCameraReverseOutline } from "react-icons/io5";

interface User {
  profile?: string;
  username?: string;
  address?: {
    city?: { name?: string };
    state?: { name?: string };
  };
  createdAt?: string;
}

interface ProfileImageProps {
  profile: string | undefined;
  user?: User;
  isUploading: boolean;
  fileInputRef: React.RefObject<HTMLInputElement>;
  handleImageChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

export const ProfileImage = ({
  profile,
  isUploading,
  fileInputRef,
  user,
  handleImageChange,
}: ProfileImageProps) => {
  return (
    <div className="relative w-32 h-32 rounded-full border-4 border-primary100 shadow-md max-sm:mt-12 dark:border-darkborder max-lg:w-24 max-lg:h-24 max-md:w-28 max-md:h-28">
      <img
        src={
          user?.profile
            ? user.profile.startsWith("http")
              ? user.profile
              : `${process.env.NEXT_PUBLIC_API}/${user?.profile}`
            : "/profile-avatar.png"
        }
        alt="User"
        className="w-full h-full object-cover rounded-full"
        onError={(e) => {
          if (e.currentTarget.src.endsWith("/profile-avatar.png")) return;
          e.currentTarget.onerror = null;
          e.currentTarget.src = "/profile-avatar.png";
        }}
      />
      <button
        onClick={() => {
          if (!isUploading && fileInputRef.current) {
            fileInputRef.current.click();
          }
        }}
        disabled={isUploading}
        className={`w-8 h-8 flex justify-center items-center absolute bottom-0 z-10 right-0 bg-white border-primary100 text-primary border border-primary rounded-full p-1 shadow dark:bg-background dark:border-darkborder rtl:left-0 rtl:right-auto ${
          isUploading
            ? "opacity-50 cursor-not-allowed"
            : "hover:bg-primary transition"
        }`}
        aria-label="Profile Image"
      >
        {isUploading ? (
          <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
        ) : (
          <IoCameraReverseOutline className="text-lg text-primary500 dark:text-white" />
        )}
      </button>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={handleImageChange}
      />
    </div>
  );
};
