"use client";

import { useChatStore } from "@/store/useChatStore";
import { Conversation } from "@/types/conversations";
import Image from "next/image";
import Link from "next/link";
import { Skeleton } from "./ui/skeleton";
import { dashToPoint, nl2br, parseMessage } from "@/lib/utils";
import { useBrokenFile, useSyncMedia } from "@/hooks/useWhatsApp";
import axios from "axios";
import { boolean } from "zod";
import { useEffect, useState } from "react";
import { Button } from "./ui/button";
import { RefreshCcw } from "lucide-react";


interface MessageItemImageProps {
    conversation: Conversation;
}

const MessageItemImage = ({ conversation }: MessageItemImageProps) => {
    const { setSelectedLightBoxImage } = useChatStore();
    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">
            {(!isFetching && !isFetchingBroken) ?
                (isBroken || typeof isBroken === "undefined") ? 
                    <Button disabled={isFetching} onClick={(e) => {
                        refetch();
                    }}>
                        <RefreshCcw className={`${isFetching ? 'animate-spin' : ''}`}/>
                        Reload
                    </Button>
                :
                    <Link onClick={(e) => setSelectedLightBoxImage(conversation.media_url || "")} href={"#"}>
                        <Image src={conversation.media_url || ""} alt={conversation.media_file_name || ""} width={350} height={200} />
                    </Link>
                 :
                 <Skeleton className="h-[200px] w-[350px] rounded-xl" />
            }
           <span className="text-sm text-gray-800 dark:text-white pb-1" dangerouslySetInnerHTML={{__html:nl2br(parseMessage(conversation.message_text))  || ""}}/>
        </div>
    );
};

export default MessageItemImage;    