"use client";

import React, { useState, useCallback } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";

import { Loader2, ArrowLeft, Image as ImageIcon, Video, FileText, Plus, X, Smile, Bold, Italic, Strikethrough, Code } from "lucide-react";
import { useUpdateTemplate, useGetTemplate, useGetTemplateCategories } from "@/hooks/useTemplateHooks";
import { useAuth } from "@/contexts/auth-context";
import { formatPreview } from "@/lib/utils";
import { useDropzone } from "react-dropzone";
import EmojiPicker from "emoji-picker-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";

const templateSchema = z.object({
    name: z.string().min(1, "Name is required").regex(/^[a-z0-9_]+$/, "Lowercase alphanumeric and underscores only"),
    category: z.string().min(1, "Category is required"),
    template_category: z.number().optional(),
    language: z.string().min(1, "Language is required"),
    header_type: z.string(),
    header_text: z.string().optional(),
    body_text: z.string().min(1, "Body text is required"),
    footer_text: z.string().optional(),
    buttons: z.array(z.object({
        type: z.string(),
        text: z.string().min(1, "Button text is required"),
        url_type: z.string().optional(),
        url: z.string().optional(),
        phone_number: z.string().optional(),
        example: z.string().optional(),
    })).optional(),
    sample_header: z.array(z.string()).optional(),
    sample_body: z.array(z.string()).optional(),
});

type TemplateFormValues = z.infer<typeof templateSchema>;

interface TemplateEditProps {
    onBack: () => void;
    templateId: string;
}

