import React, { useState, useEffect } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { useNavigate } from "react-router-dom"; import { Crown, Bookmark, X, Heart, Eye, Phone, MessageSquare, ChevronLeft } from "lucide-react"; import VisibilityIcon from "@mui/icons-material/Visibility"; import axiosInstance, { apiForFiles } from "../../api/axiosInstance"; import { API_ENDPOINTS } from "../../api/apiEndpoints"; import UpgradeModal from "./UpgradeModal"; import toast from "react-hot-toast"; // Custom Icons import personIcon from "../../assets/images/personicon.svg"; import religionIcon from "../../assets/images/religonicon.svg"; import locationIcon from "../../assets/images/locationicon.svg"; import cashIcon from "../../assets/images/cashicon.svg"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { shortlistProfile, sendInterest, declineProfile } from "../../services/shortlistapi"; import { sendMessage } from "../../services/chatApi"; import { getHeaderDetails } from "../../api/preview.api"; export default function ProfileCardUI({ profile }) { const [isLiked, setIsLiked] = useState(false); const [isShortlisted, setIsShortlisted] = useState(profile.is_shortlisted === 1); const [isUpgradeModalOpen, setIsUpgradeModalOpen] = useState(false); const [isViewContactModalOpen, setIsViewContactModalOpen] = useState(false); const [isInterestStatusModalOpen, setIsInterestStatusModalOpen] = useState(false); const [isInterestRejectedModalOpen, setIsInterestRejectedModalOpen] = useState(false); const [isContactSuccessModalOpen, setIsContactSuccessModalOpen] = useState(false); const [isChatConfirmModalOpen, setIsChatConfirmModalOpen] = useState(false); const [isCreatingChat, setIsCreatingChat] = useState(false); const [modalTitle, setModalTitle] = useState(""); const [modalMessage, setModalMessage] = useState(""); const [unlockedMobile, setUnlockedMobile] = useState(null); const navigate = useNavigate(); const queryClient = useQueryClient(); const { data: headerData } = useQuery({ queryKey: ["headerDetails"], queryFn: getHeaderDetails, staleTime: 60000, // Reuse data for 1 minute }); const isUserPaid = headerData?.myDetails?.is_paid_member === true; const handleInterest = async (e) => { e.stopPropagation(); if (!isUserPaid) { setIsUpgradeModalOpen(true); return; } try { await axiosInstance.post(`${API_ENDPOINTS.INTEREST_SEND}?profile_id=${profile.id}`); setIsLiked(true); toast.success(`Interest sent to ${profile.name}!`, { icon: '❤️', style: { borderRadius: '10px', background: '#333', color: '#fff' } }); } catch (error) { toast.error("Failed to send interest."); } }; const handleDecline = async (e) => { e.stopPropagation(); try { await axiosInstance.post(`${API_ENDPOINTS.UPDATE_INTEREST_STATUS}?profile_id=${profile.id}&status=reject`); toast.success("Profile declined"); // Optionally hide card or trigger refresh } catch (error) { toast.error("Failed to decline profile."); } }; const handleCall = (e) => { e.stopPropagation(); if (!isUserPaid) { setIsUpgradeModalOpen(true); return; } const interestStatus = (profile.is_send_interest_status || "").toLowerCase(); if (profile.call_protection === 1) { if (profile.is_send_interest) { if (interestStatus === 'pending') { setModalTitle("Note"); setModalMessage("An interest request has already been sent for this profile. Please wait for their response"); setIsInterestStatusModalOpen(true); return; } else if (interestStatus === 'reject' || interestStatus === 'rejected') { setIsInterestRejectedModalOpen(true); return; } } } _handleCallTap(); }; const _handleCallTap = () => { const currentMobile = unlockedMobile || profile.mobile_number || ""; const mobile = currentMobile.toLowerCase(); if (mobile.includes("upgrade to view")) { setIsUpgradeModalOpen(true); } else if (mobile.includes("view contact")) { setIsViewContactModalOpen(true); } else { // It's a real number - Show the success modal with the number setUnlockedMobile(currentMobile); setIsContactSuccessModalOpen(true); } }; const handleMessage = (e) => { e.stopPropagation(); // 1. Check if chat already exists if (profile.chat_id) { navigate(`/chat/${profile.chat_id}`); return; } // 2. Check membership if (!isUserPaid) { setIsUpgradeModalOpen(true); return; } const interestStatus = (profile.is_send_interest_status || "").toLowerCase(); // 3. Check protection & interest status if (profile.chat_protection === 1 || profile.call_protection === 1) { if (profile.is_send_interest) { if (interestStatus === 'pending') { setModalTitle("Note"); setModalMessage("An interest request has already been sent for this profile. Please wait for their response"); setIsInterestStatusModalOpen(true); return; } else if (interestStatus === 'reject' || interestStatus === 'rejected') { setIsInterestRejectedModalOpen(true); return; } } } // 4. Show confirmation dialog setIsChatConfirmModalOpen(true); }; const _handleCreateChat = async () => { if (isCreatingChat) return; setIsChatConfirmModalOpen(false); setIsCreatingChat(true); try { const response = await axiosInstance.post(API_ENDPOINTS.CHAT_CREATE, { profile_id: profile.id }); if (response.data?.status === true || response.data?.status === 'success') { const newChatId = response.data?.chat_id; // Send default initiation message manually try { await sendMessage(newChatId, "This profile has initiated a chat with you"); } catch (msgErr) { console.error("Error sending initial message:", msgErr); } toast.success("Chat initiated!"); navigate(`/chat/${newChatId}`); queryClient.invalidateQueries(); } else { toast.error(response.data?.message || "Could not create chat."); } } catch (error) { console.error("Error creating chat", error); toast.error("Failed to start conversation"); } finally { setIsCreatingChat(false); } }; const _handleViewContact = async () => { setIsViewContactModalOpen(false); try { const formData = new FormData(); formData.append("profile_id", profile.id); const response = await apiForFiles.post(API_ENDPOINTS.VIEW_CONTACT, formData); if (response.data?.status === 'success') { const newMobile = response.data?.mobile_number; setUnlockedMobile(newMobile); setIsContactSuccessModalOpen(true); toast.success("Contact details unlocked!"); // Refresh all queries to update the UI globally queryClient.invalidateQueries(); } else { setIsUpgradeModalOpen(true); } } catch (error) { console.error("Error viewing contact", error); toast.error("Failed to view contact"); } }; const handleShortlistClick = async (e) => { e.stopPropagation(); try { const res = await axiosInstance.post(`${API_ENDPOINTS.SHORTLIST_API}?profile_id=${profile.id}`); if (res.data?.status === "success") { setIsShortlisted(!isShortlisted); toast.success(res.data.message || "Updated shortlist status"); } } catch (error) { toast.error("Failed to update shortlist"); } }; // Map API fields to UI, handling missing values const imageSrc = profile.photo || profile.image || "https://www.thirukalyanam.amrithaa.net/backend/app-assets/images/portrait/small/no-image.png"; return ( <> setIsUpgradeModalOpen(false)} /> {/* View Contact Confirmation Modal */} {isViewContactModalOpen && (

