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

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

function NationalCart() {
  const router = useRouter();
  const { request, loading } = useAxios();

  const [nationalCartImg, setNationalCartImg] = useState<string | null>(null);
  const [isCheckedOne, setIsCheckedOne] = useState(false);
  const [isModalOpen, setModalOpen] = useState<boolean>(false);

  const toggleCheckBox = () => setIsCheckedOne(!isCheckedOne);

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

  // انتخاب عکس از دوربین یا فایل
  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 = () => setNationalCartImg(reader.result as string);
      reader.readAsDataURL(file);
    }
  };

  // حذف تصویر
  const removeImage = () => setNationalCartImg(null);

  // ارسال فرم
  const uploadImage = async () => {
    if (!nationalCartImg) {
      toast.error("لطفا تصویر کارت ملی را انتخاب کنید");
      return;
    }
    if (!isCheckedOne) {
      toast.error("لطفا قوانین را مطالعه و تایید کنید");
      return;
    }

    const formData = new FormData();
    const fileInput = document.getElementById("fileInput") as HTMLInputElement;
    if (fileInput?.files?.[0]) {
      formData.append("national_card_image", fileInput.files[0]);
    }
    formData.append("mobile", mobile as string);

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

  return (
    <Container>
      <div className="p-4 flex flex-col items-center h-screen justify-center address-page">
        <span className="text-xl font-bold text-foreground">احراز هویت</span>
        <div className="mt-5">
          <AuthUserDetails />
        </div>

        <small className="font-bold mt-10 mb-4">
          برای ثبت درخواست، نیازمند احراز هویت شما هستیم
        </small>

        <div className="relative w-[150px] h-[150px] flex items-center justify-center text-white rounded-3xl border border-[#676767] overflow-hidden mt-4">
          {nationalCartImg ? (
            <>
              <img
                src={
                  nationalCartImg.startsWith("data:")
                    ? nationalCartImg
                    : IMAGE_BASE_URL + nationalCartImg
                }
                alt="nationalCartImg"
                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 profile icon"
                />
              </button>
            </>
          ) : (
            <label
              htmlFor="fileInput"
              className="cursor-pointer w-[150px] h-[150px] flex items-center justify-center text-white rounded-3xl border border-[#676767]"
            >
              <Image
                src={"/images/icons/gallery-add.svg"}
                width={76}
                height={76}
                alt="add profile icon"
              />
            </label>
          )}
        </div>

        <input
          id="fileInput"
          type="file"
          accept="image/*"
          capture="environment" // 🔥 مستقیم دوربین پشت
          className="hidden"
          onChange={selectImage}
        />

        <small className="font-bold mt-10 mb-4">
          اصل کارت ملی را بر روی سینه در دست گرفته و از خود عکس بگیرید
        </small>

        <div className="flex items-center gap-2 mt-10">
          <input
            className="scale-125"
            type="checkbox"
            onChange={toggleCheckBox}
          />
          <span
            onClick={() => setModalOpen(true)}
            className="text-xs font-bold cursor-pointer"
          >
            تایید قوانین و مقررات
          </span>
        </div>

        <AuthNextButton
          onClick={uploadImage}
          className="mt-20"
          loading={loading} disabled={loading}
        >
          ثبت و ادامه
        </AuthNextButton>

        <button
          className="text-sm text-gray-500 mt-5"
          onClick={() => router.push("/settings/edit")}
          type="button"
        >
          رد کن
        </button>

        <AuthRules isModalOpen={isModalOpen} setModalOpen={setModalOpen} />
      </div>
    </Container>
  );
}

export default NationalCart;
