/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import Container from "@/components/elements/Container";
import React, { useState, useEffect } from "react";

import AuthNextButton from "@/components/auth/AuthNextButton";
import Image from "next/image";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import { useUser } from "@/hooks/useUser";
import { formatFullName } from "@/lib/formatFullName";
import { BASE_URL, IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import Cookies from "js-cookie";
import axios from "axios";

function LicensePage() {
  const user = useUser();
  const { loading } = useAxios();
  const userId = user?._id; // فرض بر وجود user.id به عنوان _id

  const [avatar, setAvatar] = useState<string | null>(null);
  const [license, setLicense] = useState<any>(null);
  const [loadingUpload, setLoadingUpload] = useState(false);

  // دریافت اطلاعات License هنگام لود صفحه
  useEffect(() => {
    if (userId) {
      fetchLicense();
    }
  }, [userId]);


  const fetchLicense = async () => {
    try {
      // گرفتن توکن از کوکی
      const token = Cookies.get("token");
      if (!token) {
        toast.error("توکن یافت نشد، لطفاً دوباره وارد شوید");
        return;
      }
  
      const response = await axios.get(`${BASE_URL}/users/License/${userId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
  
      setLicense(response.data);
  
      if (response.data.licenseImg) {
        setAvatar(response.data.licenseImg);
      }
    } catch (error) {
      
      console.error(error);
      
    }
  };

  // Compress image and convert to Base64
  const compressImage = (
    file: File,
    maxWidth: number,
    maxHeight: number,
    quality: number
  ): Promise<string> => {
    return new Promise((resolve, reject) => {
      const img = new window.Image();
      const reader = new FileReader();
      reader.onload = (e) => {
        img.src = e.target?.result as string;
        img.onload = () => {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");
          if (!ctx) {
            reject(new Error("Canvas context not supported"));
            return;
          }

          let width = img.width;
          let height = img.height;

          if (width > height) {
            if (width > maxWidth) {
              height = Math.round((height * maxWidth) / width);
              width = maxWidth;
            }
          } else {
            if (height > maxHeight) {
              width = Math.round((width * maxHeight) / height);
              height = maxHeight;
            }
          }

          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(img, 0, 0, width, height);
          resolve(canvas.toDataURL("image/jpeg", quality));
        };
        img.onerror = () => reject(new Error("Failed to load image"));
      };
      reader.readAsDataURL(file);
    });
  };

  // Select and compress image
  const selectImage = async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      if (!file.type.startsWith("image/")) {
        toast.error("فقط فایل‌های تصویری مجاز هستند");
        return;
      }
      try {
        setLoadingUpload(true);
        const compressedBase64 = await compressImage(file, 800, 800, 0.7);
        setAvatar(compressedBase64);
      } catch (error) {
        toast.error("خطا در بارگذاری تصویر");
        console.error("Image compression error:", error);
      } finally {
        setLoadingUpload(false);
      }
    }
  };

  // Remove image (local)
  const removeImage = () => {
    setAvatar(null);
    const fileInput = document.getElementById("fileInput") as HTMLInputElement;
    if (fileInput) fileInput.value = "";
  };

  const upload = async () => {
    if (!avatar) {
      toast.error("لطفاً یک تصویر انتخاب کنید");
      return;
    }

    try {
      setLoadingUpload(true);

      // گرفتن توکن از کوکی
      const token = Cookies.get("token");
      if (!token) {
        toast.error("توکن یافت نشد، لطفاً دوباره وارد شوید");
        return;
      }

      const response = await axios.post(
        `${BASE_URL}/users/License`,
        { image: avatar, userId },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (response.status === 201) {
        toast.success("تصویر با موفقیت آپلود شد");
        setLicense(response.data.license);
        
      }
    } catch (error) {
      toast.error("خطا در آپلود تصویر");
      console.error( error);
    } finally {
      setLoadingUpload(false);
    }
  };



  return (
    <Container>
      <div className="p-4 flex flex-col items-center justify-center address-page">
        <span className="text-xl mb-9 font-bold">بارگذاری مجوز</span>

        <div className="flex flex-col justify-center items-center">
          <ProfileAvatar
            src={user?.profile_image}
            alt={user?.user_name || "user profile"}
            size="md"
            rounded="2xl"
            className="h-[130px] w-[130px]"
            fallback="/images/placeholder.png"
          />
          <div className="flex flex-col justify-center items-center gap-1 mt-1">
            <span>{formatFullName(user?.first_name, user?.last_name)}</span>
            <div className="flex flex-col justify-center items-center gap-1 mt-1">
              {user?.user_name}
            
            </div>
          </div>
        </div>
        <small className="font-bold mt-10 mb-4 text-center">
          برای ثبت درخواست نیازمند احراز هویت شما هستیم
        </small>

        <div className="flex flex-col items-center justify-center">
          {loading || loadingUpload ? (
            <p>Loading...</p>
          ) : (
            <>
              <div className="flex flex-col items-center mb-4">
                <div className="relative w-[250px] h-[250px] flex items-center justify-center text-white rounded-3xl border border-[#676767] overflow-hidden mt-10">
                  {avatar ? (
                    <>
                      <img
                        src={avatar}
                        alt="License Image"
                        className="w-full h-full 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 license 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 license icon"
                      />
                    </label>
                  )}
                </div>
                <input
                  id="fileInput"
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={selectImage}
                />
              </div>
              {license && (
                <div className="flex flex-col items-center mt-4 text-green-700">
                  <p>وضعیت تأیید: {license.Confirmation ? "تأیید شده" : "در انتظار تأیید"}</p>
                </div>
              )}
            </>
          )}
        </div>

        <small className="font-bold mt-10 mb-4 text-center">
          برای دریافت تیک طلایی مجوز خود را بارگذاری کنید
        </small>

        <div className="flex">
          <div>
            <svg
              width="80"
              height="80"
              viewBox="0 0 80 80"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                opacity="0.4"
                d="M35.8331 8.16689C38.1331 6.20023 41.8998 6.20023 44.2331 8.16689L49.4998 12.7002C50.4998 13.5669 52.3664 14.2669 53.6998 14.2669H59.3664C62.8998 14.2669 65.7998 17.1669 65.7998 20.7002V26.3669C65.7998 27.6669 66.4998 29.5669 67.3664 30.5669L71.8998 35.8336C73.8664 38.1336 73.8664 41.9002 71.8998 44.2336L67.3664 49.5002C66.4998 50.5002 65.7998 52.3669 65.7998 53.7002V59.3669C65.7998 62.9002 62.8998 65.8002 59.3664 65.8002H53.6998C52.3998 65.8002 50.4998 66.5002 49.4998 67.3669L44.2331 71.9002C41.9331 73.8669 38.1664 73.8669 35.8331 71.9002L30.5664 67.3669C29.5664 66.5002 27.6998 65.8002 26.3664 65.8002H20.5998C17.0664 65.8002 14.1664 62.9002 14.1664 59.3669V53.6669C14.1664 52.3669 13.4664 50.5002 12.6331 49.5002L8.13311 44.2002C6.19977 41.9002 6.19977 38.1669 8.13311 35.8669L12.6331 30.5669C13.4664 29.5669 14.1664 27.7002 14.1664 26.4002V20.6669C14.1664 17.1336 17.0664 14.2336 20.5998 14.2336H26.3664C27.6664 14.2336 29.5664 13.5336 30.5664 12.6669L35.8331 8.16689Z"
                fill="#dbd40b"
              />
              <path
                d="M35.9665 50.5668C35.2999 50.5668 34.6665 50.3001 34.1999 49.8334L26.1332 41.7668C25.1665 40.8001 25.1665 39.2001 26.1332 38.2334C27.0999 37.2668 28.6999 37.2668 29.6665 38.2334L35.9665 44.5334L50.2999 30.2001C51.2665 29.2334 52.8665 29.2334 53.8332 30.2001C54.7999 31.1668 54.7999 32.7668 53.8332 33.7334L37.7332 49.8334C37.2665 50.3001 36.6332 50.5668 35.9665 50.5668Z"
                fill="#f5f507"
              />
            </svg>
          </div>
        </div>
        <AuthNextButton onClick={upload} className="mt-20" loading={loadingUpload} disabled={loadingUpload}>
          ثبت و ادامه
        </AuthNextButton>
        <small className="font-bold mt-10 mb-1 text-center">
          زمان تایید مدارک 5 دقیقه تا 1 ساعت در ساعات اداری و
        </small>
        <small className="font-bold text-center">
          3 تا 8 ساعت در ساعات غیر اداری
        </small>
      </div>
    </Container>
  );
}

export default LicensePage;