"use client";

import Image from "next/image";
import { HeartIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import ProfilePicture from "@/src/components/reusables/ui/profilePicture";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import { cn } from "@/lib/utils";
import { Option } from "@/src/utils/types";
import { useGetInputData } from "@/src/utils/hooks/useGetInputData";
import ShowInterest from "@/src/components/user/ShowInterest";
import { toast } from "react-toastify";
import LoadingSpinner from "@/src/components/reusables/ui/LoadingSpinner";
import NudgePopup from "./NudgePopup";
import AcceptInterests from "@/src/components/user/AcceptInterests";
import axiosInstance from "@/lib/axios";
import { useGetSingleUser } from "@/src/utils/hooks/useGetSingleUser";
import { setOtherUsersProfile } from "@/src/redux/profileSlice";
import MatchScore from "./MatchScore";

interface Props {
  compatibility: any
}

const ProfileBanner = ({ compatibility }: Props) => {
  const otherUsersProfile = useAppSelector(
    (state) => state.profile.otherUsersProfile
  );

  const [viewMode, setViewMode] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [nudgeCount, setNudgeCount] = useState<Record<string, number>>({});
  const [isReady, setIsReady] = useState(false);
  const [openNudge, setopenNudge] = useState(false);
  const [liked, setLiked] = useState(otherUsersProfile?.is_favorite_by_me);
  const [isBlocked, setIsBlocked] = useState<boolean>(false);

  const dispatch = useAppDispatch();


  const { data: user, refetch } = useGetSingleUser(otherUsersProfile?.user_id);

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


  const router = useRouter();
  const GoBack = () => {
    router.back();
  };

  const handleLiked = async ({ targetUserId }: any) => {
    try {
      if (typeof window === "undefined") return;
      const userId = localStorage.getItem("userId");

      const response = await axiosInstance.post(
        `/users/${userId}/dashboard/favorite/${targetUserId}`,
        {}
      );

      setLiked(!liked);
    } catch (error) {}
  };

  const handleBlock = async ({ targetUserId }: any) => {
    try {
      if (typeof window === "undefined") return;

      const userId = localStorage.getItem("userId");

      setIsLoading(true);

      const response = await axiosInstance.post(
        `/users/${userId}/dashboard/block/${targetUserId}`,
        {}
      );

      setIsLoading(false);

      if (isBlocked) {
        toast.success("User successfully unblocked");
   
      } else {
             toast.success("User successfully blocked");
      }

      refetch();
    } catch (error) {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (typeof window !== "undefined") {
      try {
        const stored = localStorage.getItem("nudgeCount");
        if (stored) {
          const parsed = JSON.parse(stored);
          if (parsed && typeof parsed === "object") {
            setNudgeCount(parsed);
          }
        }
      } catch (e) {
        console.error("Error parsing nudgeCount:", e);
      } finally {
        setIsReady(true);
      }
    }
  }, []);

  useEffect(() => {
    if (typeof window !== "undefined" && isReady) {
      localStorage.setItem("nudgeCount", JSON.stringify(nudgeCount));
    }
  }, [nudgeCount, isReady]);


  useEffect(() => {
  setIsBlocked(otherUsersProfile?.is_blocked_by_me ?? false)
}, [otherUsersProfile])


  const handleNudge = async ({ targetUserId }: any) => {
    try {
      if (typeof window === "undefined") return;

      const userId = localStorage.getItem("userId");

      if (!targetUserId || !isReady) return;

      const currentCount = nudgeCount[targetUserId] || 0;
      if (currentCount >= 2) return;

      setIsLoading(true);

      const response = await axiosInstance.post(
        `/users/${userId}/dashboard/nugde`,
        {
          subscribed_to_id: targetUserId,
        },
      );
      setIsLoading(false);
      setNudgeCount((prev) => ({
        ...prev,
        [targetUserId]: (prev[targetUserId] || 0) + 1,
      }));
      toast.success("Nudge sent successfully!");
      setopenNudge(false);
      refetch()
    } catch (error) {
      setIsLoading(false);
      toast.error("Failed to send nudge. Try again");
    }
  };

  const id = otherUsersProfile?.user_id;

  // Separate calls to useGetInputData
  const { data: subscribeAmountData } = useGetInputData("subscribe_amount");

  const inputOptions: { key: string; options: Option[]; rawValue?: any }[] = [
    {
      key: "subscribe_amount",
      options:
        subscribeAmountData?.payload?.value.map((item: string) => ({
          label: item,
          value: item.toLowerCase(),
        })) || [],
      rawValue: subscribeAmountData?.payload?.value,
    },
  ];

  const [amount, setAmount] = useState(
    subscribeAmountData?.payload?.value?.[0]
  );

  if (!isReady || !id) return null;

  console.log({compatibility})

  const hasNudgedTwice = (nudgeCount[id] || 0) >= 2;

  return (
    <section className="relative w-full overflow-hidden">
      {/* Banner Image */}
      <div className="relative w-full h-[200px]">
        <Image
          src={otherUsersProfile?.cover_photo || "/images/cover-photo.png"}
          alt="Cover"
          fill
          className="object-cover"
        />

        {/* Back Button */}
        <div className="absolute top-6 left-6 z-10">
          <Button
            variant="secondary"
            className={
              "bg-black hover:bg-black text-white rounded-md h-8 px-4 py-0 cursor-pointer"
            }
            onClick={GoBack}
          >
            Back
          </Button>
        </div>

        {/* Favorite Button */}
        <div className="absolute top-6 right-6 z-10">
          <Button
            variant="secondary"
            className="bg-white hover:bg-white text-black rounded-full h-8 p-5 cursor-pointer flex items-center gap-2"
            onClick={() =>
              handleLiked({ targetUserId: otherUsersProfile?.user_id })
            }
          >
            Add to favorite{" "}
            <HeartIcon
              className={cn(
                "h-5 w-5 ml-1",
                liked ? "fill-red-500 text-red-500" : "text-gray-400"
              )}
            />
          </Button>
        </div>

        {/* Profile Photo */}

        <ProfilePicture
          src={otherUsersProfile?.photo || "/images/cover-photo.png"}
          alt={`${"User"}'s profile`}
          viewMode={viewMode}
          userInfo={{
            name: otherUsersProfile?.first_name || "",
            age: otherUsersProfile?.age || 0,
            location: otherUsersProfile?.state || "",
          }}
        />
      </div>

      {/* Bottom Info and Actions */}
      <div className="w-[100%] flex justify-end">
        <div className="flex items-center justify-between px-6 pt-5 w-[70%] pb-4">
          {/* Match Score */}
          <MatchScore match_score={compatibility?.payload?.matches[0]?.match_score || 0} />


          {/* Buttons */}
          <div className="flex items-center gap-3">
            {otherUsersProfile?.is_subscribed_by_me &&
            !otherUsersProfile?.is_subscribed_to_me ? (
              <Button
                className={`text-white text-xs px-4 py-1 rounded-full ${
                  hasNudgedTwice
                    ? "bg-gray-400 cursor-not-allowed"
                    : "bg-[#EF2424] hover:bg-[#EF2424]/80"
                }`}
                disabled={hasNudgedTwice}
                onClick={() => setopenNudge(true)}
              >
                Nudge
              </Button>
            ) : otherUsersProfile?.is_subscribed_to_me &&
              !otherUsersProfile?.is_subscribed_by_me ? (
              <AcceptInterests
                amount={amount}
                id={otherUsersProfile?.user_id}
              />
            ) : otherUsersProfile?.is_subscribed_to_me &&
              otherUsersProfile?.is_subscribed_by_me ? (
              <Button
                variant="outline"
                className="border-red-500 text-red-500 text-xs px-4 py-1 rounded-full hover:bg-red-50"
                onClick={() => {
                  setIsBlocked((prev) => !prev);
                  handleBlock({ targetUserId: otherUsersProfile?.user_id });
                }}
              >
                {isLoading ? (
                  <LoadingSpinner />
                ) : isBlocked ? (
                  "Unblock"
                ) : (
                  "Block"
                )}
              </Button>
            ) : (
              <ShowInterest amount={amount} id={otherUsersProfile?.user_id} />
            )}
          </div>
        </div>
      </div>

      {openNudge && (
        <NudgePopup
          openNudge={openNudge}
          setopenNudge={setopenNudge}
          isLoading={isLoading}
          handleNudge={handleNudge}
          nudgeCount={nudgeCount[id] || 0}
        />
      )}
    </section>
  );
};

export default ProfileBanner;
