"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { useAppSelector } from "@/src/redux/hook";
import { FaLocationDot } from "react-icons/fa6";

import { X } from "lucide-react";
import axiosInstance from "@/lib/axios";
import useGeolocation from "@/src/utils/hooks/useGeolocation";
import LocationPermissionPopup from "./LocationPermissionPopup";
import axios from "axios";

export default function RequestAddressCheck() {
  const [loading, setLoading] = useState(false);
  const [openModal, setOpenModal] = useState(false);
  const [openModal2, setOpenModal2] = useState(false);

  const houseNumber = useAppSelector((state) => state.profile.houseNumber);
  const streetName = useAppSelector((state) => state.profile.streetName);
  const lga = useAppSelector((state) => state.profile.lga);
  const landmark = useAppSelector((state) => state.profile.landmark);
  const postcode = useAppSelector((state) => state.profile.postcode);
  const state = useAppSelector((state) => state.profile.state);
  const country = useAppSelector((state) => state.profile.country);

  const handleInitiateAddress = async () => {
    try {
      setLoading(true);

      // Ask for geolocation only when user confirms
      const coords = await new Promise<{ lat: number; lng: number }>(
        (resolve, reject) => {
          if (!navigator.geolocation) {
            return reject(new Error("Geolocation not supported"));
          }

          navigator.geolocation.getCurrentPosition(
            (position) => {
              resolve({
                lat: position.coords.latitude,
                lng: position.coords.longitude,
              });
            },
            (error) => reject(error)
          );
        }
      );

      const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];
      const userToken = localStorage.getItem("userToken");
      const userId = localStorage.getItem("userId");

      if (!userId) {
        throw new Error("UserID not found.");
      }

      const response = await axiosInstance.post(
        `/paystack/address/${userId}/initialize`,
        {
          latitude: coords.lat.toString(),
          longitude: coords.lng.toString(),
        }
        // {
        //   headers: {
        //     Authorization: `Bearer ${userToken}`,
        //     "Content-Type": "application/json",
        //   },
        // }
      );

      const authUrl = response.data.payload?.authorization_url;
      if (authUrl) {
        window.location.href = authUrl; 
      } else {
        throw new Error("Authorization URL not found.");
      }
    } catch (error) {
      console.error("Error requesting address info:", error);
    } finally {
      setLoading(false);
      setOpenModal2(false);
    }
  };

  return (
    <>
      <Button
        onClick={() => setOpenModal(true)}
        disabled={loading}
        className="bg-[#EF2424] hover:bg-[#EF2424] text-white rounded-full h-9 px-4 cursor-pointer"
      >
        Request address verification
      </Button>

      {openModal && (
        <div
          onClick={() => setOpenModal(false)}
          className="fixed inset-0 bg-black/40 backdrop-blur-md flex items-center justify-center z-50"
        >
          {/* Modal Box */}
          <div
            onClick={(e) => e.stopPropagation()}
            className="bg-white rounded-lg p-6 w-[90%] max-w-md relative shadow-lg"
          >
            {/* Cancel Icon */}
            <button
              onClick={() => setOpenModal(false)}
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 transition"
              aria-label="Close"
            >
              <X className="w-5 h-5" />
            </button>

            {/* Modal Content */}
            <h2 className="text-lg font-semibold mb-4">Warning</h2>
            <p className="mb-10 text-sm">
              Please ensure that this device is currently at the location
              registered with this account before proceeding with this process
              for an authentic verification.
            </p>

            <div className="flex justify-end gap-4">
              <Button
                onClick={() => setOpenModal(false)}
                className="bg-[#808080] text-white rounded-full"
              >
                Cancel
              </Button>
              <Button
                onClick={() => {
                  setOpenModal(false);
                  setOpenModal2(true);
                }}
                disabled={loading}
                className="bg-[#EF2424] hover:bg-[#EF2424]/90 text-white rounded-full"
              >
                {/* {loading ? "Requesting..." : "Yes, continue"} */}
                Proceed
              </Button>
            </div>
          </div>
        </div>
      )}

      {openModal2 && (
        <LocationPermissionPopup
          onAllow={() => {
            handleInitiateAddress();
          }}
          onDeny={() => {
            setOpenModal2(false);
          }}
          loading={loading}
        />
      )}
    </>
  );
}
