"use client"

import { DialogClose } from "@radix-ui/react-dialog"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog"
import { Button } from "./ui/button"
import { Input } from "./ui/input"
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "./ui/form"
import { useForm } from "react-hook-form"
import { useTemplates } from "@/hooks/useWhatsApp"
import { Combobox } from "./ui/combobox"
import { useEffect, useState } from "react"
import Dropzone, { FileRejection } from "react-dropzone";
import { CopyIcon, ExternalLink, FileIcon, FileText, Link2, Link2Icon, LinkIcon, Loader2, Phone, PhoneCall, Reply, ReplyIcon, UploadIcon } from "lucide-react"
import Image from "next/image"
import { Textarea } from "./ui/textarea"
import { ScrollArea } from "./ui/scroll-area"
import { nl2br, parseMessage } from "@/lib/utils"
import { Label } from "./ui/label"
import Link from "next/link"
import { useMutation } from "@tanstack/react-query"
import api from "@/lib/axios";
import { toast } from "sonner"
import { useChatStore } from "@/store/useChatStore"
import { useAuth } from "@/contexts/auth-context"
import { useQuery } from "@tanstack/react-query"
import { useDebounce } from "use-debounce"

interface MessageInputTemplateProps {
    open:boolean,
    onChangeOpen:(open: boolean) => void,
}
export default function MessageInputTemplate({ open, onChangeOpen}:MessageInputTemplateProps) {
    
    const { data } = useTemplates(open);
    const [detailTemplate, setDetailTemplate] = useState<any>(null);
    const [optionTemplate, setOptionTemplate] = useState([]);
    const [selectedTemplate, setSelectedTemplate] = useState(null);
    const { selectedContact , withoutContact} = useChatStore();
    const { user } = useAuth();

    const [file, setFile] = useState<any>(null);
    const [attachmentFile, setAttachmentFile] = useState<File | null>(null);
    const [headerTemplate, setHeaderTemplate]   = useState<any>(null);
    const [bodyTemplate, setBodyTemplate]       = useState<any>(null);
    const [footerTemplate, setFooterTemplate]   = useState<any>(null);
    const [buttonTemplate, setButtonTemplate]   = useState<any>(null);
    const [allowed, setAllowed] = useState<any[]>([
        "application/pdf",
        "application/msword",
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ])

    const [searchContactText, setSearchContactText] = useState("");
    const [debouncedSearch] = useDebounce(searchContactText, 500);

    const { data: contactsData, isFetching: isFetchingContacts } = useQuery({
        queryKey: ['contacts-search', debouncedSearch],
        queryFn: () => api.get('/api/contact', {
            params: {
                account_id: process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE,
                search: debouncedSearch,
                per_page: 20
            }
        }).then(res => res.data.data.result), // Paginated data in res.data.data.result
        enabled: withoutContact
    });

    const contactOptions = (contactsData || []).map((c: any) => ({
        value: c.phone_number,
        label: `${c.name} (${c.phone_number})`
    }));

    if (searchContactText && /^[0-9]+$/.test(searchContactText)) {
        if (!contactOptions.find((o: any) => o.value === searchContactText)) {
            contactOptions.push({
                value: searchContactText,
                label: `Gunakan nomor: ${searchContactText}`
            });
        }
    }

    const form = useForm({
        mode:"onSubmit",
    });

    useEffect(() => {
        if(detailTemplate) {
            form.setValue('bodies',[]);
            form.setValue('headers',[]);
            const header = detailTemplate?.components.filter((fill: any) => fill.type == "HEADER").at(0)


            setHeaderTemplate(header ?? null);


            if(header?.example) {
                if(header.format == 'TEXT') {
                    header?.example?.header_text?.map((item: any, index: number) => {
                        form.setValue(`headers.${index}`, item);
                    })

                    form.setValue('header',fillTemplate(header?.text, header?.example?.header_text));
                }

                if(header.format == "DOCUMENT") {
                    getMimeType(header?.example?.header_handle?.at(0))
                }
            } else {
                header?.type == 'TEXT' ? form.setValue('header', header?.text) : form.setValue('header', '')
            }
          


            const body = detailTemplate?.components.filter((fill:any) => fill.type == "BODY").at(0)
            setBodyTemplate(body ?? null);
            
            if(body?.example) {
                body?.example?.body_text[0]?.map((item:any, index:number) => {
                   form.setValue(`bodies.${index}`, item);
                });
                form.setValue('body',fillTemplate(body?.text, body?.example?.body_text[0]));
            } else {
                form.setValue('body', body?.text);
            }

            const footer = detailTemplate?.components.filter((fill: any) => fill.type == "FOOTER").at(0)
            setFooterTemplate(footer ?? null);
            if(footer) form.setValue('footer', footer?.text);

            const button = detailTemplate?.components.filter((fill: any) => fill.type == "BUTTONS").at(0)
            setButtonTemplate(button ?? null);

            button?.buttons && (
                button?.buttons.map((item: any, index: number) => {
                    if(item.type == "URL") {
                        if(item.example) {
                            const url = new URL(item.example[0]);
                            form.setValue(`buttons.${index}`, url.pathname);
                        } else {
                            form.setValue(`buttons.${index}`, item.url);
                        }
                    }

                    if(item.type == "COPY_CODE") {
                        if(item.example) {
                            form.setValue(`buttons.${index}`, item.example?.at(0));
                        } 
                    }

                    if(item.type == "PHONE_NUMBER") {
                        form.setValue(`buttons.${index}`, item.phone_number);
                    }
                })
            )
        }
    },[detailTemplate]);

    useEffect(() => {
        if(!open) {
            reset();
        } else {
            if(!withoutContact) {
                form.setValue("phone_number",selectedContact?.phone_number)
                form.setValue("name",selectedContact?.name)
            } else {
                form.setValue("phone_number","")
            }
           
        }
    },[open]);

    const reset = () => {
        form.setValue("template","");
        setDetailTemplate(null);
        setBodyTemplate(null);
        setButtonTemplate(null);
        setFooterTemplate(null);
        setHeaderTemplate(null);
        setFile(null);
    }

    const fillTemplate = (template:any, values: any) => {
        let message = template;
        values.forEach((val: any, i: number) => {
            const placeholder = `{{${i + 1}}}`;
            message = message.replace(placeholder, val);
        });
        return message;
    }

    const getMimeType =  (url:any) => {
        const pathname = new URL(url).pathname;
        const extension =  pathname.split('.').pop();
        let mime_type = ["*/*"];
        if(extension == "pdf") {
            mime_type = ["application/pdf"]
        }else if(extension == "doc" || extension == "docx") {
            mime_type =  ["application/msword",
                         "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                        "application/vnd.ms-excel",
                         "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
        }else if(extension == "xls" || extension == "xlsx"){
             mime_type =  ["application/vnd.ms-excel",
                         "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
        }
        setAllowed(mime_type)
    }


    const templateMutate = useMutation({
        mutationKey:["template-message"],
        mutationFn:async (payload: FormData) => await api.post("/api/whatsapp/send-message/template",payload, {
            headers: {
                "Content-Type":"multipart/form-data"
            }
        }),
        onSuccess:(response) => {
            toast.success(response.data?.message);
            reset();
            onChangeOpen(false);
        },
        onError:(error:any) => {
            console.log(error);
            toast.error(error.response?.data?.message || error.message);
        }
    })
    
    const onSubmit =  async (values: any) => {
        if (withoutContact) {
            const phoneNumber = values.phone_number || "";
            if (!phoneNumber.startsWith("62")) {
                toast.error("Nomor telepon harus diawali dengan 62");
                return;
            }
        }

        const payload = new FormData();
        payload.append('message',JSON.stringify(values));
        payload.append('account_id',process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE || '');
        payload.append('phone_number',values.phone_number);
        payload.append('template',JSON.stringify(detailTemplate));
        payload.append('maded_by',JSON.stringify(user))

        if(file) {
            payload.append('filename', file?.name)
            payload.append("file",file);
        }

        templateMutate.mutateAsync(payload);
    }   

    const handlePaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
        if (!(e.clipboardData && e.clipboardData.items)) return;

       

        for (let i = 0; i < e.clipboardData.items.length; i++) {
            const item = e.clipboardData.items[i];
            // if(headerTemplate?.format == "IMAGE") {
            //     if (item.type.indexOf('image') !== 0 ) {
            //         toast.error("File harus berupa gambar");
            //         return
            //     }
            // }
            // if(headerTemplate?.format == "VIDEO") {
            //     if (item.type.indexOf('video') !== 0) {
            //         toast.error("File harus berupa video");
            //         return
            //     }
            // }
            // if(headerTemplate?.format == "DOCUMENT") {
            //     if (
            //         !(
            //             item.type === "application/pdf" ||
            //             item.type === "application/msword" ||
            //             item.type === "application/vnd.ms-excel" ||
            //             item.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            //             item.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            //             item.type === "text/csv" ||
            //             (
            //                 item.type === "" && 
            //                 item.getAsFile()?.name?.match(/\.(pdf|docx?|xlsx?|csv|et)$/i)
            //             )
            //         )
            //     ) {
            //         toast.error("File harus berupa dokumen");
            //         return
            //     }
            // }
            if (item.type.indexOf('image') !== -1) {
                const pastedFile = item.getAsFile();
                if (pastedFile) {
                    setAttachmentFile(pastedFile);
                    setFile(Object.assign(pastedFile, {
                        preview: URL.createObjectURL(pastedFile),
                    }));
                    // Optionally update allowed mime-types if you want to restrict
                    e.preventDefault();
                }
            } else if (item.type.indexOf('video') !== -1) {
                const pastedFile = item.getAsFile();
                if (pastedFile) {
                    setAttachmentFile(pastedFile);
                    setFile(Object.assign(pastedFile, {
                        preview: URL.createObjectURL(pastedFile),
                    }));
                    e.preventDefault();
                }
            } else if (
                item.type === "application/pdf" ||
                item.type.startsWith("application/") ||
                item.type.startsWith("text/") ||
                (item.type === "" && item.getAsFile()?.name?.match(/\.(docx?|xlsx?|pptx?|txt|zip|rar|csv)$/i))
            ) {
                const pastedFile = item.getAsFile();
                if (pastedFile) {
                    setAttachmentFile(pastedFile);
                    setFile(Object.assign(pastedFile, {
                        preview: URL.createObjectURL(pastedFile),
                    }));
                    e.preventDefault();
                }
            }
        }
    }
    return (
        <Dialog open={open} onOpenChange={onChangeOpen} 
        >
             <DialogContent className="sm:max-w-4xl">
                <DialogHeader>
                    <DialogTitle>Kirim Pesan Template</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} >
                        <ScrollArea className="h-[500px] w-full pr-4"> {/* Adjust height and add padding for scrollbar */}
                            <div className="grid sm:grid-cols-2 gap-4" onPaste={handlePaste}>
                                <div className="flex flex-col gap-3">
                                    {
                                        !withoutContact && (
                                            <FormField
                                                    control={form.control}
                                                    name="name"
                                                    render={({ field }) => (
                                                        <FormItem>
                                                            <FormLabel>Nama</FormLabel>
                                                            <FormControl>
                                                                <Input  {...field} type="text" placeholder="Nama" className="focus:outline-none"  disabled={!withoutContact}/>
                                                            </FormControl>
                                                            <FormMessage/>
                                                        </FormItem>
                                                    )}
                                            />
                                        )
                                    }
                                   
                                    <FormField
                                            control={form.control}
                                            name="phone_number"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>No Telepon</FormLabel>
                                                    <FormControl>
                                                        {withoutContact ? (
                                                            <Combobox
                                                                data={contactOptions}
                                                                value={field.value}
                                                                onChange={(val) => {
                                                                    field.onChange(val);
                                                                    const selectedContact = contactsData?.find((c: any) => c.phone_number === val);
                                                                    if (selectedContact && !form.getValues("name")) {
                                                                        form.setValue("name", selectedContact.name);
                                                                    }
                                                                }}
                                                                onInputChange={setSearchContactText}
                                                                loading={isFetchingContacts}
                                                                placeholder="Pilih atau ketik No Telepon"
                                                            />
                                                        ) : (
                                                            <Input  {...field} type="text"  placeholder="No Telepon" disabled  required/>
                                                        )}
                                                    </FormControl>
                                                    <FormMessage/>
                                                    <FormDescription className="text-xs">*Format no hp diawali 62. Contoh 6281318227996</FormDescription> 
                                                </FormItem>
                                            )}
                                    />
                                    <FormField
                                            control={form.control}
                                            name="template"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>Template</FormLabel>
                                                    <FormControl>
                                                        <Combobox {...field} data={data?.map((item: any) => ({value:item.id, label:item.name}))}
                                                            onChange={(e) => {
                                                                form.setValue("template",e);
                                                                setFile(null);
                                                                setAttachmentFile(null);
                                                                setDetailTemplate(data.filter((fill:any) => fill.id == e).at(0));
                                                            }}
                                                            placeholder="Pilih template"/>
                                                    </FormControl>
                                                    <FormMessage/>
                                                </FormItem>
                                            )}
                                    />
                                    {headerTemplate && (
                                        <>
                                            <span className="text-sm font-semibold">Header</span>
                                            <span className="border"/>
                                            {headerTemplate?.format == "TEXT" && (
                                                <>
                                                    <FormField
                                                        control={form.control}
                                                        name="name"
                                                        render={({ field }) => (
                                                            <FormItem>
                                                                <FormControl>
                                                                    <Input {...field} type="text" placeholder="Header" disabled value={form.watch('header')}/>
                                                                </FormControl>
                                                                <FormMessage/>
                                                            </FormItem>
                                                        )}
                                                    />
                                                    {headerTemplate?.example && (
                                                        headerTemplate?.example?.header_text?.map((item:any, index: number)  => (
                                                            <FormField
                                                                key={index}
                                                                control={form.control}
                                                                name={`headers.${index}`}
                                                                render={({ field }) => (
                                                                    <FormItem>
                                                                        <FormLabel>{`Parameter Header {{${index + 1}}}`}</FormLabel>
                                                                        <FormControl>
                                                                            <Input {...field} type="text" placeholder={`{{${index + 1}}}`} 
                                                                                defaultValue={item} onChange={(e) => {
                                                                                form.setValue(`headers.${index}` ,  e?.target.value);     
                                                                                form.setValue('header', fillTemplate(headerTemplate?.text, form.getValues('headers')))        
                                                                            }} required />
                                                                        </FormControl>
                                                                        <FormMessage/>
                                                                    </FormItem>
                                                                )}
                                                            />
                                                        ))
                                                    )}
                                                </>
                                            )}

                                            {headerTemplate?.format == "LOCATION" && (
                                                <>
                                                    <div className="flex flex-col gap-1">
                                                        <FormField
                                                            control={form.control}
                                                            name="longitude"
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormControl>
                                                                        <Input type="text" placeholder="Longitude" required {...field}/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                        <FormField
                                                            control={form.control}
                                                            name="latitude"
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormControl>
                                                                        <Input type="text" placeholder="Latitude" required {...field}/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                        <FormField
                                                            control={form.control}
                                                            name="name"
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormControl>
                                                                        <Input type="text" placeholder="Nama Alamat" required {...field}/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                        <FormField
                                                            control={form.control}
                                                            name="address"
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormControl>
                                                                        <Input type="text" placeholder="Alamat"  required {...field}/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                    </div>
                                                </>
                                            )}

                                            {["IMAGE","VIDEO","DOCUMENT"].includes(headerTemplate?.format) && (
                                                <Dropzone
                                                    accept={headerTemplate?.format == "IMAGE" ? {
                                                    "image/*":[]
                                                    }:headerTemplate?.format == "VIDEO" ? {
                                                    "video/*":[]
                                                    }:{
                                                        "*/*":allowed
                                                    }}
                                                    onDrop={(
                                                        acceptedFiles: File[],
                                                        rejection: FileRejection[]
                                                        ) => {
                                                            setFile(Object.assign(acceptedFiles[0], {
                                                                preview: URL.createObjectURL(acceptedFiles[0]),
                                                        }));
                                                    }}
                                                >
                                                {({
                                                getRootProps,
                                                getInputProps,
                                                fileRejections,
                                                acceptedFiles,
                                                }) => (
                                                <div {...getRootProps()} className="cursor-pointer">
                                                    <div className="border-dashed border-2 rounded-md relative w-100 h-auto mt-2  cursor:pointer">
                                                    <div className="flex flex-col justify-center items-center gap-2 m-8">
                                                        {(acceptedFiles.length > 0 || file) ? (
                                                        <>
                                                            <div className="bg-gray-200 text-gray-600 dark:bg-gray-500 dark:text-zinc-900 p-2 rounded-md">
                                                            <FileIcon className="h-4 w-4" />
                                                            </div>
                                                            <span className="text-gray-500 text-sm font-medium text-center">
                                                            {/* {acceptedFiles[0].name ?? file?.name} */}
                                                            {file?.name}
                                                            </span>
                                                            <span className="text-gray-500 text-xs"> 
                                                            {/* {(acceptedFiles[0].size / 1024 / 1024).toFixed(2)} MB */}
                                                            {file?.size ? (file?.size / 1024 / 1024).toFixed(2) : 0} MB
                                                            </span>
                                                        </>
                                                        ) : (
                                                        <>
                                                            <div className="bg-gray-200 text-gray-600 dark:bg-gray-500 dark:text-zinc-900 p-2 rounded-md">
                                                            <UploadIcon className="h-4 w-4" />
                                                            </div>
                                                            <span className="text-gray-500 text-xs">
                                                                Upload {headerTemplate?.format == "IMAGE" ? 'Gambar' : headerTemplate?.format == "VIDEO" ? "Video" : "Dokumem"}
                                                            </span>
                                                        </>
                                                        )}
                                                    </div>
                                                    <input
                                                        type="file"
                                                        {...getInputProps()}
                                                        id="customer_import"
                                                        className="opacity-0 absolute top-0 w-full h-full cursor-pointer"
                                                        data-filename="upload_file"
                                                        accept={headerTemplate?.format == "IMAGE" ? "image/*" : headerTemplate?.format == "VIDEO" ? "video/*" : allowed.join(',')}
                                                    />
                                                    </div>
                                                    {fileRejections.map(({ file, errors }, index) => (
                                                    <div className="flex flex-col mt-2" key={index}>
                                                        {errors.map((item, index) => (
                                                        <span
                                                            className="text-red-800 text-sm"
                                                            key={index}
                                                        >
                                                        </span>
                                                        ))}
                                                    </div>
                                                    ))}
                                                </div>
                                                )}
                                            </Dropzone>
                                            )}
                                        </>
                                    )}
                                    {bodyTemplate && (
                                            <>
                                                <span className="text-sm font-semibold">Body</span>
                                                <span className="border"/>
                                                <FormField
                                                    control={form.control}
                                                    name="body"
                                                    render={({ field }) => (
                                                        <FormItem>
                                                            <FormControl>
                                                                <Textarea rows={5} className="max-w-2xl" disabled  value={form.watch('body')}/>
                                                            </FormControl>
                                                            <FormMessage/>
                                                        </FormItem>
                                                    )}
                                                />
                                                {bodyTemplate?.example && (
                                                    bodyTemplate?.example?.body_text[0]?.map((item:any, index:number) => (
                                                        <FormField
                                                            key={index}
                                                            control={form.control}
                                                            name={`bodies.${index}`}
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormLabel>{`Parameter Body {{${index + 1}}}`}</FormLabel>
                                                                    <FormControl>
                                                                        <Input type="text" placeholder={`{{${index + 1}}}`} 
                                                                            defaultValue={item} onChange={(e) => {
                                                                            form.setValue(`bodies.${index}` ,  e?.target.value);     
                                                                            form.setValue('body', fillTemplate(bodyTemplate?.text, form.getValues('bodies')))        
                                                                        }} required/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                    ))
                                                )}
                                            </>
                                    )}
                                    {footerTemplate && (
                                            <>
                                                <span className="text-sm font-semibold">Footer</span>
                                                <span className="border"/>
                                                <FormField
                                                    control={form.control}
                                                    name={`footer`}
                                                    render={({ field }) => (
                                                        <FormItem>
                                                            <FormControl>
                                                                <Input type="text" placeholder="Footer" value={footerTemplate?.text || ''} disabled/>
                                                            </FormControl>
                                                            <FormMessage/>
                                                        </FormItem>
                                                    )}
                                                />
                                            </>
                                    )}
                                    {buttonTemplate && (
                                        <>
                                            <span className="text-sm font-semibold">Button</span>
                                            <span className="border"/>
                                            {buttonTemplate?.buttons?.map((item:any, index:number) => (
                                                <div key={index}>
                                                    {item?.type == "URL" && (
                                                        item?.example ? (
                                                                <div className="flex flex-row gap-2" >
                                                                    <Label>{item?.url?.replace('/{{1}}','')}</Label>
                                                                    <FormField
                                                                        control={form.control}
                                                                        name={`buttons.${index}`}
                                                                        render={({ field }) => (
                                                                            <FormItem>
                                                                                <FormControl>
                                                                                    <Input {...field}  type="text" placeholder="Path"  required defaultValue={form.getValues(`buttons.${index}`)}/>
                                                                                </FormControl>
                                                                                <FormMessage/>
                                                                            </FormItem>
                                                                        )}
                                                                    />
                                                                </div>
                                                            )

                                                            :
                                                            (
                                                                <FormField
                                                                    control={form.control}
                                                                    name={`buttons.${index}`}
                                                                    render={({ field }) => (
                                                                        <FormItem>
                                                                            <FormControl>
                                                                                <Input {...field}  type="url" placeholder={item.type} disabled defaultValue={form.getValues(`buttons.${index}`)}/>
                                                                            </FormControl>
                                                                            <FormMessage/>
                                                                        </FormItem>
                                                                    )}
                                                                />
                                                            )
                                                    )}
                                                    {item.type == "COPY_CODE" && (
                                                        <FormField
                                                            control={form.control}
                                                            name={`buttons.${index}`}
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormControl>
                                                                        <Input {...field} type="text" placeholder={item.text}  required defaultValue={form.getValues(`buttons.${index}`)}/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                    )}

                                                    {item.type == "QUICK_REPLY" && (
                                                        <FormField
                                                            control={form.control}
                                                            name={`buttons.${index}`}
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormControl>
                                                                        <Input {...field} type="text" placeholder={'Quick Reply '+item.text}  required defaultValue={form.getValues(`buttons.${index}`)}/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                    )}

                                                    {item.type == "PHONE_NUMBER" && (
                                                        <FormField
                                                            control={form.control}
                                                            name={`buttons.${index}`}
                                                            render={({ field }) => (
                                                                <FormItem>
                                                                    <FormControl>
                                                                        <Input {...field}  type="text" placeholder={item.text}  required defaultValue={form.getValues(`buttons.${index}`)}/>
                                                                    </FormControl>
                                                                    <FormMessage/>
                                                                </FormItem>
                                                            )}
                                                        />
                                                    )}
                                                </div>
                                            ))}
                                        </>
                                    )}
                                </div>
                                <div className="shadow p-5 rounded-lg flex flex-col gap-2">
                                    <h4 className="font-medium">Preview Template</h4>
                                    {
                                        detailTemplate && (
                                            <div className="px-3 py-3 rounded-lg shadow-sm text-sm relative flex flex-col gap-2 bg-[#d9fdd3] dark:bg-[#005c4b] rounded-tr-none">
                                                {
                                                    headerTemplate && (
                                                        <>
                                                            {headerTemplate?.format == "TEXT" && (
                                                                <p className="font-semibold">{form.watch('header')}</p>
                                                            )}

                                                            {headerTemplate?.format == "IMAGE" && (
                                                                <>
                                                                    {headerTemplate?.example && (
                                                                        headerTemplate?.example?.header_handle?.map((item:any, index:number) => (
                                                                            <div className="flex flex-col gap-1" key={index}>
                                                                                <Image src={file?.preview ?? item} alt="Gambar" width={500} height={100}/>
                                                                            </div>
                                                                        ))
                                                                    )}
                                                                </>
                                                            )}

                                                            {headerTemplate?.format == "VIDEO" && (
                                                                <>
                                                                    {headerTemplate?.example && (
                                                                        headerTemplate?.example?.header_handle?.map((item:any, index:number) => (
                                                                            <div className="flex flex-col gap-1" key={index}>
                                                                                <video 
                                                                                controls 
                                                                                width="500" 
                                                                                height="250" 
                                                                                autoPlay={false} 
                                                                                src={file?.preview ?? item} 
                                                                                >
                                                                                <source src={file?.preview ?? item} type="video/mp4" />
                                                                                Your browser does not support the video tag.
                                                                                </video>
                                                                            </div>
                                                                        ))
                                                                    )}
                                                                </>
                                                            )}

                                                            {headerTemplate?.format == "DOCUMENT" && (
                                                                <>
                                                                    {headerTemplate?.example && (
                                                                        headerTemplate?.example?.header_handle?.map((item:any, index:number) => (
                                                                            <div className="rounded bg-zinc-800/25 p-3" key={index}>
                                                                                <div className="grid grid-cols-6">
                                                                                    <FileText className="text-white w-10 h-10"/>
                                                                                    <div className="col-span-5">
                                                                                        <p className="text-white ">{file?.name}</p>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        ))
                                                                    )}
                                                                </>
                                                            )}

                                                        </>
                                                    )
                                                }
                                                {
                                                    bodyTemplate && (
                                                        <>
                                                            <p dangerouslySetInnerHTML={{__html:nl2br(parseMessage(form.getValues("body")))}}/>
                                                        </>
                                                    )
                                                }
                                                {
                                                    footerTemplate && (
                                                        <p className="text-xs font-normal text-gray-400">{footerTemplate?.text}</p>
                                                    )
                                                }
                                                
                                                {
                                                    buttonTemplate && (
                                                        <>
                                                            {buttonTemplate?.buttons?.map((item:any, index:number) => (
                                                                <div className="flex flex-col gap-1" key={index}>
                                                                    {
                                                                        item.type == "URL" && (
                                                                            <>
                                                                                <span className="border-b border-gray-200 dark:border-white w-full"></span>
                                                                                <Link href={
                                                                                    item.example ? item.url?.replace('/{{1}}','')+`${form.getValues('buttons.'+index)}` :
                                                                                    `${form.getValues('buttons.'+index)}`
                                                                                } target="_blank">
                                                                                    <Button variant="ghost" type="button" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                                                        <ExternalLink/>
                                                                                        {item.text}
                                                                                    </Button>
                                                                                </Link>
                                                                            </>
                                                                           
                                                                        )
                                                                    }
                                                                    {
                                                                        item.type == "PHONE_NUMBER" && (
                                                                            <>
                                                                                <span className="border-b border-gray-200 dark:border-white w-full"></span>
                                                                                <Button variant="ghost" type="button" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                                                    <Phone/>
                                                                                    {item.text}
                                                                                </Button>
                                                                            </>
                                                                           
                                                                        )
                                                                    }
                                                                    {
                                                                        item.type == "QUICK_REPLY" && (
                                                                            <>
                                                                                <span className="border-b border-gray-200 dark:border-white w-full"></span>
                                                                                <Button variant="ghost" type="button" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                                                    <ReplyIcon/>
                                                                                    {item.text}
                                                                                </Button>
                                                                            </>
                                                                           
                                                                        )
                                                                    }
                                                                    {
                                                                        item.type == "COPY_CODE" && (
                                                                            <>
                                                                                <span className="border-b border-gray-200 dark:border-white w-full"></span>
                                                                                <Button variant="ghost" type="button" size="sm" className="w-full font-normal hover:bg-gray-400/25">
                                                                                    <CopyIcon/>
                                                                                    {item.text}
                                                                                </Button>
                                                                            </>
                                                                           
                                                                        )
                                                                    }
                                                                </div>
                                                            ))}
                                                        </>
                                                    )
                                                }
                                            </div>
                                        )
                                    }
                                </div>
                            </div>
                        </ScrollArea>
                        <DialogFooter>
                            <DialogClose asChild disabled={templateMutate.isPending}>
                                <Button variant="outline">Cancel</Button>
                            </DialogClose>
                            {
                                templateMutate.isPending ?
                                <Button disabled>
                                    <Loader2 className="animate-spin"/>
                                    Kirim
                                </Button>
                                :
                                <Button type="submit">Kirim</Button>

                            }
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    )
}