TwitchClone / src / components / userContent / index.tsx
index.tsx
Raw
import { useEffect, useState } from "react";
import { api } from "../../utils/api";
import { useRoomDataContext } from "../../utils/context/RoomDataContext";
import { UserSchema } from "../../types/user";
import { Content } from "@prisma/client";
import router from "next/router";

interface DemoUsers {
  id: string;
  name: string | null;
  image?: string | null;
  email?: string | null;
  videos?: {
    id: string;
    createdAt: Date;
    playbackId: string;
    roomId: string;
    streamKey: string;
    updatedAt: Date;
    userId: string;
  }[];
}

interface UserContentProps {
  user: DemoUsers;
  playbackId: string;
  roomId: string;
  selectedId: string | null;
  setRoomId: (roomId: string) => void;
  // onSelectVideo: (videoId: string) => void;
  // onRoomSelect: (roomId: string) => void;
}
const UserContent: React.FC<UserContentProps> = ({
  user,
  roomId,
  playbackId,
  selectedId,
  setRoomId,
}) => {
  const [sel, setSel] = useState(false);
  const [selectedPlaybackId, setSelectedPlaybackId] = useState<string | null>(
    null
  );
  const { roomData, setRoomData, userData, setUserData } = useRoomDataContext();
  //   const [uploadId, setUploadId] = useState<string | null>(null);
  //   const [uploadUrl, setUploadUrl] = useState<string | null>(null);
  //   const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [selectedVideoId, setSelectedVideoId] = useState<string | null>(null);
  const [hoveredVideo, setHoveredVideo] = useState<string | null>(null);

  const videoRes = api.lambda.fetchLiveStream.useQuery({ playbackId });
  if (!selectedId) {
    console.error("selectedId is empty");
  }

  useEffect(() => {
    if (sel) {
      setSel(false);
      if (videoRes.data) {
        // Perform actions with videoRes.data, e.g., update roomData

        // const videoRes = api.lambda.fetchLiveStream.useQuery({ playbackId });

        console.log(videoRes, "video");
        console.log("Setting room data:", {
          ...roomData,
          assetId: videoRes.data?.assetId || "",
          playbackId: videoRes.data?.playbackId,
        });

        setRoomData((prev) => {
          console.log(
            "1 one",
            selectedId,
            videoRes.data?.assetId || "",
            videoRes.data?.playbackId
          );
          if (!prev) {
            return null;
          }
          console.log("userContent Data", {
            ...prev,
            roomId: selectedId || "",
            assetId: videoRes.data?.assetId,
            assetUrl: videoRes.data?.playbackId,
          });
          return {
            ...prev,
            roomId: selectedId || "",
            assetId: videoRes.data?.assetId,
            assetUrl: videoRes.data?.playbackId,
          };
        });
      }
    }
  }, [sel, videoRes.data]);

  const handleSelect = async (asset: Content) => {
    console.log("handleSelect", asset.roomId, playbackId);
    console.log(asset, "asset");
    if (!roomId) {
      console.error("playbackId is empty");
      return;
    }
    setSelectedVideoId(playbackId);
    setRoomId(roomId);

    console.log("id", playbackId);
    setSelectedPlaybackId(playbackId);
    setSel(true);
    setRoomData((prev) => {
      if (!prev) {
        return null;
      }

      console.log("userContent Data", {
        ...prev,
        selectedId,
        assetData: asset,
        roomId: asset.roomId,
      });
      return {
        ...prev,
        selectedId,
        assetData: asset,
        roomId: asset.roomId,
      };
    });

    // Navigate to the stream page programmatically
    // router.push(`/streams/${playbackId}`);
    const userEmail = asset.userId;
    try {
      await router.push(`/${userEmail}`);
    } catch (e) {
      console.log(e);
    }
  };
  const mostRecentVideo = user.videos?.reduce<{
    id: string;
    createdAt: Date;
    playbackId: string;
    roomId: string;
    streamKey: string;
    updatedAt: Date;
    userId: string;
  } | null>(
    (recent, video) =>
      !recent || new Date(recent.createdAt) < new Date(video.createdAt)
        ? video
        : recent,
    null
  );
  console.log("mostRecentVideo", mostRecentVideo);
  return (
    <div className="m-2 border p-4 shadow-lg">
      <div className="flex items-center">
        <img
          className="mr-4 h-16 w-16 rounded-full"
          src={user.image || "https://via.placeholder.com/150"}
          alt={user.name || "User Profile Picture"}
        />
        <div>
          <h2 className="text-xl font-semibold">{user.name}</h2>
          <p className="text-gray-600">{user.email}</p>
        </div>
      </div>
      {mostRecentVideo ? (
        <div className="mt-4">
          <h3 className="text-lg font-semibold">Most Recent Video:</h3>
          <div
            key={mostRecentVideo.id}
            onMouseEnter={() => setHoveredVideo(mostRecentVideo.playbackId)} // Set hovered video on mouse enter
            onMouseLeave={() => setHoveredVideo(null)} // Clear hovered video on mouse leave
          >
            <img
              className="mt-2 cursor-pointer rounded-md"
              src={`https://image.mux.com/${mostRecentVideo.playbackId}/thumbnail.jpg`}
              alt="Video Thumbnail"
              onClick={() => {
                void handleSelect(mostRecentVideo);
              }}
            />
          </div>
        </div>
      ) : (
        <p className="mt-4 text-gray-600">No videos uploaded yet.</p>
      )}
    </div>
  );
};

export default UserContent;