"use client";

import React, { useEffect, useState, useCallback } from "react";
import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { IProfileData } from "@/types/types";
import Image from "next/image";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";

// کتابخانه برای crop
import Cropper from "react-easy-crop";
import getCroppedImg from "@/helpers/cropImage";
import { Area } from "react-easy-crop";

function AvatarPage() {
  const router = useRouter();
  const { request, loading } = useAxios();
  const [userDetail, setUserDetail] = useState<IProfileData | null>(null);
  const [avatar, setAvatar] = useState<string | null>(null);
  const [crop, setCrop] = useState({ x: 0, y: 0 });
  const [zoom, setZoom] = useState(1);
  const [loadingUpload, setLoadingUpload] = useState(false);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);

  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  const fetchData = async () => {
    try {
      const response = await request<{ user: IProfileData }>("GET", "/profile");
      setUserDetail(response?.user || null);
      setAvatar(response?.user?.profile_image || null);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // انتخاب تصویر
  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 = (e) => {
        const imageDataUrl = e.target?.result as string;
        setAvatar(imageDataUrl);
      };
      reader.readAsDataURL(file);
    }
  };

  // حذف تصویر
  // const removeImage = () => {
  //   setAvatar(null);
  //   setOriginalImage(null);
  // };

  // دریافت مختصات crop شده
  const onCropComplete = useCallback(
    (croppedArea: Area, croppedPixels: Area) => {
      setCroppedAreaPixels(croppedPixels);
    },
    []
  );

  // تبدیل crop شده به blob
  const createCroppedImage = async () => {
    if (!avatar || !croppedAreaPixels) return null;
    const croppedImage = await getCroppedImg(avatar, croppedAreaPixels);
    return croppedImage;
  };

  // آپلود تصویر
  const uploadImage = async () => {
    if (!avatar) {
      toast.error("لطفا تصویر پروفایل را انتخاب کنید");
      return;
    }
    setLoadingUpload(true);
    const croppedBlob = await createCroppedImage();
    if (!croppedBlob) {
      toast.error("خطا در برش تصویر");
      setLoadingUpload(false);
      return;
    }

    const formData = new FormData();
    formData.append("profile_image", croppedBlob, "avatar.jpg");
    formData.append("mobile", mobile as string);

    try {
      await request("POST", "/verify/profile_image", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      toast.success("تصویر با موفقیت ثبت شد!");
      navigateHandler();
    } catch (err) {
      console.log("Upload error:", err);
      toast.error("خطا در ارسال تصویر!");
      setLoadingUpload(false);
    }
  };

  // ناوبری بعد از آپلود
  const navigateHandler = () => {
    if (userDetail?.user_type === "user") {
      router.push("/verify/expertise");
    } else {
      router.push("/verify/gender");
    }
  };

  return (
    <AuthPageLayout>
      <AuthPageContent>
        <span className="text-xl font-bold mb-4">تصویر پروفایل</span>

        <div className="relative aspect-square w-[250px] bg-gray-200 rounded-3xl overflow-hidden mb-4">
              {avatar ? (
                <Cropper
                  image={avatar.startsWith("data:") ? avatar : IMAGE_BASE_URL + avatar}
                  crop={crop}
                  zoom={zoom}
                  aspect={1} // مربع 1:1
                  onCropChange={setCrop}
                  onZoomChange={setZoom}
                  onCropComplete={onCropComplete}
                  cropShape="rect"
                  showGrid={false}
                  objectFit="contain" // نمایش کامل تصویر
                />
              ) : (
                <label
                  htmlFor="fileInput"
                  className="cursor-pointer w-full h-full flex items-center justify-center"
                >
                  <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}
            />

        <AuthNextButton className="mt-4">
          <label className="cursor-pointer w-full h-full" htmlFor="fileInput">
            انتخاب/ویرایش تصویر
          </label>
        </AuthNextButton>
      </AuthPageContent>

      <AuthFormFooter
        onSkip={navigateHandler}
        skipDisabled={loadingUpload}
      >
        <AuthNextButton
          onClick={uploadImage}
          loading={loadingUpload}
          disabled={loadingUpload}
        >
          ثبت و ادامه
        </AuthNextButton>
      </AuthFormFooter>
    </AuthPageLayout>
  );
}

export default AvatarPage;