"use client";

import { Button } from "@/components/ui/button";
import axiosInstance from "@/lib/axios";
import axios from "axios";
import { X } from "lucide-react";
import React, { useEffect, useState } from "react";
import { toast } from "react-toastify";
import LoadingSpinner from "../reusables/ui/LoadingSpinner";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import {
  setIsUserDeclined,
  setOtherUsersProfile,
} from "@/src/redux/profileSlice";
import { useGetSingleUser } from "@/src/utils/hooks/useGetSingleUser";

interface InterestProps {
  amount: any;
  id: any;
}

const AcceptInterests = ({ amount, id }: InterestProps) => {
  const [loading, setLoading] = useState(false);
  const [openModal, setOpenModal] = useState(false);

  const dispatch = useAppDispatch();

  const { data: user, refetch } = useGetSingleUser(id);

  useEffect(() => {
    if (user?.payload) {
      dispatch(setOtherUsersProfile(user.payload));
      console.log({ user });
    }
  }, [user, dispatch]);

 
  const handleInitiateSubscription = async () => {
    try {
      setLoading(true);
      const userId = localStorage.getItem("userId");

      if (!userId) {
        throw new Error("User not authenticated.");
      }

      const response = await axiosInstance.post(
        `/paystack/${userId}/initialize`,
        {
          amount: amount,
          subscribed_to_id: id,
        }
      );

      const authUrl = response.data.payload?.authorization_url;
      const message = response.data?.message || "Request completed.";

      if (authUrl) {
        toast.success(message);
        if (authUrl) {
          window.location.href = authUrl; // ✅ works reliably on all devices
        }
      } else {
        toast.success(message);

        await refetch();
      }
    } catch (error) {
      console.error("Error requesting address info:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleDecline = async () => {
    setLoading(true);
    const userToken = localStorage.getItem("userToken");
    const userId = localStorage.getItem("userId");
    const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

    try {
      const res = await axios.post(
        `${apiUrl}/users/${userId}/dashboard/decline/${id}`,
        {},
        {
          headers: {
            Authorization: `Bearer ${userToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      toast.success("User successfully declined");
      dispatch(setIsUserDeclined(true));
      setLoading(false);
      refetch();
    } catch (err) {}
  };

  return (
    <div>
      <div className="flex flex-col md:flex-row items-center gap-4">
        <Button
          className={`text-white text-xs px-4 py-1 rounded-full ${"bg-[#EF2424] hover:bg-[#EF2424]/80"}`}
          onClick={() => setOpenModal(true)}
          disabled={loading}
        >
          Accept
        </Button>
        <Button
          variant="outline"
          className="border-red-500 text-red-500 text-xs px-4 py-1 rounded-full hover:bg-red-50"
          onClick={() => handleDecline()}
        >
          {loading ? <LoadingSpinner /> : "Decline"}
        </Button>
      </div>

      {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 */}

            <p className="mb-10 text-sm">
              Are you sure you want to subscribe back to this person?
            </p>

            <div className="flex items-center justify-end w-full gap-4">
              <Button
                onClick={handleInitiateSubscription}
                disabled={loading}
                className="bg-[#EF2424] hover:bg-[#EF2424]/90 text-white rounded-full cursor-pointer"
              >
                {loading ? <LoadingSpinner /> : "Yes, continue"}
              </Button>
              <Button
                onClick={() => setOpenModal(false)}
                className="border border-[#EF2424] bg-white text-[#EF2424] rounded-full cursor-pointer"
              >
                No
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default AcceptInterests;