Note

You need to view this profile's contact details. If you choose to "Proceed" one count will be deducted from your subscription.

)} {/* Interest Status Modal (Pending) */} {isInterestStatusModalOpen && (

{modalTitle}

{modalMessage}

)} {/* Interest Rejected Modal */} {isInterestRejectedModalOpen && (

Note

Your previous interest request was declined. You may resend your interest to this profile

)} {/* Contact Success Modal */} {isContactSuccessModalOpen && (

Success!

The contact number has been unlocked.

{unlockedMobile || (!profile.mobile_number?.toLowerCase().includes("view") ? profile.mobile_number : "Fetching...")}
)} {/* Chat Confirmation Modal */} {isChatConfirmModalOpen && (() => { const currentMobile = profile.mobile_number || ""; const mobileLower = currentMobile.toLowerCase(); const isMobileVisible = currentMobile !== "" && !mobileLower.includes("upgrade") && !mobileLower.includes("view contact"); return (

{isMobileVisible ? "Ready to Chat?" : "Note"}

{isMobileVisible ? `Are you ready to chat with ${currentMobile}?` : "Starting a conversation will use 1 chat count. Are you ready to proceed?"}

); })()}
navigate(`/profile-details/${profile.id}`)} className="w-full max-w-sm rounded-[10px] shadow-xl overflow-hidden border border-green-200 bg-white cursor-pointer hover:shadow-2xl transition-all duration-300" >
{/* Premium Badge */} {profile.isPremium && ( )} {isShortlisted ? "Shortlisted" : "Shortlist"}
{profile.name} { e.target.src = "https://www.thirukalyanam.amrithaa.net/backend/app-assets/images/portrait/small/no-image.png"; }} />
{/* Gradient Overlay */}

{profile.name}

ID: {profile.member_id || profile.id}

{profile.name}

ID: {profile.member_id || profile.id} {profile.last_seen_at && profile.last_seen_at !== "-" ? profile.last_seen_at : "Recently"}
{(profile.age || profile.height) && (
Person
{profile.age ? `${profile.age} yrs` : ""} {profile.age && profile.height ? ", " : ""} {profile.height ? `${profile.height} cm` : ""}
)} {(profile.religion_name || profile.caste_name) && (
Religion
{profile.religion_name} {profile.religion_name && profile.caste_name ? " / " : ""} {profile.caste_name}
)} {(profile.annual_income_name || profile.income) && (
Cash
{profile.annual_income_name || profile.income}
)} {(profile.district_name || profile.location) && (
Location
{profile.district_name || profile.location}
)}
{profile.is_send_interest_received && profile.statusReceived?.toLowerCase() === 'pending' ? ( <> ) : (!(profile.is_send_interest || isLiked) && !profile.is_send_interest_received) ? ( <> ) : ( <> )}
); }