import { useEffect, useState } from 'react';
import { Button, Input, Switch, TextField, toast } from '@heroui/react';
import {
    ArrowPathIcon,
    ChatBubbleLeftRightIcon,
    CheckCircleIcon,
    ClockIcon,
    ExclamationTriangleIcon,
    EyeIcon,
    PaperAirplaneIcon,
    PlusIcon,
    XCircleIcon,
} from '@heroicons/react/24/solid';
import { api, getErrorMessage } from '@/lib/api';
import { FormModal, FormSection, FullWidth } from '@/Components/ui/FormModal';
import { Field } from '@/Components/ui/Field';
import { SelectField } from '@/Components/ui/SelectField';
import { FileDropzone } from '@/Components/ui/FileDropzone';
import type { KegiatanFormValues } from '@/Components/Kegiatan/KegiatanFields';

interface TemplateItem {
    id: number | string;
    meta_template_id?: string;
    name: string;
    language?: string;
    category?: string;
    status: string;
    components?: any[];
}

interface RecipientPreview {
    row_index: number;
    raw_name: string;
    raw_phone: string;
    phone_number: string | null;
    is_valid: boolean;
    variables: string[];
    named_variables: Record<string, string>;
}

interface PreviewResult {
    headers: string[];
    phone_column_name: string | null;
    name_column_name: string | null;
    recipients: RecipientPreview[];
    total_rows: number;
    valid_count: number;
    invalid_count: number;
}

interface Props {
    kegiatanId?: number | null;
    form: KegiatanFormValues;
    setForm: React.Dispatch<React.SetStateAction<KegiatanFormValues>>;
    readOnly?: boolean;
}

