"use client";

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

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

const ShowInterest = ({ 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));
    }
  }, [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); // Show toast before redirect
      setTimeout(() => {
        window.location.href = authUrl;
      }, 100);
    } else {
      // No redirect case, but still a successful response
      toast.success(message);

      // Refetch here, since user stays on the page
      await refetch();
    }

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

  return (
    <div>
      <Button
        onClick={() => setOpenModal(true)}
        className="bg-[#EF2424] text-white text-xs md:px-4 px-2 py-1 rounded-full hover:bg-[#EF2424]/80"
      >
        Show Interest
      </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 */}

            <p className="mb-10 text-sm mt-4">
              Are you sure you want to show interest on this person? You&apos;ll be able to see contact details once the other person shows interest in you as well.
            </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 ? "loading..." : "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 ShowInterest;
