"use client";

import { Conversation } from "@/types/conversations";
import Image from "next/image";
import { dashToPoint, nl2br, parseMessage } from "@/lib/utils";
import { CopyIcon, ExternalLink, FileText, MapPin, Phone, ReplyIcon, Share2 } from "lucide-react";
import { Icon } from "@iconify/react";
import { Button } from "./ui/button";
import Link from "next/link";
import { useChatStore } from "@/store/useChatStore";
import { Skeleton } from "./ui/skeleton";


interface MessageItemTemplateProps {
    conversation: Conversation;
}

const MessageItemTemplate = ({ conversation }: MessageItemTemplateProps) => {
    const { setSelectedLightBoxImage } = useChatStore();
   
    return (
        <div className="flex flex-col gap-2">
            {
                conversation.message_json?.map((item: any, index: number) => {
                    if(item.type === "header") {
                        if(item.format === "text") {
                            return (
                                <div key={index}>
                                    <p className="text-sm text-gray-800 dark:text-white">{item.text}</p>
                                </div>
                            )
                        }else if(item.format === "image") {
                            return (
                                <div key={index}>
                                    <Link onClick={(e) => setSelectedLightBoxImage(item.text)} href={"#"}>
                                        {
                                            item.text ?
                                            <Image  src={item.text || ""} alt={""} width={350} height={200} />
                                            :
                                            <Skeleton className="h-[200px] w-[350px] rounded-xl" />
                                        }
                                    </Link>
                                </div>
                            )
                        }else if(item.format === "video") {
                            return (
                                <div key={index}>
                                    {
                                        item.text ?
                                            <video controls width={350} height={200}>
                                                <source src={item.text || ""}/>
                                            </video>
                                        :
                                        <Skeleton className="h-[200px] w-[350px] rounded-xl" />
                                    }
                                </div>
                            )
                        }else if(item.format === "document") {
                            const isPdf =
                                item.mime_type === "application/pdf" ||
                                item.filename?.toLowerCase().endsWith(".pdf") ||
                                item.text?.toLowerCase().includes(".pdf");

                            return (
                                <div key={index} className="flex flex-col rounded-lg overflow-hidden bg-zinc-400/25 dark:bg-[#111b21]">
                                    {isPdf && item.text && (
                                        <div className="relative w-full h-[180px] bg-white overflow-hidden border-b border-black/10 dark:border-white/10">
                                            <iframe
                                                src={`${item.text}#toolbar=0&navpanes=0&scrollbar=0&view=FitH`}
                                                title={item.filename || "PDF Preview"}
                                                className="w-full h-full border-0 pointer-events-none"
                                                loading="lazy"
                                            />
                                            <Link
                                                href={item.text || "#"}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="absolute inset-0 z-10"
                                                title="Buka PDF di tab baru"
                                            />
                                        </div>
                                    )}
                                    <Link
                                        href={item.text || "#"}
                                        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" />
                                        ) : (item.mime_type === "application/msword" || item.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" />
                                        ) : (item.mime_type === "application/vnd.ms-excel" || item.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" />
                                        ) : item.mime_type === "application/vnd.openxmlformats-officedocument.presentationml.presentation" ? (
                                            <Icon icon="vscode-icons:file-type-powerpoint" className="text-orange-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">
                                                {item.filename || "Dokumen"}
                                            </span>
                                            <span className="text-xs text-gray-500 dark:text-gray-400 uppercase">
                                                {isPdf ? "PDF" : item.mime_type?.split("/").pop() || "FILE"}
                                            </span>
                                        </div>
                                    </Link>
                                </div>
                            )
                        }else if(item.format === "location") {
                            return (
                                <div key={index}>
                                    <p>{item.text}</p>
                                </div>
                            )
                        }
                    }else if(item.type === "body") {
                        const urlRegex = /(https?:\/\/[^\s]+)/g;
                        const parts = dashToPoint(conversation.message_text).split(urlRegex);
                        return (
                            <div key={index}>
                                {parts.map((part, i) =>
                                    urlRegex.test(part) ? (
                                    <Link
                                        key={i}
                                        href={part}
                                        target="_blank"
                                        className="text-emerald-600 dark:text-emerald-400 hover:underline hover:text-emerald-800"
                                        rel="noopener noreferrer"
                                    >
                                        {part}
                                    </Link>
                                    ) : (
                                        <p key={i} className="text-sm text-gray-800 dark:text-white" dangerouslySetInnerHTML={{ __html: nl2br(parseMessage(item.text)) }} />
                                    )
                                )}
                            </div>
                        )
                    }else if(item.type === "footer") {
                        return (
                            <div key={index}>
                                <p className="text-xs text-gray-400" dangerouslySetInnerHTML={{ __html: item.text }} />
                            </div>
                        )
                    }else if(item.type === "button") {
                        return (
                            <div key={index} className="flex flex-col gap-2">
                                <span className="border-b border-gray-300 dark:border-white w-full"></span>
                                {item.items.map((button: any, index: number) => {
                                    if(button.sub_type === "url") {
                                        return (
                                            <div key={index}>
                                                <Link href={button.text} target="_blank" className="w-full font-normal hover:bg-gray-400/25">
                                                    <Button variant="ghost"  size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                        <ExternalLink/>
                                                        {button.name}
                                                    </Button>
                                                </Link>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "phone_number") {
                                        return (
                                            <div key={index}>
                                                <Link href={button.text} target="_blank">
                                                    <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                        <Phone/>
                                                        {button.name}
                                                    </Button>
                                                </Link>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "quick_reply") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <ReplyIcon/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "copy_code") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <CopyIcon/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "voice_call") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <Phone/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "share_location") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <MapPin/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "share_phone_number") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <Share2/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "share_email") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <Share2/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "share_address") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <Share2/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                    if(button.sub_type === "share_website") {
                                        return (
                                            <div key={index}>
                                                <Button variant="ghost" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                    <Share2/>
                                                    {button.name}
                                                </Button>
                                            </div>
                                        )
                                    }
                                })}
                            </div>
                        )
                    }
                })
            }
        </div>
    );
};

export default MessageItemTemplate;