export function WaBlastSection({ kegiatanId, form, setForm, readOnly = false }: Props) {
    const [templates, setTemplates] = useState<TemplateItem[]>([]);
    const [loadingTemplates, setLoadingTemplates] = useState(false);
    const [syncing, setSyncing] = useState(false);

    // Modal Create Template
    const [createModalOpen, setCreateModalOpen] = useState(false);
    const [newTmplName, setNewTmplName] = useState('');
    const [newTmplCategory, setNewTmplCategory] = useState<'UTILITY' | 'MARKETING'>('UTILITY');
    const [newTmplBody, setNewTmplBody] = useState('');
    const [newTmplFooter, setNewTmplFooter] = useState('');
    const [submittingTemplate, setSubmittingTemplate] = useState(false);

    // Preview Contacts
    const [previewSource, setPreviewSource] = useState<'daftar_hadir' | 'gform' | 'file'>('daftar_hadir');
    const [uploadFile, setUploadFile] = useState<File | null>(null);
    const [loadingPreview, setLoadingPreview] = useState(false);
    const [previewData, setPreviewData] = useState<PreviewResult | null>(null);

    // Schedule & Blast Sending
    const [scheduleType, setScheduleType] = useState<'now' | 'scheduled'>(
        form.wa_blast_schedule ? 'scheduled' : 'now'
    );
    const [sendingBlast, setSendingBlast] = useState(false);
    const [campaignStatus, setCampaignStatus] = useState<any>(null);
    const [checkingStatus, setCheckingStatus] = useState(false);

    // Load templates when toggled on or kegiatanId changes
    useEffect(() => {
        if (form.enable_wa_blast) {
            loadTemplates();
            if (kegiatanId) {
                checkBlastStatus();
            }
        }
    }, [form.enable_wa_blast, kegiatanId]);

    const activeKegiatanId = kegiatanId || 0;

    async function loadTemplates() {
        setLoadingTemplates(true);
        try {
            const url = activeKegiatanId
                ? `/kegiatan/${activeKegiatanId}/blast/templates`
                : `/wa-blast/templates`;
            const res = await api.get(url);
            if (res.data?.ok) {
                setTemplates(res.data.templates || []);
                if (form.wa_template_id) {
                    const matched = (res.data.templates || []).find(
                        (t: TemplateItem) => String(t.id) === String(form.wa_template_id)
                    );
                    if (matched) {
                        setForm((s) => ({
                            ...s,
                            wa_template_name: matched.name,
                            wa_template_status: matched.status,
                        }));
                    }
                }
            }
        } catch (err) {
            // Silently handle if not loaded
        } finally {
            setLoadingTemplates(false);
        }
    }

    async function syncTemplates() {
        setSyncing(true);
        try {
            const url = activeKegiatanId
                ? `/kegiatan/${activeKegiatanId}/blast/templates/sync`
                : `/wa-blast/templates/sync`;
            const res = await api.post(url);
            if (res.data?.ok) {
                setTemplates(res.data.templates || []);
                if (res.data.kegiatan_template_status) {
                    setForm((s) => ({
                        ...s,
                        wa_template_status: res.data.kegiatan_template_status,
                    }));
                }
                toast.success('Status template berhasil disinkronkan dengan Meta!');
            }
        } catch (err) {
            toast.danger(getErrorMessage(err, 'Gagal menyinkronkan status template.'));
        } finally {
            setSyncing(false);
        }
    }

    async function handleCreateTemplate() {
        if (!newTmplName.trim() || !newTmplBody.trim()) {
            toast.danger('Nama template dan teks isi pesan wajib diisi.');
            return;
        }

        setSubmittingTemplate(true);
        try {
            const url = activeKegiatanId
                ? `/kegiatan/${activeKegiatanId}/blast/templates`
                : `/wa-blast/templates/create`;

            const res = await api.post(url, {
                name: newTmplName.trim().toLowerCase().replace(/\s+/g, '_'),
                category: newTmplCategory,
                body_text: newTmplBody.trim(),
                footer_text: newTmplFooter.trim() || null,
            });

            if (res.data?.ok) {
                toast.success(res.data.message || 'Template berhasil diajukan ke Meta (status: PENDING).');
                setCreateModalOpen(false);
                setNewTmplName('');
                setNewTmplBody('');
                setNewTmplFooter('');

                const created = res.data.template;
                if (created) {
                    setForm((s) => ({
                        ...s,
                        wa_template_id: String(created.id),
                        wa_template_name: created.name,
                        wa_template_status: created.status || 'pending',
                    }));
                }
                loadTemplates();
            } else {
                toast.danger(res.data?.error || 'Gagal membuat template.');
            }
        } catch (err) {
            toast.danger(getErrorMessage(err, 'Gagal membuat template ke Meta.'));
        } finally {
            setSubmittingTemplate(false);
        }
    }

    async function handlePreviewContacts() {
        setLoadingPreview(true);
        try {
            const url = activeKegiatanId
                ? `/kegiatan/${activeKegiatanId}/blast/preview-recipients`
                : `/kegiatan/0/blast/preview-recipients`;

            let res;
            if (previewSource === 'file' && uploadFile) {
                const fd = new FormData();
                fd.append('file', uploadFile);
                fd.append('source', 'uploaded_file');
                res = await api.post(url, fd, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                });
            } else {
                res = await api.post(url, {
                    source: previewSource === 'gform' ? 'gform_link' : 'daftar_hadir_file',
                });
            }

            if (res.data?.ok) {
                setPreviewData(res.data);
                toast.success(`Berhasil memindai ${res.data.total_rows} baris kontak!`);
            } else {
                toast.danger(res.data?.error || 'Gagal membaca kontak.');
            }
        } catch (err) {
            toast.danger(getErrorMessage(err, 'Gagal memproses berkas kontak.'));
        } finally {
            setLoadingPreview(false);
        }
    }

    async function handleSendBlast() {
        if (!form.wa_template_id) {
            toast.danger('Silakan pilih template pesan WhatsApp terlebih dahulu.');
            return;
        }

        const currentTemplate = templates.find((t) => String(t.id) === String(form.wa_template_id));
        const status = (currentTemplate?.status || form.wa_template_status || '').toLowerCase();

        if (status !== 'approved') {
            toast.danger('Template belum disetujui (APPROVED) oleh Meta. Tunggu review selesai.');
            return;
        }

        if (!previewData || previewData.valid_count === 0) {
            toast.danger('Belum ada kontak valid untuk dikirimi pesan. Silakan klik "Muat / Pratinjau Kontak".');
            return;
        }

        const validRecipients = previewData.recipients.filter((r) => r.is_valid && r.phone_number);

        setSendingBlast(true);
        try {
            const url = activeKegiatanId
                ? `/kegiatan/${activeKegiatanId}/blast/send`
                : `/kegiatan/0/blast/send`;

            const payload = {
                template_id: form.wa_template_id,
                schedule_type: scheduleType,
                scheduled_at: scheduleType === 'scheduled' ? form.wa_blast_schedule : null,
                recipients: validRecipients.map((r) => ({
                    phone_number: r.phone_number,
                    variables: r.variables,
                    named_variables: r.named_variables,
                })),
            };

            const res = await api.post(url, payload);

            if (res.data?.ok) {
                toast.success(res.data.message || 'Blasting WhatsApp berhasil diproses!');
                setForm((s) => ({
                    ...s,
                    wa_blast_status: res.data.campaign?.status || (scheduleType === 'scheduled' ? 'scheduled' : 'processing'),
                }));
                checkBlastStatus();
            } else {
                toast.danger(res.data?.error || 'Gagal mengirim blasting.');
            }
        } catch (err) {
            toast.danger(getErrorMessage(err, 'Gagal mengirim blasting WhatsApp.'));
        } finally {
            setSendingBlast(false);
        }
    }

    async function checkBlastStatus() {
        if (!activeKegiatanId) return;
        setCheckingStatus(true);
        try {
            const res = await api.get(`/kegiatan/${activeKegiatanId}/blast/status`);
            if (res.data?.ok && res.data.has_campaign) {
                setCampaignStatus(res.data.campaign);
            }
        } catch (err) {
            // Silently ignore
        } finally {
            setCheckingStatus(false);
        }
    }

    const selectedTemplate = templates.find((t) => String(t.id) === String(form.wa_template_id));
    const currentStatus = (selectedTemplate?.status || form.wa_template_status || '').toLowerCase();
    const isApproved = currentStatus === 'approved';
    const isPending = currentStatus === 'pending';
    const isRejected = currentStatus === 'rejected';

    return (
        <div className="rounded-2xl border border-gray-200 bg-white p-5 shadow-xs space-y-5">
            {/* Header Switch */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-gray-200">
                <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center w-10 h-10 rounded-xl bg-sky-100 text-sky-600 shrink-0">
                        <ChatBubbleLeftRightIcon className="w-5 h-5" />
                    </div>
                    <div>
                        <h3 className="text-base font-bold text-gray-900">
                            WhatsApp Broadcast / Blasting
                        </h3>
                        <p className="text-xs text-gray-500 mt-0.5">
                            Kirim pesan broadcast ke peserta melalui data berkas daftar hadir kegiatan atau link Google Form.
                        </p>
                    </div>
                </div>

                {!readOnly && (
                    <label className="flex items-center gap-2 cursor-pointer select-none">
                        <span className="text-xs font-medium text-gray-600">
                            {form.enable_wa_blast ? 'Fitur Aktif' : 'Nonaktif'}
                        </span>
                        <Switch
                            isSelected={form.enable_wa_blast}
                            onChange={(val) => setForm((s) => ({ ...s, enable_wa_blast: val }))}
                            size="md"
                        >
                            <Switch.Content>
                                <Switch.Control>
                                    <Switch.Thumb />
                                </Switch.Control>
                            </Switch.Content>
                        </Switch>
                    </label>
                )}
            </div>

            {/* Expanded Blasting Config */}
            {form.enable_wa_blast && (
                <div className="space-y-6 pt-1">
                    {/* Live Campaign Status if already dispatched */}
                    {campaignStatus && (
                        <div className="rounded-xl border border-sky-200 bg-sky-50/70 p-4 space-y-3">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <ClockIcon className="w-4 h-4 text-sky-600" />
                                    <h4 className="text-sm font-semibold text-sky-950">
                                        Status Pengiriman: <span className="uppercase tracking-wide font-bold">{campaignStatus.status}</span>
                                    </h4>
                                </div>
                                <Button
                                    variant="outline"
                                    size="md"
                                    onPress={checkBlastStatus}
                                    isDisabled={checkingStatus}
                                    className="border-sky-300 text-sky-700 hover:bg-sky-100 font-medium"
                                >
                                    <ArrowPathIcon className={`w-4 h-4 ${checkingStatus ? 'animate-spin' : ''}`} />
                                    Segarkan
                                </Button>
                            </div>
                            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center text-xs">
                                <div className="rounded-lg bg-white p-2.5 border border-gray-200 shadow-2xs">
                                    <span className="text-gray-500 block text-[11px]">Total Target</span>
                                    <span className="text-base font-bold text-gray-900">{campaignStatus.total_recipients ?? 0}</span>
                                </div>
                                <div className="rounded-lg bg-white p-2.5 border border-gray-200 shadow-2xs">
                                    <span className="text-gray-500 block text-[11px]">Terkirim</span>
                                    <span className="text-base font-bold text-emerald-600">{campaignStatus.sent_count ?? 0}</span>
                                </div>
                                <div className="rounded-lg bg-white p-2.5 border border-gray-200 shadow-2xs">
                                    <span className="text-gray-500 block text-[11px]">Dibaca</span>
                                    <span className="text-base font-bold text-sky-600">{campaignStatus.read_count ?? 0}</span>
                                </div>
                                <div className="rounded-lg bg-white p-2.5 border border-gray-200 shadow-2xs">
                                    <span className="text-gray-500 block text-[11px]">Gagal</span>
                                    <span className="text-base font-bold text-rose-600">{campaignStatus.failed_count ?? 0}</span>
                                </div>
                            </div>
                            {campaignStatus.scheduled_at && (
                                <p className="text-xs text-sky-800 italic">
                                    Dijadwalkan untuk dikirim pada: {new Date(campaignStatus.scheduled_at).toLocaleString('id-ID')}
                                </p>
                            )}
                        </div>
                    )}

                    {/* Step 1: Template Management */}
                    <div className="rounded-xl border border-gray-200 bg-gray-50/40 p-4 space-y-3">
                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                            <label className="text-xs font-semibold uppercase tracking-wide text-gray-500 flex items-center gap-1.5">
                                <span>1. Template Pesan WhatsApp</span>
                                {loadingTemplates && <ArrowPathIcon className="w-3.5 h-3.5 animate-spin text-gray-400" />}
                            </label>
                            {!readOnly && (
                                <div className="flex items-center gap-2.5">
                                    <Button
                                        variant="outline"
                                        size="md"
                                        onPress={syncTemplates}
                                        isDisabled={syncing}
                                        className="font-medium"
                                    >
                                        <ArrowPathIcon className={`w-4 h-4 ${syncing ? 'animate-spin' : ''}`} />
                                        Sinkronkan Status
                                    </Button>
                                    <Button
                                        variant="primary"
                                        size="md"
                                        onPress={() => setCreateModalOpen(true)}
                                        className="font-medium"
                                    >
                                        <PlusIcon className="w-4 h-4" />
                                        Buat Template Baru
                                    </Button>
                                </div>
                            )}
                        </div>

                        {/* Template SelectField & Status Badge */}
                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 items-end">
                            <div className="sm:col-span-2">
                                <SelectField
                                    label="Pilih Template Pesan"
                                    placeholder="Pilih template terdaftar..."
                                    items={templates.map((t) => ({
                                        id: String(t.id),
                                        label: `${t.name} (${t.status.toUpperCase()} - ${t.category || 'UTILITY'})`,
                                    }))}
                                    selectedKey={form.wa_template_id ? String(form.wa_template_id) : null}
                                    onSelectionChange={(key) => {
                                        const val = key ? String(key) : '';
                                        const tmpl = templates.find((t) => String(t.id) === val);
                                        setForm((s) => ({
                                            ...s,
                                            wa_template_id: val,
                                            wa_template_name: tmpl?.name || '',
                                            wa_template_status: tmpl?.status || 'pending',
                                        }));
                                    }}
                                    isDisabled={readOnly}
                                    clearable
                                />
                            </div>

                            {/* Approval Status Badge */}
                            <div className="pb-1">
                                {form.wa_template_id ? (
                                    isApproved ? (
                                        <div className="flex items-center gap-1.5 text-xs font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-3 py-2 rounded-xl">
                                            <CheckCircleIcon className="w-4 h-4 text-emerald-600 shrink-0" />
                                            <span>APPROVED (Siap Kirim)</span>
                                        </div>
                                    ) : isPending ? (
                                        <div className="flex items-center gap-1.5 text-xs font-semibold text-amber-700 bg-amber-50 border border-amber-200 px-3 py-2 rounded-xl">
                                            <ClockIcon className="w-4 h-4 text-amber-600 shrink-0" />
                                            <span>PENDING (Menunggu Persetujuan)</span>
                                        </div>
                                    ) : (
                                        <div className="flex items-center gap-1.5 text-xs font-semibold text-rose-700 bg-rose-50 border border-rose-200 px-3 py-2 rounded-xl">
                                            <XCircleIcon className="w-4 h-4 text-rose-600 shrink-0" />
                                            <span>REJECTED (Ditolak)</span>
                                        </div>
                                    )
                                ) : (
                                    <span className="text-xs text-gray-400 italic">Pilih template untuk cek status</span>
                                )}
                            </div>
                        </div>

                        {/* Notice for Pending Approval */}
                        {isPending && (
                            <div className="rounded-xl border border-amber-200 bg-amber-50/70 p-3 flex items-start gap-2.5 text-xs text-amber-800">
                                <ExclamationTriangleIcon className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
                                <div>
                                    <span className="font-semibold">Template masih dalam proses peninjauan:</span>
                                    <p className="mt-0.5 text-amber-700">
                                        Pesan blast hanya dapat dikirim saat template sudah disetujui (<strong>APPROVED</strong>). Klik tombol <strong>"Sinkronkan Status"</strong> secara berkala untuk memperbarui status.
                                    </p>
                                </div>
                            </div>
                        )}

                        {/* Template Message Live Preview */}
                        {selectedTemplate && (
                            <div className="rounded-xl border border-gray-200 bg-white p-4 space-y-3">
                                <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-1.5 text-xs font-semibold text-gray-700">
                                        <EyeIcon className="w-4 h-4 text-sky-600" />
                                        <span>Pratinjau Isi Pesan Template</span>
                                    </div>
                                    <span className="text-[11px] font-mono px-2 py-0.5 rounded bg-gray-100 text-gray-600">
                                        {selectedTemplate.language || 'id'} • {selectedTemplate.category || 'UTILITY'}
                                    </span>
                                </div>

                                {(() => {
                                    const bodyComp = selectedTemplate.components?.find((c: any) => String(c.type).toUpperCase() === 'BODY');
                                    const headerComp = selectedTemplate.components?.find((c: any) => String(c.type).toUpperCase() === 'HEADER');
                                    const footerComp = selectedTemplate.components?.find((c: any) => String(c.type).toUpperCase() === 'FOOTER');
                                    const rawBody = bodyComp?.text || (selectedTemplate as any).body_text || '(Tidak ada teks pesan)';

                                    const firstRecipient = previewData?.recipients?.[0];
                                    const sampleName = firstRecipient?.raw_name && firstRecipient.raw_name !== '-'
                                        ? firstRecipient.raw_name
                                        : 'Budi Santoso (Contoh)';

                                    // Replace {{nama}}, {{name}}, {{1}} with first contact or fallback
                                    let renderedBody = rawBody
                                        .replace(/\{\{\s*nama\s*\}\}/gi, sampleName)
                                        .replace(/\{\{\s*name\s*\}\}/gi, sampleName)
                                        .replace(/\{\{\s*1\s*\}\}/g, sampleName);

                                    // Replace other named variables if present in preview
                                    if (firstRecipient?.named_variables) {
                                        Object.entries(firstRecipient.named_variables).forEach(([k, val]) => {
                                            if (val && k !== 'nama' && k !== 'name' && k !== '1') {
                                                const reg = new RegExp(`\\{\\{\\s*${k}\\s*\\}\\}`, 'gi');
                                                renderedBody = renderedBody.replace(reg, val);
                                            }
                                        });
                                    }

                                    return (
                                        <div className="space-y-2.5">
                                            {/* WhatsApp-style bubble */}
                                            <div className="rounded-2xl rounded-tl-xs bg-[#eef7ee] border border-emerald-200/80 p-3.5 sm:p-4 text-xs sm:text-sm text-gray-800 shadow-2xs max-w-xl space-y-2">
                                                {headerComp?.text && (
                                                    <div className="font-bold text-gray-900 pb-1 border-b border-emerald-200/60">
                                                        {headerComp.text}
                                                    </div>
                                                )}
                                                <div className="whitespace-pre-wrap leading-relaxed">
                                                    {renderedBody}
                                                </div>
                                                {footerComp?.text && (
                                                    <div className="text-[11px] text-gray-500 pt-1 border-t border-emerald-200/60">
                                                        {footerComp.text}
                                                    </div>
                                                )}
                                                <div className="flex justify-end pt-1">
                                                    <span className="text-[10px] text-gray-400 font-mono">Pratinjau Pesan</span>
                                                </div>
                                            </div>

                                            {/* Variable hint */}
                                            <div className="flex flex-wrap items-center gap-2 text-xs text-gray-500 bg-gray-50 p-2.5 rounded-lg border border-gray-100">
                                                <span className="font-medium text-gray-700">Keterangan Variabel:</span>
                                                {firstRecipient ? (
                                                    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200 font-medium">
                                                        Variabel <code className="font-mono text-[11px] font-bold">{'{{nama}}'}</code> / <code className="font-mono text-[11px] font-bold">{'{{1}}'}</code> diganti menjadi <strong>"{sampleName}"</strong> (data baris pertama dari daftar peserta).
                                                    </span>
                                                ) : (
                                                    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-amber-50 text-amber-700 border border-amber-200">
                                                        Belum memuat kontak. Tampilan di atas menggunakan contoh nama <strong>"Budi Santoso"</strong>. Klik <em>"Muat / Pratinjau Kontak"</em> di bawah untuk melihat nama riil peserta.
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    );
                                })()}
                            </div>
                        )}
                    </div>

                    {/* Step 2: Schedule Option */}
                    <div className="rounded-xl border border-gray-200 bg-gray-50/40 p-4 space-y-3">
                        <label className="text-xs font-semibold uppercase tracking-wide text-gray-500 block">
                            2. Pengaturan Waktu Pengiriman
                        </label>
                        <div className="flex flex-wrap gap-4">
                            <label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
                                <input
                                    type="radio"
                                    name="scheduleType"
                                    disabled={readOnly}
                                    checked={scheduleType === 'now'}
                                    onChange={() => {
                                        setScheduleType('now');
                                        setForm((s) => ({ ...s, wa_blast_schedule: '' }));
                                    }}
                                    className="text-sky-600 focus:ring-sky-500"
                                />
                                <span>Kirim Langsung (Seketika)</span>
                            </label>
                            <label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
                                <input
                                    type="radio"
                                    name="scheduleType"
                                    disabled={readOnly}
                                    checked={scheduleType === 'scheduled'}
                                    onChange={() => setScheduleType('scheduled')}
                                    className="text-sky-600 focus:ring-sky-500"
                                />
                                <span>Jadwalkan Pengiriman</span>
                            </label>
                        </div>

                        {scheduleType === 'scheduled' && (
                            <div className="mt-2 max-w-xs">
                                <Field
                                    label="Waktu Pengiriman (WIB)"
                                    type="datetime-local"
                                    value={form.wa_blast_schedule || ''}
                                    onChange={(v) => setForm((s) => ({ ...s, wa_blast_schedule: v }))}
                                    disabled={readOnly}
                                />
                            </div>
                        )}
                    </div>

                    {/* Step 3: Contact Source & Smart Detection Preview */}
                    <div className="rounded-xl border border-gray-200 bg-gray-50/40 p-4 space-y-3">
                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                            <label className="text-xs font-semibold uppercase tracking-wide text-gray-500">
                                3. Sumber Kontak & Deteksi Pintar Kolom
                            </label>
                            <Button
                                variant="outline"
                                size="md"
                                onPress={handlePreviewContacts}
                                isDisabled={loadingPreview || (previewSource === 'file' && !uploadFile)}
                                className="text-sky-700 border-sky-300 hover:bg-sky-50 font-medium"
                            >
                                <ArrowPathIcon className={`w-4 h-4 ${loadingPreview ? 'animate-spin' : ''}`} />
                                {loadingPreview ? 'Memindai Kontak...' : 'Muat / Pratinjau Kontak'}
                            </Button>
                        </div>

                        {/* Source Switcher Pills */}
                        <div className="flex flex-wrap gap-2.5 text-sm">
                            <button
                                type="button"
                                onClick={() => setPreviewSource('daftar_hadir')}
                                className={`px-4 py-2 rounded-xl border font-medium cursor-pointer transition-colors ${
                                    previewSource === 'daftar_hadir'
                                        ? 'border-sky-600 bg-sky-50 text-sky-700'
                                        : 'border-gray-200 bg-white text-gray-700 hover:bg-gray-50'
                                }`}
                            >
                                Berkas Daftar Hadir (XLSX) Kegiatan
                            </button>
                            <button
                                type="button"
                                onClick={() => setPreviewSource('gform')}
                                className={`px-4 py-2 rounded-xl border font-medium cursor-pointer transition-colors ${
                                    previewSource === 'gform'
                                        ? 'border-sky-600 bg-sky-50 text-sky-700'
                                        : 'border-gray-200 bg-white text-gray-700 hover:bg-gray-50'
                                }`}
                            >
                                Link Google Sheet / GForm Peserta
                            </button>
                            <button
                                type="button"
                                onClick={() => setPreviewSource('file')}
                                className={`px-4 py-2 rounded-xl border font-medium cursor-pointer transition-colors ${
                                    previewSource === 'file'
                                        ? 'border-sky-600 bg-sky-50 text-sky-700'
                                        : 'border-gray-200 bg-white text-gray-700 hover:bg-gray-50'
                                }`}
                            >
                                Unggah Berkas Kontak Baru (.xlsx / .csv)
                            </button>
                        </div>

                        {previewSource === 'file' && (
                            <div className="pt-2">
                                <FileDropzone
                                    label="Berkas Kontak (.xlsx, .xls, .csv)"
                                    file={uploadFile}
                                    onChange={setUploadFile}
                                    accept=".xlsx,.xls,.csv,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                                />
                            </div>
                        )}

                        {/* Smart Detection Results */}
                        {previewData && (
                            <div className="space-y-3 pt-3 border-t border-gray-200">
                                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
                                    <div className="rounded-xl bg-white p-3 border border-gray-200 shadow-2xs text-xs">
                                        <span className="text-gray-400 block mb-0.5">Kolom Telepon Terdeteksi:</span>
                                        <span className="font-semibold text-emerald-700 font-mono">
                                            {previewData.phone_column_name ? `"${previewData.phone_column_name}"` : '⚠️ Tidak ditemukan'}
                                        </span>
                                    </div>
                                    <div className="rounded-xl bg-white p-3 border border-gray-200 shadow-2xs text-xs">
                                        <span className="text-gray-400 block mb-0.5">Kolom Nama Terdeteksi:</span>
                                        <span className="font-semibold text-sky-700 font-mono">
                                            {previewData.name_column_name ? `"${previewData.name_column_name}"` : '⚠️ Tidak ditemukan'}
                                        </span>
                                    </div>
                                    <div className="rounded-xl bg-white p-3 border border-gray-200 shadow-2xs text-xs flex items-center justify-between">
                                        <div>
                                            <span className="text-gray-400 block mb-0.5">Nomor Siap Kirim:</span>
                                            <span className="font-bold text-emerald-700 text-sm">
                                                {previewData.valid_count} / {previewData.total_rows}
                                            </span>
                                        </div>
                                        {previewData.invalid_count > 0 && (
                                            <span className="text-[11px] text-amber-700 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-md font-medium">
                                                {previewData.invalid_count} diabaikan
                                            </span>
                                        )}
                                    </div>
                                </div>

                                {/* Preview Table matching DataTable standards */}
                                <div className="overflow-x-auto rounded-xl border border-gray-200 bg-white">
                                    <table className="w-full text-sm">
                                        <thead>
                                            <tr className="bg-gray-50 border-b border-gray-200">
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Baris</th>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama</th>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No. Input Asli</th>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No. Normalisasi E.164</th>
                                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-gray-100">
                                            {previewData.recipients.slice(0, 10).map((r) => (
                                                <tr key={r.row_index} className={!r.is_valid ? 'bg-amber-50/40 text-gray-400' : 'hover:bg-gray-50'}>
                                                    <td className="px-3 py-2 text-xs font-mono text-gray-500">{r.row_index}</td>
                                                    <td className="px-3 py-2 text-xs font-medium text-gray-800">{r.raw_name || '-'}</td>
                                                    <td className="px-3 py-2 text-xs font-mono text-gray-600">{r.raw_phone || '-'}</td>
                                                    <td className="px-3 py-2 text-xs font-mono font-medium text-emerald-700">
                                                        {r.phone_number || '-'}
                                                    </td>
                                                    <td className="px-3 py-2 text-xs">
                                                        {r.is_valid ? (
                                                            <span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 text-[10px] px-2 py-0.5 font-medium">
                                                                <CheckCircleIcon className="w-3 h-3 text-emerald-600" /> Siap
                                                            </span>
                                                        ) : (
                                                            <span className="inline-flex items-center gap-1 rounded-full bg-rose-50 text-rose-700 border border-rose-200 text-[10px] px-2 py-0.5 font-medium">
                                                                <XCircleIcon className="w-3 h-3 text-rose-600" /> Invalid
                                                            </span>
                                                        )}
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                                {previewData.recipients.length > 10 && (
                                    <p className="text-[11px] text-gray-400 italic text-right">
                                        Menampilkan 10 dari {previewData.total_rows} total kontak penerima.
                                    </p>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Step 4: Dispatch / Trigger Blasting */}
                    {!readOnly && (
                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-4 rounded-xl border border-gray-200 bg-gray-50">
                            <div>
                                <h4 className="text-sm font-bold text-gray-900">
                                    {scheduleType === 'scheduled' ? 'Jadwalkan Pengiriman' : 'Kirim Pesan Sekarang'}
                                </h4>
                                <p className="text-xs text-gray-500 mt-0.5">
                                    Pesan akan dikirimkan otomatis ke seluruh nomor kontak yang siap kirim.
                                </p>
                            </div>

                            <Button
                                variant="primary"
                                size="lg"
                                onPress={handleSendBlast}
                                isDisabled={
                                    sendingBlast ||
                                    !isApproved ||
                                    !previewData ||
                                    previewData.valid_count === 0
                                }
                                className="px-6 py-3 text-sm font-semibold shadow-sm gap-2"
                            >
                                <PaperAirplaneIcon className="w-5 h-5" />
                                {sendingBlast
                                    ? 'Memproses...'
                                    : scheduleType === 'scheduled'
                                    ? 'Jadwalkan Pengiriman'
                                    : 'Kirim Sekarang'}
                            </Button>
                        </div>
                    )}
                </div>
            )}

            {/* Modal Buat Template Baru via standard FormModal */}
            <FormModal
                isOpen={createModalOpen}
                onOpenChange={setCreateModalOpen}
                title="Buat Template WhatsApp Baru"
                subtitle="Daftarkan template pesan baru untuk kegiatan ini."
                icon={<ChatBubbleLeftRightIcon className="w-5 h-5 text-sky-600" />}
                onSubmit={handleCreateTemplate}
                isSubmitting={submittingTemplate}
                submitLabel="Ajukan Template"
            >
                <FullWidth>
                    <Field
                        label="Nama Template"
                        value={newTmplName}
                        onChange={(v) => setNewTmplName(v.toLowerCase().replace(/[^a-z0-9_]/g, ''))}
                        placeholder="contoh: undangan_kegiatan_pelatihan"
                        required
                    />
                    <p className="text-[11px] text-gray-400 mt-1">
                        Hanya huruf kecil, angka, dan garis bawah (_).
                    </p>
                </FullWidth>

                <FullWidth>
                    <SelectField
                        label="Kategori"
                        items={[
                            { id: 'UTILITY', label: 'UTILITY (Pemberitahuan, Pengingat, Undangan)' },
                            { id: 'MARKETING', label: 'MARKETING (Promosi, Penawaran)' },
                        ]}
                        selectedKey={newTmplCategory}
                        onSelectionChange={(key) => setNewTmplCategory((key || 'UTILITY') as any)}
                    />
                </FullWidth>

                <FullWidth>
                    <Field
                        label="Isi Pesan (Body)"
                        value={newTmplBody}
                        onChange={setNewTmplBody}
                        multiline
                        placeholder="Halo {{nama}}, terima kasih telah hadir dalam acara kami..."
                        required
                    />
                    <p className="text-[11px] text-gray-400 mt-1">
                        Gunakan variabel seperti <code>{'{{nama}}'}</code> atau <code>{'{{1}}'}</code> untuk personalisasi data spreadsheet.
                    </p>
                </FullWidth>

                <FullWidth>
                    <Field
                        label="Footer Teks (Opsional)"
                        value={newTmplFooter}
                        onChange={setNewTmplFooter}
                        placeholder="PT Natagara Solusi Digital"
                    />
                </FullWidth>
            </FormModal>
        </div>
    );
}
