import { GoDotFill } from "react-icons/go";
import { Message } from "../../../types/MessageListType";
import { formatCallDuration } from "../../../utils/formatUTCtoLocalDate";
import { useAppSelector } from "../../../utils/hooks";

interface CallInMessageListProps {
  messageData: Message;
}

export default function CallInMessageList({
  messageData,
}: CallInMessageListProps) {
  const userData = useAppSelector((state) => state.userData);

  const call = messageData?.Calls?.[0];
  if (!call) return null;

  const isMissed =
    call.call_status === "missed" ||
    (!call.users.includes(userData.user_id.toString()) &&
      call.call_status === "ended");
  const isVideo = call.call_type === "video";
  const isOutgoing = messageData.sender_id === userData.user_id;

  // --- Icon Path ---
  let iconSrc = "";
  if (isMissed) {
    iconSrc = isVideo
      ? "/CallIcons/missed_video_call.png"
      : "/CallIcons/missed_audio_call.png";
  } else {
    iconSrc = isVideo
      ? isOutgoing
        ? "/CallIcons/outgoing_video_call.png"
        : "/CallIcons/incoming_video_call.png"
      : isOutgoing
        ? "/CallIcons/outgoing_audio_call.png"
        : "/CallIcons/incoming_audio_call.png";
  }

  // --- Title & Subtext ---
  let title = "";
  let subtext = "";
  if (isMissed) {
    title = "Missed Call";
  } else {
    title = isVideo ? "Video Call" : "Audio Call";
    subtext = isOutgoing ? "Outgoing Call" : "Incoming Call";
  }

  return (
    <div className={`flex h-14 w-60 ${location.pathname !== "/video-call" ? "w-60 lg:w-80" : "w-60 lg:w-60"} items-center gap-2 rounded-lg bg-secondary p-1 text-xs text-darkText`}>
      <div className="grid h-11 w-11 place-content-center rounded-lg bg-otherMessageBg">
        <img src={iconSrc} className="h-7 w-7 object-contain" alt="" />
      </div>

      <div className="flex flex-col gap-1">
        <div className="text-sm font-medium">{title}</div>

        <div className="flex items-center gap-1">
          {subtext && <div className="text-xs">{subtext}</div>}
          {!isMissed && call.call_duration != 0 && (
            <>
              <GoDotFill className="h-2 w-2 text-lightText" />
              <div className="text-[#FCC604]">
                {formatCallDuration(call.call_duration)}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
