"use client";

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

interface MessageItemAudioProps {
    conversation: Conversation;
}

const MessageItemDocument = ({ conversation }: MessageItemAudioProps) => {
    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);
    
    const isPdf =
        conversation.media_mime_type === "application/pdf" ||
        conversation.media_file_name?.toLowerCase().endsWith(".pdf") ||
        conversation.media_url?.toLowerCase().includes(".pdf");

    return (
        <div className="flex flex-col gap-2">
            {
                 (!isFetching && !isFetchingBroken) ?
                    <div className="flex flex-col rounded-lg overflow-hidden bg-zinc-400/25 dark:bg-[#111b21]">
                        {
                             (isBroken || typeof isBroken === "undefined") ? (
                                <div className="p-3">
                                    <Button disabled={isFetching} className="w-full" onClick={(e) => {
                                        refetch();
                                    }}>
                                        <RefreshCcw className={`${isFetching ? 'animate-spin' : ''}`}/>
                                        Reload
                                    </Button>
                                </div>
                            ) : (
                                <>
                                    {isPdf && conversation.media_url && (
                                        <div className="relative w-full h-[180px] bg-white overflow-hidden border-b border-black/10 dark:border-white/10">
                                            <iframe
                                                src={`${conversation.media_url}#toolbar=0&navpanes=0&scrollbar=0&view=FitH`}
                                                title={conversation.media_file_name || "PDF Preview"}
                                                className="w-full h-full border-0 pointer-events-none"
                                                loading="lazy"
                                            />
                                            <Link
                                                href={conversation.media_url || "#"}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="absolute inset-0 z-10"
                                                title="Buka PDF di tab baru"
                                            />
                                        </div>
                                    )}
                                    <Link
                                        href={conversation.media_url || "#"}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="flex flex-row items-center gap-2 p-3 hover:bg-black/5 dark:hover:bg-white/5 transition-colors"
                                    >
                                        {isPdf ?
                                            <Icon icon="vscode-icons:file-type-pdf2" className="text-red-600 h-10 w-10 shrink-0"/>
                                            :
                                            (conversation.media_mime_type == "application/msword" || conversation.media_mime_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") ?
                                                <Icon icon="vscode-icons:file-type-word" className="text-blue-600 h-10 w-10 shrink-0"/>
                                            :
                                            (conversation.media_mime_type == "application/vnd.ms-excel" || conversation.media_mime_type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")  ?
                                                <Icon icon="vscode-icons:file-type-excel" className="text-green-600 h-10 w-10 shrink-0"/>
                                            :
                                            <FileText className="text-gray-600 dark:text-gray-200 h-10 w-10 shrink-0"/>
                                        }
                                        <div className="flex flex-col min-w-0 flex-1">
                                            <span className="text-gray-700 dark:text-gray-200 text-sm font-medium truncate">
                                                {conversation?.media_file_name || "Dokumen"}
                                            </span>
                                            <span className="text-xs text-gray-500 dark:text-gray-400 uppercase">
                                                {isPdf ? "PDF" : conversation.media_mime_type?.split("/").pop() || "FILE"}
                                            </span>
                                        </div>
                                    </Link>
                                </>
                            )
                        }
                </div>
                :
                <Skeleton className="h-[50px] 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 MessageItemDocument;