"use client";

import AuthNextButton from "@/components/auth/AuthNextButton";
import Container from "@/components/elements/Container";
import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { useUser } from "@/hooks/useUser";
import Image from "next/image";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";

function AvatarPage() {
  const router = useRouter();
  const user = useUser();
  const [avatar, setAvatar] = useState<string | null>(null);
  const [loadingUpload, setLoadingUpload] = useState(false);

  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  useEffect(() => {
    setAvatar(user?.profile_image || null);
  }, [user]);

  // Select image
  const selectImage = async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = () => setAvatar(reader.result as string);
      reader.readAsDataURL(file);
    }
  };

  // Upload image
  const uploadImage = async () => {
    if (!avatar) {
      toast.error("لطفا تصویر پروفایل را انتخاب کنید");
    } else {
      setLoadingUpload(true);

      const formData = new FormData();
      // اطمینان حاصل کنید که داده تصویر درست به سرور ارسال می‌شود
      const fileInput = document.getElementById(
        "fileInput"
      ) as HTMLInputElement;
      if (fileInput?.files?.[0]) {
        formData.append("profile_image", fileInput.files[0]);
      }
      formData.append("mobile", mobile as string);

      try {
        if (avatar.startsWith("data:")) {
          await request("PATCH", "/verify/profile_image", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });
          router.push("/settings/edit");
        } else {
          setLoadingUpload(false);
        }
      } catch (err) {
        console.log("Upload error:", err);
        setLoadingUpload(false);
      }
    }
  };

  // Remove image
  const removeImage = () => {
    setAvatar(null);
  };



  return (
    <Container>
      <div className="p-4 flex flex-col items-center h-screen justify-center">
        <div className="flex flex-col items-center mb-4">
          <span className="text-xl font-bold text-foreground">تصویر پروفایل</span>
          <div className="relative aspect-square w-[250px] flex items-center justify-center text-white rounded-3xl border border-[#676767] overflow-hidden mt-10">
                {avatar ? (
                  <>
                    <img
                      src={
                        avatar.startsWith("data:")
                          ? avatar
                          : IMAGE_BASE_URL + avatar
                      }
                      alt="Avatar"
                      className="w-full h-full aspect-square object-cover"
                    />
                    <button
                      onClick={removeImage}
                      className="p-4 absolute top-0 right-0"
                    >
                      <Image
                        src={"/images/icons/close-circle.svg"}
                        width={25}
                        height={25}
                        alt="remove profile icon"
                      />
                    </button>
                  </>
                ) : (
                  <label
                    htmlFor="fileInput"
                    className="cursor-pointer w-[250px] h-[250px] flex items-center justify-center text-white rounded-3xl border border-[#676767] "
                  >
                    <Image
                      src={"/images/icons/gallery-add.svg"}
                      width={120}
                      height={120}
                      alt="add profile icon"
                    />
                  </label>
                )}
              </div>
              <input
                id="fileInput"
                type="file"
                accept="image/*"
                className="hidden"
                onChange={selectImage}
              />
            </div>
            <AuthNextButton className="mt-2">
              <label
                className="cursor-pointer w-full h-full"
                htmlFor="fileInput"
              >
                ویرایش تصویر
              </label>
            </AuthNextButton>

        <AuthNextButton
          onClick={uploadImage}
          className="mt-20"
          loading={loadingUpload}
          disabled={loadingUpload || loading}
        >
          ویرایش
        </AuthNextButton>
      </div>
    </Container>
  );
}

export default AvatarPage;
