"use client";

import { Conversation } from "@/types/conversations";
import { Skeleton } from "./ui/skeleton";
import { dashToPoint, nl2br, parseMessage } from "@/lib/utils";
import Link from "next/link";
import { useBrokenFile, useSyncMedia } from "@/hooks/useWhatsApp";
import { Button } from "./ui/button";
import { RefreshCcw } from "lucide-react";


interface MessageItemVideoProps {
    conversation: Conversation;
}

const MessageItemVideo = ({ conversation }: MessageItemVideoProps) => {
    const { refetch, isFetching, data } = useSyncMedia(conversation.id.toString());
    const { isFetching:isFetchingBroken, data:isBroken } = useBrokenFile(conversation.media_file_path ?? '');

    const urlRegex = /(https?:\/\/[^\s]+)/g;
    const parts = dashToPoint(conversation.message_text).split(urlRegex);
    return (
        <div className="flex flex-col gap-2">
            <div className="">
                {
                    (!isFetching && !isFetchingBroken) ?
                        (isBroken || typeof isBroken === "undefined") ? 
                            <Button disabled={isFetching} onClick={(e) => {
                                refetch();
                            }}>
                                <RefreshCcw className={`${isFetching ? 'animate-spin' : ''}`}/>
                                Reload
                            </Button>
                        :
                        <video controls width={350} height={200}>
                            <source src={conversation.media_url || ""} type="video/mp4" />
                        </video>
                    :
                    <Skeleton className="h-[200px] w-[350px] rounded-xl" />
                }
            </div>
            
            {/* <span className="border-t border-gray-200 dark:border-gray-700"></span> */}
            <span className="text-sm text-gray-800 dark:text-white pb-1" dangerouslySetInnerHTML={{__html:nl2br(parseMessage(conversation.message_text))  || ""}}/>
        </div>
    );
};

export default MessageItemVideo;    