export default function TemplateEdit({ onBack, templateId }: TemplateEditProps) {
    const { user } = useAuth();
    const updateTemplateMutation = useUpdateTemplate(templateId);
    const { data: templateData, isLoading: isLoadingData } = useGetTemplate(templateId);
    const { data: templateCategories, isLoading: isLoadingCategories } = useGetTemplateCategories();
    const [fileHeader, setFileHeader] = useState<File & { preview?: string } | null>(null);
    const [localOnly, setLocalOnly] = useState(false);

    const { register, control, handleSubmit, watch, setValue, getValues, formState: { errors }, reset } = useForm<TemplateFormValues>({
        resolver: zodResolver(templateSchema),
        defaultValues: {
            name: "",
            category: "MARKETING",
            template_category: 1,
            language: "id",
            header_type: "NONE",
            header_text: "",
            body_text: "",
            footer_text: "",
            buttons: [],
            sample_header: [],
            sample_body: []
        }
    });

    const { fields, append, remove } = useFieldArray({
        control,
        name: "buttons"
    });

    const watchAllFields = watch();

    React.useEffect(() => {
        if (templateData) {
            const data = templateData;
            const newValues: Partial<TemplateFormValues> = {
                name: data.name,
                category: data.category || 'MARKETING',
                template_category: data.template_category || 1,
                language: data.language || 'id',
                header_type: 'NONE',
                header_text: '',
                body_text: '',
                footer_text: '',
                buttons: [],
                sample_header: [],
                sample_body: []
            };

            data.components?.forEach((component: any) => {
                if (component.type === 'HEADER') {
                    newValues.header_type = component.format;
                    newValues.header_text = component.text || '';
                    if (component.format !== "TEXT" && component.format !== "NONE") {
                        const mediaUrl = data?.media?.media_url || (component.example?.header_handle && component.example.header_handle[0]);
                        if (mediaUrl) {
                            setFileHeader(Object.assign(new File([""], "existing_file"), { preview: mediaUrl }));
                        }
                    }
                    if (component.format === "TEXT" && component.example?.header_text) {
                        newValues.sample_header = [component.example.header_text[0]];
                    }
                }
                if (component.type === 'BODY') {
                    newValues.body_text = component.text || '';
                    if (component.example?.body_text) {
                        newValues.sample_body = component.example.body_text[0] || [];
                    }
                }
                if (component.type === 'FOOTER') {
                    newValues.footer_text = component.text || '';
                }
                if (component.type === 'BUTTONS' && component.buttons) {
                    newValues.buttons = component.buttons.map((button: any) => ({
                        type: button.type,
                        text: button.text,
                        url: button.url,
                        url_type: button.example ? 'DYNAMIC' : 'STATIC',
                        example: button.example && button.example.length > 0 ? button.example[0] : '',
                        phone_number: button.phone_number
                    }));
                }
            });

            reset(newValues as TemplateFormValues);
        }
    }, [templateData, reset]);

    const onSubmit = async (data: TemplateFormValues) => {
        const payload = new FormData();
        if (localOnly) {
            payload.append('local_only', '1');
        }
        payload.append('updated_by', JSON.stringify(user));
        payload.append('name', data.name);
        payload.append('category', data.category);
        if (data.template_category !== undefined) {
            payload.append('template_category', String(data.template_category));
        }
        payload.append('language', data.language);
        payload.append('header_type', data.header_type || 'NONE');
        payload.append('body_text', data.body_text);
        payload.append('footer_text', data.footer_text || '');
        
        if (data.header_type === 'TEXT' && data.header_text) {
            payload.append('header_text', data.header_text);
        }

        const examples = {
            body_text: data.sample_body || [],
            header_text: data.sample_header || []
        };
        payload.append('examples', JSON.stringify(examples));
        payload.append('buttons', JSON.stringify(data.buttons || []));

        if (fileHeader) {
            payload.append('header_handle', fileHeader);
        }

        await updateTemplateMutation.mutateAsync(payload);
        onBack();
    };

    const onDropHeader = useCallback((acceptedFiles: File[]) => {
        const file = acceptedFiles[0];
        if (file) {
            setFileHeader(Object.assign(file, {
                preview: URL.createObjectURL(file)
            }));
        }
    }, []);

    const { getRootProps, getInputProps } = useDropzone({
        onDrop: onDropHeader,
        accept: watchAllFields.header_type === 'IMAGE' ? { 'image/*': [] } : 
                watchAllFields.header_type === 'VIDEO' ? { 'video/*': [] } : 
                { 'application/pdf': [] },
        multiple: false
    });

    const getVariablesCount = (text: string) => {
        const matches = text.match(/{{(\d+)}}/g);
        return matches ? matches.length : 0;
    };

    const handleAddVariable = (field: 'header_text' | 'body_text') => {
        const current = getValues(field) || '';
        const count = getVariablesCount(current);
        if (field === 'header_text' && count >= 1) return; // Only 1 var for header
        setValue(field, `${current} {{${count + 1}}}`, { shouldValidate: true });
    };

    const handleFormatBody = (format: string) => {
        const current = getValues('body_text') || '';
        let wrap = '';
        if (format === 'bold') wrap = '*';
        if (format === 'italic') wrap = '_';
        if (format === 'strikethrough') wrap = '~';
        if (format === 'monospace') wrap = '```';
        setValue('body_text', `${current}${wrap}${wrap}`, { shouldValidate: true });
    };

    return (
        <div className="flex flex-col h-full bg-[#f0f2f5] dark:bg-[#111b21] overflow-hidden">
            <div className="flex items-center px-6 py-4 bg-white dark:bg-[#202c33] border-b border-gray-200 dark:border-gray-800">
                <Button variant="ghost" size="icon" onClick={onBack} className="mr-4">
                    <ArrowLeft className="w-5 h-5 text-gray-500" />
                </Button>
                <h1 className="text-xl font-semibold text-gray-800 dark:text-gray-100">Edit Template Whatsapp</h1>
            </div>

            {isLoadingData ? (
                <div className="flex-1 flex justify-center items-center">
                    <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
                </div>
            ) : (
                <div className="flex-1 overflow-auto p-6 flex flex-col md:flex-row gap-6 items-start">
                {/* FORM LEFT SIDE */}
                <div className="flex-1 w-full bg-white dark:bg-[#202c33] p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-800 space-y-6">
                    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="block text-sm font-medium mb-1">Kategori</label>
                                <select 
                                    className="flex h-10 w-full items-center justify-between rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-[#111b21] dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus:ring-gray-300"
                                    onChange={(e) => setValue("category", e.target.value)} 
                                    defaultValue={watchAllFields.category}
                                >
                                    <option value="" disabled>Pilih Kategori</option>
                                    <option value="MARKETING">Marketing</option>
                                    <option value="UTILITY">Utility</option>
                                    <option value="AUTHENTICATION">Authentication</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium mb-1">Kategori Internal</label>
                                <select 
                                    className="flex h-10 w-full items-center justify-between rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-[#111b21] dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus:ring-gray-300"
                                    onChange={(e) => setValue("template_category", Number(e.target.value))} 
                                    defaultValue={watchAllFields.template_category}
                                    disabled={isLoadingCategories}
                                >
                                    {templateCategories?.map((cat: any) => (
                                        <option key={cat.id} value={cat.id}>{cat.name}</option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-medium mb-1">Bahasa</label>
                                <select 
                                    className="flex h-10 w-full items-center justify-between rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-[#111b21] dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus:ring-gray-300"
                                    onChange={(e) => setValue("language", e.target.value)} 
                                    defaultValue={watchAllFields.language}
                                >
                                    <option value="" disabled>Pilih Bahasa</option>
                                    <option value="id">Indonesian</option>
                                    <option value="en">English</option>
                                </select>
                            </div>
                        </div>

                        <div>
                            <label className="block text-sm font-medium mb-1">Nama Template</label>
                            <Input {...register("name")} placeholder="contoh: promo_merdeka_2024" />
                            {errors.name && <span className="text-xs text-red-500">{errors.name.message}</span>}
                            <p className="text-xs text-gray-500 mt-1">Hanya huruf kecil, angka, dan garis bawah (_)</p>
                        </div>

                        {/* HEADER */}
                        <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-md">
                            <h3 className="font-medium mb-4">Header (Opsional)</h3>
                            <div className="text-xs text-yellow-600 mb-2">Note: To change image/video, select the type again.</div>
                            <select 
                                className="flex mb-4 h-10 w-full items-center justify-between rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-[#111b21] dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus:ring-gray-300"
                                onChange={(e) => { setValue("header_type", e.target.value); setFileHeader(null); }} 
                                defaultValue={watchAllFields.header_type}
                            >
                                <option value="" disabled>Tipe Header</option>
                                <option value="NONE">None</option>
                                <option value="TEXT">Text</option>
                                <option value="IMAGE">Image</option>
                                <option value="VIDEO">Video</option>
                                <option value="DOCUMENT">Document</option>
                            </select>

                            {watchAllFields.header_type === 'TEXT' && (
                                <div className="space-y-2">
                                    <Input {...register("header_text")} placeholder="Masukkan teks header" />
                                    <Button type="button" variant="outline" size="sm" onClick={() => handleAddVariable('header_text')}>+ Tambah Variabel</Button>
                                    {getVariablesCount(watchAllFields.header_text || '') > 0 && (
                                        <div className="mt-2 p-3 bg-gray-50 dark:bg-gray-800 rounded">
                                            <label className="text-xs font-semibold">Sample Variabel Header</label>
                                            <Input {...register(`sample_header.0`)} placeholder="Contoh: Diskon 50%" className="mt-1" size={1} />
                                        </div>
                                    )}
                                </div>
                            )}

                            {['IMAGE', 'VIDEO', 'DOCUMENT'].includes(watchAllFields.header_type || '') && (
                                <div {...getRootProps()} className="border-2 border-dashed border-gray-300 dark:border-gray-600 p-6 text-center cursor-pointer rounded-md hover:bg-gray-50 dark:hover:bg-gray-800">
                                    <input {...getInputProps()} />
                                    {fileHeader ? (
                                        <p className="text-sm text-green-600 font-medium">{fileHeader.name} terpilih.</p>
                                    ) : (
                                        <p className="text-sm text-gray-500">Tarik dan lepas file di sini, atau klik untuk memilih file</p>
                                    )}
                                </div>
                            )}
                        </div>

                        {/* BODY */}
                        <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-md">
                            <h3 className="font-medium mb-4">Body</h3>
                            <Textarea {...register("body_text")} placeholder="Masukkan teks pesan..." rows={5} />
                            {errors.body_text && <span className="text-xs text-red-500">{errors.body_text.message}</span>}
                            
                            <div className="flex items-center gap-2 mt-2">
                                <Button type="button" variant="outline" size="sm" onClick={() => handleAddVariable('body_text')}>+ Variabel</Button>
                                <Popover>
                                    <PopoverTrigger asChild>
                                        <Button type="button" variant="ghost" size="icon"><Smile className="w-4 h-4" /></Button>
                                    </PopoverTrigger>
                                    <PopoverContent className="w-auto p-0 border-none" align="start">
                                        {/* @ts-ignore - emoji-picker-react types mismatch with React 18 in this setup */}
                                        <EmojiPicker onEmojiClick={(e) => {
                                            const current = getValues('body_text');
                                            setValue('body_text', current + e.emoji);
                                        }} />
                                    </PopoverContent>
                                </Popover>
                                <Button type="button" variant="ghost" size="icon" onClick={() => handleFormatBody('bold')}><Bold className="w-4 h-4" /></Button>
                                <Button type="button" variant="ghost" size="icon" onClick={() => handleFormatBody('italic')}><Italic className="w-4 h-4" /></Button>
                                <Button type="button" variant="ghost" size="icon" onClick={() => handleFormatBody('strikethrough')}><Strikethrough className="w-4 h-4" /></Button>
                                <Button type="button" variant="ghost" size="icon" onClick={() => handleFormatBody('monospace')}><Code className="w-4 h-4" /></Button>
                            </div>

                            {getVariablesCount(watchAllFields.body_text || '') > 0 && (
                                <div className="mt-4 p-3 bg-gray-50 dark:bg-gray-800 rounded space-y-2">
                                    <label className="text-xs font-semibold">Sample Variabel Body</label>
                                    {Array.from({ length: getVariablesCount(watchAllFields.body_text || '') }).map((_, i) => (
                                        <Input key={`body-var-${i}`} {...register(`sample_body.${i}`)} placeholder={`Sample untuk {{${i+1}}}`} className="mt-1" />
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* FOOTER */}
                        <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-md">
                            <h3 className="font-medium mb-4">Footer (Opsional)</h3>
                            <Input {...register("footer_text")} placeholder="Teks kecil di bagian bawah pesan" />
                        </div>

                        {/* BUTTONS */}
                        <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-md">
                            <h3 className="font-medium mb-4">Tombol (Opsional)</h3>
                            {fields.map((field, index) => (
                                <div key={field.id} className="p-4 mb-4 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-[#1a2328] relative">
                                    <Button type="button" variant="ghost" size="icon" className="absolute top-2 right-2 h-6 w-6 text-red-500" onClick={() => remove(index)}>
                                        <X className="w-4 h-4" />
                                    </Button>
                                    <div className="grid grid-cols-2 gap-4 mb-4">
                                        <div>
                                            <label className="text-xs font-medium">Tipe Tombol</label>
                                            <select 
                                                className="flex h-10 w-full items-center justify-between rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-[#111b21] dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus:ring-gray-300"
                                                onChange={(e) => setValue(`buttons.${index}.type` as const, e.target.value)} 
                                                defaultValue={watch(`buttons.${index}.type`)}
                                            >
                                                <option value="" disabled>Pilih Tipe</option>
                                                <option value="QUICK_REPLY">Quick Reply (Kustom)</option>
                                                <option value="URL">Buka Situs Web</option>
                                                <option value="PHONE_NUMBER">Telepon</option>
                                                <option value="COPY_CODE">Salin Kode Promo</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label className="text-xs font-medium">Teks Tombol</label>
                                            <Input {...register(`buttons.${index}.text` as const)} placeholder="Teks tombol" />
                                        </div>
                                    </div>

                                    {watch(`buttons.${index}.type`) === 'URL' && (
                                        <div className="grid grid-cols-2 gap-4">
                                            <div>
                                                <label className="text-xs font-medium">Tipe URL</label>
                                                <select 
                                                    className="flex h-10 w-full items-center justify-between rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-[#111b21] dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus:ring-gray-300"
                                                    onChange={(e) => setValue(`buttons.${index}.url_type` as const, e.target.value)} 
                                                    defaultValue="STATIC"
                                                >
                                                    <option value="" disabled>Pilih Tipe URL</option>
                                                    <option value="STATIC">Statis</option>
                                                    <option value="DYNAMIC">Dinamis</option>
                                                </select>
                                            </div>
                                            <div>
                                                <label className="text-xs font-medium">URL</label>
                                                <Input {...register(`buttons.${index}.url` as const)} placeholder="https://example.com" />
                                            </div>
                                        </div>
                                    )}

                                    {watch(`buttons.${index}.type`) === 'PHONE_NUMBER' && (
                                        <div className="mt-2">
                                            <label className="text-xs font-medium">Nomor Telepon</label>
                                            <Input {...register(`buttons.${index}.phone_number` as const)} placeholder="+628123456789" />
                                        </div>
                                    )}
                                    
                                    {watch(`buttons.${index}.type`) === 'COPY_CODE' && (
                                        <div className="mt-2">
                                            <label className="text-xs font-medium">Kode Promo</label>
                                            <Input {...register(`buttons.${index}.example` as const)} placeholder="PROMO2024" />
                                        </div>
                                    )}
                                </div>
                            ))}

                            <div className="flex gap-2">
                                <Button type="button" variant="outline" size="sm" onClick={() => append({ type: 'QUICK_REPLY', text: '' })}>+ Quick Reply</Button>
                                <Button type="button" variant="outline" size="sm" onClick={() => append({ type: 'URL', text: '', url_type: 'STATIC', url: '' })}>+ URL</Button>
                                <Button type="button" variant="outline" size="sm" onClick={() => append({ type: 'PHONE_NUMBER', text: '', phone_number: '' })}>+ Telepon</Button>
                            </div>
                        </div>

                        <div className="flex flex-col gap-4 sm:flex-row justify-between items-center pt-4">
                            <label className="flex items-center space-x-2 text-sm text-gray-700 dark:text-gray-300">
                                <input 
                                    type="checkbox" 
                                    className="rounded border-gray-300 text-[#00a884] focus:ring-[#00a884]"
                                    checked={localOnly}
                                    onChange={(e) => setLocalOnly(e.target.checked)}
                                />
                                <span>Hanya simpan Kategori Internal (Tidak akan mengirim update ke Meta)</span>
                            </label>
                            <Button type="submit" className="bg-[#00a884] hover:bg-[#008f6f] text-white" disabled={updateTemplateMutation.isPending}>
                                {updateTemplateMutation.isPending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                                Update Template
                            </Button>
                        </div>
                    </form>
                </div>

                {/* PREVIEW RIGHT SIDE */}
                <div className="w-full md:w-[350px] flex-shrink-0 sticky top-0">
                    <div className="bg-white dark:bg-[#202c33] p-4 rounded-lg shadow-sm border border-gray-200 dark:border-gray-800 text-center mb-4">
                        <h2 className="font-semibold">Preview</h2>
                    </div>
                    
                    {/* Mock Phone */}
                        <div className="w-full h-[600px] bg-[#efeae2] dark:bg-[#0b141a] rounded-3xl border-[8px] border-gray-800 dark:border-black overflow-hidden relative shadow-xl flex flex-col" style={{ backgroundImage: "url('https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png')", backgroundSize: 'cover' }}>
                            {/* App Bar */}
                            <div className="bg-[#075e54] dark:bg-[#202c33] h-14 flex items-center px-4 shadow-sm z-10">
                                <ArrowLeft className="w-5 h-5 text-white mr-2" />
                                <div className="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 mr-3"></div>
                                <span className="text-white font-medium">WhatsApp</span>
                            </div>

                            {/* Chat Area */}
                            <div className="flex-1 p-4 overflow-y-auto flex flex-col">
                                <div className="mt-auto w-full flex flex-col">
                                    <div className="bg-white dark:bg-[#202c33] p-2 rounded-lg rounded-tl-none shadow-sm max-w-[90%] w-full self-start mb-2 relative">
                                    {/* Header Preview */}
                                    {watchAllFields.header_type === 'TEXT' && watchAllFields.header_text && (
                                        <div className="font-bold text-sm mb-2 text-gray-800 dark:text-gray-100 whitespace-pre-wrap"
                                             dangerouslySetInnerHTML={{ __html: formatPreview(watchAllFields.header_text, watchAllFields.sample_header || []) }} />
                                    )}
                                    {watchAllFields.header_type === 'IMAGE' && (
                                        <div className="w-full h-32 bg-gray-200 dark:bg-gray-700 rounded mb-2 flex items-center justify-center overflow-hidden">
                                            {fileHeader?.preview ? <img src={fileHeader.preview} className="w-full h-full object-cover" /> : <ImageIcon className="w-8 h-8 text-gray-400" />}
                                        </div>
                                    )}
                                    {watchAllFields.header_type === 'VIDEO' && (
                                        <div className="w-full h-32 bg-gray-200 dark:bg-gray-700 rounded mb-2 flex items-center justify-center overflow-hidden">
                                            {fileHeader?.preview ? <video src={fileHeader.preview} className="w-full h-full object-cover" /> : <Video className="w-8 h-8 text-gray-400" />}
                                        </div>
                                    )}
                                    {watchAllFields.header_type === 'DOCUMENT' && (
                                        <div className="w-full p-3 bg-gray-100 dark:bg-gray-800 rounded mb-2 flex items-center border border-gray-200 dark:border-gray-700">
                                            <div className="w-10 h-10 bg-red-100 text-red-500 rounded flex items-center justify-center mr-3">
                                                <FileText className="w-6 h-6" />
                                            </div>
                                            <div className="flex-1 min-w-0">
                                                <p className="text-sm font-medium truncate dark:text-gray-200">{fileHeader?.name || "document.pdf"}</p>
                                                <p className="text-xs text-gray-500">PDF Document</p>
                                            </div>
                                        </div>
                                    )}

                                    {/* Body Preview */}
                                    {watchAllFields.body_text ? (
                                        <p className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-words"
                                           dangerouslySetInnerHTML={{ __html: formatPreview(watchAllFields.body_text, watchAllFields.sample_body || []) }} />
                                    ) : (
                                        <p className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-words">
                                            Pesan Anda...
                                        </p>
                                    )}

                                    {/* Footer Preview */}
                                    {watchAllFields.footer_text && (
                                        <p className="text-[11px] text-gray-500 mt-2 leading-tight"
                                           dangerouslySetInnerHTML={{ __html: formatPreview(watchAllFields.footer_text, []) }} />
                                    )}
                                </div>
                                
                                {/* Buttons Preview */}
                                {watchAllFields.buttons && watchAllFields.buttons.length > 0 && (
                                    <div className="flex flex-col gap-1 w-[90%] self-start">
                                        {watchAllFields.buttons.map((btn, idx) => (
                                            <div key={idx} className="bg-white dark:bg-[#202c33] text-[#00a884] dark:text-[#00a884] font-medium text-sm p-3 text-center rounded-lg shadow-sm w-full border border-gray-100 dark:border-gray-800">
                                                {btn.text || "Tombol"}
                                            </div>
                                        ))}
                                    </div>
                                )}
                                </div>
                            </div>
                        </div>
                </div>
            </div>
            )}
        </div>
    );
}
