import React, { useState, useEffect, useCallback } from 'react'
import type { DashboardData } from '../../types'

interface CampaignFormData {
    name: string;
    send_whatsapp: number;
    send_email: number;
    send_meta: number | boolean;
    instances: string[];
    role_ids: string[];
    user_ids: string[];
    external_numbers: string;
    external_emails: string;
    billing_countries: string[];
    wp_profile_languages: string[];
    total_spent_min: string | number;
    orders_count_min: string | number;
    only_verified_phone: number;
    woo_order_statuses: string[];
    woo_ordered_products: string[];
    email_subject: string;
    email_message: string;
    email_content_json: string;
    message: string;
    start_datetime: string;
    min_whatsapp_interval: string | number;
    max_whatsapp_interval: string | number;
    wa_daily_limit: string | number;
    min_email_interval: string | number;
    max_email_interval: string | number;
    email_daily_limit: string | number;
    repeat_campaign: string;
    message_type: string;
    media_url: string;
    share_post_id: string;
    share_product_id: string;
    append_info: number;
    post_info: { title: number; excerpt: number; link: number; image: number;[key: string]: number };
    product_info: { title: number; price: number; description: number; link: number; image: number;[key: string]: number };
    email_template_id: string;
    meta_message_type: string;
    meta_template_id: string;
    repeat_days: string | number;
    append_post: number;
    append_product: number;
    // For other potential dynamic fields
    [key: string]: unknown;
}
import {
    Users,
    Send,
    Clock,
    ChevronRight,
    ChevronLeft,
    CheckCircle2,
    Zap,
    Rocket,
    Type,
    Loader2,
    ShoppingCart,
    Hash,
    Image as ImageIcon,
    Mail as MailIcon,
    CheckCircle2 as CheckIcon
} from 'lucide-react'
import { AdminButton, SecondaryButton, GhostButton, SettingInput } from '../ui/settings-ui'
import { Label } from '../ui/label'
import { Textarea } from '../ui/textarea'
import { Separator } from '../ui/separator'
import { Switch } from '../ui/switch'
import { Checkbox } from '../ui/checkbox'
import { motion, AnimatePresence } from 'framer-motion'
import { Badge } from '../ui/badge'
import { cn } from "src/lib/utils"
import { MultiSelectTagify } from '../ui/multi-select-tagify'
import { SearchableSelect } from '../ui/searchable-select'
import { PersonalizationDialog } from '../ui/personalization-dialog'
import { WhatsAppRuleConfig } from '../ui/whatsapp-rule-config'
import { EmojiPickerButton } from '../ui/whatsapp-toolbar'
import { ModernCardHeader, SettingCard } from '../ui/settings-ui'

interface MetaTemplate {
    name: string;
    langs: string[];
    id?: string | number;
    label?: string;
    value?: string;
    language?: string;
}



interface WizardProps {
    initialData?: Partial<CampaignFormData>;
    onSave: (data: CampaignFormData) => void;
    onCancel: () => void;
    meta: {
        roles: { label: string; id: string }[];
        users: { label: string; id: string }[];
        products: { label: string; id: string }[];
        posts: { label: string; id: string }[];
        email_templates: { name: string; id: string }[];
        instances: { label: string; id: string }[];
        woo_countries: Record<string, string>;
        templates: MetaTemplate[];
        icon_base_url: string;
        nonces: {
            calc: string;
            preview: string;
        };
        rootData: DashboardData;
    }
}

const getSteps = () => [
    { id: 'basic', title: 'Channels', icon: <Zap className="w-5 h-5 opacity-40 grayscale" /> },
    { id: 'audience', title: 'Audience', icon: <Users className="w-5 h-5 opacity-40 grayscale" /> },
    { id: 'filters', title: 'WooCommerce', icon: <Rocket className="w-5 h-5 opacity-40 grayscale" /> },
    { id: 'content', title: 'Content', icon: <Type className="w-5 h-5 opacity-40 grayscale" /> },
    { id: 'schedule', title: 'Scheduling', icon: <Clock className="w-5 h-5 opacity-40 grayscale" /> },
    { id: 'confirm', title: 'Review', icon: <CheckCircle2 className="w-5 h-5 opacity-40 grayscale" /> },
]

export default function CampaignWizard({ initialData, onSave, onCancel, meta }: WizardProps) {
    const steps = getSteps()
    const [currentStep, setCurrentStep] = useState(0)

    const [formData, setFormData] = useState<CampaignFormData>(() => {
        const base = initialData || {
            name: '',
            send_whatsapp: 1,
            send_email: 0,
            send_meta: 0,
            instances: [],
            role_ids: [],
            user_ids: [],
            external_numbers: '',
            external_emails: '',
            billing_countries: [],
            wp_profile_languages: [],
            total_spent_min: 0,
            orders_count_min: 0,
            only_verified_phone: 0,
            woo_order_statuses: [],
            woo_ordered_products: [],
            email_subject: '',
            email_message: '',
            email_content_json: '',
            message: '',
            start_datetime: '',
            min_whatsapp_interval: 5,
            max_whatsapp_interval: 10,
            wa_daily_limit: 500,
            min_email_interval: 5,
            max_email_interval: 10,
            email_daily_limit: 0,
            repeat_campaign: 'no_repeat',
            message_type: 'text',
            media_url: '',
            share_post_id: '',
            share_product_id: '',
            append_info: 0,
            post_info: { title: 1, excerpt: 1, link: 1, image: 0 },
            product_info: { title: 1, price: 1, description: 0, link: 1, image: 0 },
            email_template_id: '',
            meta_message_type: 'session',
            meta_template_id: '',
            repeat_days: 1,
            append_post: 0,
            append_product: 0,
        };

        if (!initialData) {
            const saved = localStorage.getItem('wawp_campaign_wizard_draft');
            if (saved) {
                try {
                    const parsed = JSON.parse(saved);
                    return { ...base, ...parsed };
                } catch (e: unknown) {
                    console.error("Failed to load draft", e);
                }
            }
        }
        return base;
    });

    const [isCalculating, setIsCalculating] = useState(false)
    const [recipientCount, setRecipientCount] = useState<number | null>(null)
    const [personalizationOpen, setPersonalizationOpen] = useState(false)

    // Render-time sync for initialData changes
    const [prevInitialData, setPrevInitialData] = useState(initialData);
    if (initialData !== prevInitialData) {
        setPrevInitialData(initialData);
        if (initialData) {
            const normalized = { ...initialData } as Record<string, unknown>;
            ['role_ids', 'user_ids', 'billing_countries', 'wp_profile_languages', 'woo_order_statuses', 'woo_ordered_products'].forEach(key => {
                if (normalized[key] && typeof normalized[key] === 'string') {
                    normalized[key] = (normalized[key] as string).split(',').filter(Boolean);
                } else if (!normalized[key]) {
                    normalized[key] = [];
                }
            });
            if (normalized.repeat_type && !normalized.repeat_campaign) {
                normalized.repeat_campaign = normalized.repeat_type;
            }
            setFormData(normalized as CampaignFormData);
        }
    }

    const calculateRecipients = useCallback(async () => {
        if (Object.keys(formData).length < 5) return
        setIsCalculating(true)

        try {
            const res = await fetch(`${meta.rootData.global.apiRestUrl}/campaigns/calc`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': meta.rootData.global.wpRestNonce
                },
                body: JSON.stringify(formData)
            })
            const json = await res.json()
            const n = parseInt(json.data?.count || json.data || 0)
            setRecipientCount(isNaN(n) ? -1 : n)
        } catch (e: unknown) {
            console.error("Calculation failed", e)
            setRecipientCount(-1)
        } finally {
            setIsCalculating(false)
        }
    }, [formData, meta.rootData.global.apiRestUrl, meta.rootData.global.wpRestNonce])

    useEffect(() => {
        const timer = setTimeout(() => {
            calculateRecipients()
        }, 1000)
        return () => clearTimeout(timer)
    }, [calculateRecipients])

    // draftLoaded ref is no longer needed since we initialize from localStorage directly
    // useEffect for loading draft is removed to avoid set-state-in-effect error

    useEffect(() => {
        if (!initialData) {
            localStorage.setItem('wawp_campaign_wizard_draft', JSON.stringify(formData));
        }
    }, [formData, initialData]);

    const handleNext = () => {
        if (currentStep < steps.length - 1) {
            setCurrentStep(currentStep + 1)
        }
    }

    const handleBack = () => {
        if (currentStep > 0) {
            setCurrentStep(currentStep - 1)
        }
    }

    const updateField = (field: string, value: unknown) => {
        setFormData((prev: CampaignFormData) => ({ ...prev, [field]: value }))
    }

    const toggleArrayItem = (field: string, item: string) => {
        setFormData((prev: CampaignFormData) => {
            const arr = (prev[field] as string[]) || []
            const newArr = arr.includes(item) ? arr.filter((i: string) => i !== item) : [...arr, item]
            return { ...prev, [field]: newArr }
        })
    }

    const insertAtCursor = (id: string, text: string, field: string) => {
        const el = document.getElementById(id) as HTMLTextAreaElement | HTMLInputElement;
        if (el) {
            const s = el.selectionStart || 0;
            const e = el.selectionEnd || 0;
            const val = (formData[field] as string) || '';
            const next = val.substring(0, s) + text + val.substring(e);
            updateField(field, next);

            setTimeout(() => {
                el.focus();
                el.setSelectionRange(s + text.length, s + text.length);
            }, 50);
        } else {
            const val = formData[field] || '';
            updateField(field, val + text);
        }
    };

    const onKeyDownWhatsApp = (e: React.KeyboardEvent<HTMLTextAreaElement>, field: string) => {
        if (e.key === 'Enter') {
            const el = e.currentTarget;
            const val = el.value;
            const start = el.selectionStart;
            const lineStart = val.lastIndexOf('\n', start - 1) + 1;
            const currentLine = val.substring(lineStart, start);

            const bulletMatch = currentLine.match(/^(\* | - |> )/);
            const numberMatch = currentLine.match(/^(\d+)\. /);

            if (bulletMatch || numberMatch) {
                const prefix = bulletMatch ? bulletMatch[0] : `${parseInt(numberMatch![1]) + 1}. `;

                if (currentLine.trim() === prefix.trim().replace(/\d+/, '').replace('.', '')) {
                    e.preventDefault();
                    const nextVal = val.substring(0, lineStart) + val.substring(start);
                    updateField(field, nextVal);
                } else {
                    e.preventDefault();
                    const nextVal = val.substring(0, start) + '\n' + prefix + val.substring(start);
                    updateField(field, nextVal);
                    setTimeout(() => {
                        el.setSelectionRange(start + 1 + prefix.length, start + 1 + prefix.length);
                    }, 50);
                }
            }
        }
    };

    return (
        <SettingCard className="w-full overflow-hidden flex flex-col min-h-[700px] shadow-none">
            <ModernCardHeader
                title={initialData ? 'Edit Campaign' : 'Create New Bulk Campaign'}
                description="Target your audience with personalized messages"
                icon={Rocket}
                rightAction={
                    <div className="flex items-center gap-2 text-sm font-semibold text-slate-700 bg-white px-4 py-2 rounded-lg border border-slate-200">
                        {isCalculating ? (
                            <div className="flex items-center gap-2 text-blue-600 font-medium whitespace-nowrap">
                                <Loader2 className="w-4 h-4 animate-spin text-blue-400" />
                                Calculating...
                            </div>
                        ) : (
                            <div className="flex items-center gap-2 whitespace-nowrap">
                                <Users className="w-4 h-4 text-purple-500" />
                                <span>{recipientCount?.toLocaleString() || 0} Recipients</span>
                            </div>
                        )}
                    </div>
                }
            />

            <div className="bg-slate-50/10 border-b border-slate-100 p-6">
                <div className="flex items-center justify-between relative px-2 max-w-4xl mx-auto">
                    {steps.map((step, idx: number) => (
                        <div
                            key={step.id}
                            className="flex flex-col items-center z-10 basis-1 cursor-pointer group"
                            onClick={() => setCurrentStep(idx)}
                        >
                            <div className={cn(
                                "w-9 h-9 rounded-full flex items-center justify-center border-2 transition-all duration-300 group-hover:scale-110",
                                currentStep === idx ? "bg-[#004449] border-[#004449] text-white scale-105 group-hover:scale-105" :
                                    currentStep > idx ? "bg-emerald-500 border-emerald-500 text-white" : "bg-white border-slate-200 text-slate-400"
                            )}>
                                {currentStep > idx ? <CheckIcon className="w-4.5 h-4.5" /> : step.icon}
                            </div>
                            <span className={cn(
                                "text-[9px] uppercase tracking-widest font-black mt-2.5 transition-colors",
                                currentStep === idx ? "text-[#004449]" : "text-slate-400 group-hover:text-slate-600"
                            )}>{step.title}</span>
                        </div>
                    ))}
                    <div className="absolute top-[18px] left-10 right-10 h-0.5 bg-slate-100 -z-0">
                        <div className="h-full bg-[#004449] transition-all duration-500" style={{ width: `${(currentStep / (steps.length - 1)) * 100}%` }}></div>
                    </div>
                </div>
            </div>

            <div className="flex-1 p-8 overflow-y-auto">
                <AnimatePresence mode="wait">
                    <motion.div
                        key={steps[currentStep].id}
                        initial={{ opacity: 0, x: 20 }}
                        animate={{ opacity: 1, x: 0 }}
                        exit={{ opacity: 0, x: -20 }}
                        className="space-y-6"
                    >
                        {currentStep === 0 && (
                            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 text-left">
                                <div className="space-y-3">
                                    <SettingInput
                                        label="Campaign Name"
                                        value={formData.name}
                                        onChange={(val) => updateField('name', val)}
                                        placeholder="E.g. Ramadan Sale 2024"
                                        className="text-lg"
                                        icon={Rocket}
                                    />
                                </div>
                                <Separator className="opacity-50" />
                                <div className="space-y-4 pt-4">
                                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1 flex items-center gap-2">
                                        <Send className="w-3.5 h-3.5" /> Dispatch Channels Selection <span className="text-red-500">*</span>
                                    </label>

                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                        {[
                                            { id: 'send_whatsapp', label: 'Whatsapp Web', description: 'Direct WAWP engine', iconPath: (meta.rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg", color: 'text-emerald-600', bg: 'bg-emerald-50', border: 'border-emerald-100' },
                                            { id: 'send_meta', label: 'Meta WhatsApp', description: 'Business API approved', iconPath: (meta.rootData.global?.pluginUrl || '') + "assets/img/senders/meta.svg", color: 'text-blue-600', bg: 'bg-blue-50', border: 'border-blue-100' },
                                            { id: 'send_email', label: 'Email Dispatch', description: 'Secure SMTP delivery', iconPath: (meta.rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg", color: 'text-orange-600', bg: 'bg-orange-50', border: 'border-orange-100' }
                                        ].map(channel => {
                                            const isActive = Number(formData[channel.id]) === 1;
                                            return (
                                                <div key={channel.id} className="relative group">
                                                    <label className={`flex items-center gap-3 p-3 rounded-xl border-2 transition-all cursor-pointer relative overflow-hidden h-full ${isActive ? "bg-white border-[#004449] ring-4 ring-[#004449]/5" : "bg-white border-slate-100 hover:border-slate-200"
                                                        }`}>
                                                        <input
                                                            type="checkbox"
                                                            className="sr-only"
                                                            checked={isActive}
                                                            onChange={() => updateField(channel.id, isActive ? 0 : 1)}
                                                        />
                                                        <div className={`w-10 h-10 rounded-lg flex items-center justify-center transition-all border duration-300 shrink-0 ${isActive ? `${channel.bg} ${channel.border}` : "bg-slate-50 border-slate-100"
                                                            }`}>
                                                            <img src={channel.iconPath} className="w-5 h-5 object-contain" alt="" />
                                                        </div>
                                                        <div className="flex-1 min-w-0 flex flex-col justify-center">
                                                            <h4 className="text-[13px] font-bold tracking-tight !m-0 !p-0 leading-tight text-slate-900">{channel.label}</h4>
                                                            <p className="text-[10px] font-medium text-slate-500 truncate !m-0 !p-0 leading-tight">{channel.description}</p>
                                                        </div>
                                                        {isActive && (
                                                            <div className="w-5 h-5 rounded-full bg-[#004449] border-2 border-[#004449] text-white flex items-center justify-center transition-all shrink-0">
                                                                <CheckIcon size={12} strokeWidth={3} />
                                                            </div>
                                                        )}
                                                    </label>
                                                </div>
                                            );
                                        })}
                                    </div>
                                </div>
                                {Number(formData.send_whatsapp) === 1 && (
                                    <div className="space-y-4 animate-in slide-in-from-top-2">
                                        <Label className="text-base font-bold flex items-center gap-2">
                                            <Zap className="w-4 h-4 text-green-600" /> WhatsApp Instances <span className="text-red-500">*</span>
                                        </Label>
                                        <MultiSelectTagify
                                            options={meta.instances.map(i => ({ label: i.label, value: i.id }))}
                                            selected={formData.instances}
                                            onChange={(vals) => updateField('instances', vals)}
                                            placeholder="Select WhatsApp Instances..."
                                        />
                                    </div>
                                )}
                            </div>
                        )}

                        {currentStep === 1 && (
                            <div className="space-y-8 animate-in fade-in text-left">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                    <div className="space-y-4">
                                        <Label className="text-base font-bold">Target User Roles</Label>
                                        <MultiSelectTagify
                                            options={meta.roles.map(r => ({ label: r.label, value: r.id }))}
                                            selected={formData.role_ids}
                                            onChange={(vals) => updateField('role_ids', vals)}
                                            placeholder="Select roles..."
                                        />
                                    </div>
                                    <div className="space-y-4">
                                        <Label className="text-base font-bold">Target Specific Users</Label>
                                        <MultiSelectTagify
                                            options={meta.users.map(u => ({ label: u.label, value: u.id }))}
                                            selected={formData.user_ids}
                                            onChange={(vals) => updateField('user_ids', vals)}
                                            placeholder="Search specific users..."
                                        />
                                    </div>
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-4">
                                    <div className="space-y-4">
                                        <Label className="text-base font-bold">External Numbers (WhatsApp)</Label>
                                        <p className="text-[10px] text-gray-500 -mt-2">Enter one number per line.</p>
                                        <Textarea
                                            value={formData.external_numbers}
                                            onChange={(e) => updateField('external_numbers', e.target.value)}
                                            placeholder="201012345678"
                                            className="min-h-[100px] text-xs font-mono"
                                        />
                                    </div>
                                    <div className="space-y-4">
                                        <Label className="text-base font-bold">External Emails</Label>
                                        <p className="text-[10px] text-gray-500 -mt-2">Enter one email per line.</p>
                                        <Textarea
                                            value={formData.external_emails}
                                            onChange={(e) => updateField('external_emails', e.target.value)}
                                            placeholder="user@example.com"
                                            className="min-h-[100px] text-xs font-mono"
                                        />
                                    </div>
                                </div>
                                <div className="p-4 rounded-lg flex items-center justify-between w-full md:w-1/2 bg-slate-50/50 border">
                                    <div className="space-y-0.5">
                                        <Label className="font-bold">Only Verified Phone Numbers?</Label>
                                        <p className="text-[10px] text-gray-500">Only target users marked as verified in WAWP.</p>
                                    </div>
                                    <Switch checked={Number(formData.only_verified_phone) === 1} onCheckedChange={(val) => updateField('only_verified_phone', val ? 1 : 0)} />
                                </div>
                            </div>
                        )}

                        {currentStep === 2 && (
                            <div className="space-y-8 animate-in fade-in text-left">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                    <div className="space-y-4">
                                        <Label className="text-base font-bold">Billing Country</Label>
                                        <p className="text-xs text-gray-400">Filter by user billing country.</p>
                                        <MultiSelectTagify
                                            options={Object.entries(meta.woo_countries).map(([code, name]) => ({ label: name, value: code }))}
                                            selected={formData.billing_countries}
                                            onChange={(vals) => updateField('billing_countries', vals)}
                                            placeholder="Select countries..."
                                        />
                                    </div>
                                    <div className="space-y-4">
                                        <Label className="text-base font-bold">WordPress Profile Language</Label>
                                        <p className="text-xs text-gray-400">Filter by user's profile language.</p>
                                        <MultiSelectTagify
                                            options={[
                                                { label: 'English', value: 'en_US' },
                                                { label: 'Arabic', value: 'ar' },
                                                { label: 'French', value: 'fr_FR' },
                                                { label: 'Spanish', value: 'es_ES' },
                                                { label: 'German', value: 'de_DE' }
                                            ]}
                                            selected={formData.wp_profile_languages}
                                            onChange={(vals) => updateField('wp_profile_languages', vals)}
                                            placeholder="Select languages..."
                                        />
                                    </div>
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <SettingInput
                                        label="Min. Total Spent"
                                        type="number"
                                        value={String(formData.total_spent_min)}
                                        onChange={(val) => updateField('total_spent_min', val)}
                                        icon={ShoppingCart}
                                    />
                                    <SettingInput
                                        label="Min. Order Count"
                                        type="number"
                                        value={String(formData.orders_count_min)}
                                        onChange={(val) => updateField('orders_count_min', val)}
                                        icon={Hash}
                                    />
                                </div>
                                <div className="space-y-4">
                                    <Label className="text-base font-bold">Purchased Specific Products</Label>
                                    <MultiSelectTagify
                                        options={meta.products.map(p => ({ label: p.label, value: p.id }))}
                                        selected={formData.woo_ordered_products}
                                        onChange={(vals) => updateField('woo_ordered_products', vals)}
                                        placeholder="Search specific products..."
                                    />
                                </div>
                                <div className="space-y-4">
                                    <Label className="text-base font-bold">Order Statuses Filters</Label>
                                    <div className="flex flex-wrap gap-2">
                                        {['wc-completed', 'wc-processing', 'wc-on-hold', 'wc-pending', 'wc-cancelled', 'wc-refunded'].map(status => (
                                            <div key={status} className="flex items-center space-x-2 bg-gray-100 px-3 py-1.5 rounded-full border border-gray-200 cursor-pointer" onClick={() => toggleArrayItem('woo_order_statuses', status)}>
                                                <Checkbox checked={formData.woo_order_statuses.includes(status)} />
                                                <span className="text-[10px]">{status.replace('wc-', '')}</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        )}

                        {currentStep === 3 && (
                            <div className="space-y-8 animate-in fade-in text-left">
                                <div className="bg-blue-50/50 p-4 rounded-lg border border-blue-100 flex items-start gap-4 mb-6">
                                    <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center shrink-0">
                                        <Send className="w-5 h-5 text-blue-600" />
                                    </div>
                                    <div>
                                        <h4 className="font-bold text-blue-900 text-sm italic">Message Type Strategy</h4>
                                        <p className="text-[11px] text-blue-800 leading-relaxed italic opacity-80 mt-0.5">"Text with Media" is specific to WhatsApp. For Email, media is embedded in the HTML body. Post/Product sharing adds content to enabled channels.</p>
                                    </div>
                                </div>

                                <div className="space-y-4 p-6 bg-white rounded-xl border border-input">
                                    <div className="flex items-center gap-2 mb-2 font-bold text-gray-700">
                                        <Users className="w-4 h-4" /> Message Type
                                    </div>
                                    <SearchableSelect
                                        value={formData.message_type}
                                        onChange={(val: string) => updateField('message_type', val)}
                                        placeholder="Select Message Type..."
                                        searchPlaceholder="Search message types..."
                                        options={[
                                            { value: 'text', label: 'Text Only' },
                                            { value: 'media', label: 'Text with Media (WhatsApp)' },
                                            { value: 'wp_post', label: 'Share WordPress Post/Page' },
                                            { value: 'woo_product', label: 'Share WooCommerce Product' }
                                        ]}
                                    />
                                </div>

                                {Number(formData.send_whatsapp) === 1 && (
                                    <div className="space-y-6 pt-4">
                                        <WhatsAppRuleConfig
                                            type="campaign"
                                            editorId="campaign_wa_instance_ed"
                                            rule={{ ...formData, _wa_driver: 'instance' }}
                                            updateRule={(updates) => setFormData((prev: CampaignFormData) => ({ ...prev, ...updates }))}
                                            metaTemplates={meta.templates}
                                            onOpenPersonalization={() => setPersonalizationOpen(true)}
                                            onKeyDown={(e) => onKeyDownWhatsApp(e, 'message')}
                                            customFields={{
                                                message: 'message',
                                                messageType: 'meta_message_type',
                                                templateId: 'meta_template_id',
                                                driver: '_wa_driver'
                                            }}
                                        />
                                    </div>
                                )}

                                {Number(formData.send_meta) === 1 && (
                                    <div className="space-y-6 pt-4">
                                        <WhatsAppRuleConfig
                                            type="campaign"
                                            editorId="campaign_wa_meta_ed"
                                            rule={{ ...formData, _wa_driver: 'meta' }}
                                            updateRule={(updates) => setFormData((prev: CampaignFormData) => ({ ...prev, ...updates }))}
                                            metaTemplates={meta.templates}
                                            onOpenPersonalization={() => setPersonalizationOpen(true)}
                                            onKeyDown={(e) => onKeyDownWhatsApp(e, 'message')}
                                            customFields={{
                                                message: 'message',
                                                messageType: 'meta_message_type',
                                                templateId: 'meta_template_id',
                                                driver: '_wa_driver'
                                            }}
                                        />
                                        <p className="text-[10px] text-gray-400 italic px-1">Templates are used only for business-initiated conversations on Meta API.</p>
                                    </div>
                                )}

                                <PersonalizationDialog
                                    open={personalizationOpen}
                                    onOpenChange={setPersonalizationOpen}
                                    placeholders={meta.rootData?.notificationsData?.placeholders || {}}
                                    onInsert={(tag) => insertAtCursor('campaign_wa_msg', tag, 'message')}
                                />

                                {Number(formData.send_email) === 1 && (
                                    <div className="space-y-6 pt-8 border-t border-gray-100 mt-8">
                                        <div className="border rounded-xl bg-white overflow-hidden border-input">
                                            <div className="px-4 py-3 bg-gray-50/50 border-b flex items-center justify-between">
                                                <div className="flex items-center gap-2 font-bold text-gray-700">
                                                    <MailIcon className="w-4 h-4 text-slate-500" />
                                                    <span className="text-xs">Email Campaign Marketing</span>
                                                </div>
                                                <Badge variant="outline" className="h-5 px-1.5 text-[9px] font-bold bg-white border-slate-200 text-slate-500">
                                                    SMTP / API
                                                </Badge>
                                            </div>

                                            <div className="p-6 space-y-6">
                                                <div className="space-y-2">
                                                    <div className="flex items-center justify-between">
                                                        <Label className="text-xs font-bold text-gray-500 uppercase tracking-widest text-left">Email Subject <span className="text-red-500">*</span></Label>
                                                        <div className="flex items-center gap-1">
                                                            <EmojiPickerButton
                                                                targetId="campaign_em_subj"
                                                                value={formData.email_subject}
                                                                onChange={(val: string) => updateField('email_subject', val)}
                                                            />
                                                            <GhostButton
                                                                className="h-8 px-2 text-xs gap-1.5 text-slate-600 hover:text-primary hover:bg-primary/5 font-semibold"
                                                                onClick={() => setPersonalizationOpen(true)}
                                                                icon={Type}
                                                            >
                                                                Personalize
                                                            </GhostButton>
                                                        </div>
                                                    </div>
                                                    <SettingInput
                                                        label="Email Subject"
                                                        value={formData.email_subject}
                                                        onChange={(val) => updateField('email_subject', val)}
                                                        placeholder="Enter campaign subject line..."
                                                        icon={MailIcon}
                                                        labelHidden
                                                    />
                                                </div>

                                                <div className="space-y-2">
                                                    <Label className="text-xs font-bold text-gray-500 uppercase tracking-widest text-left">Select Email Template <span className="text-red-500">*</span></Label>
                                                    <SearchableSelect
                                                        value={formData.email_template_id}
                                                        onChange={(val) => setFormData((prev: CampaignFormData) => ({ ...prev, email_template_id: val }))}
                                                        placeholder="Select a template..."
                                                        searchPlaceholder="Search email templates..."
                                                        options={meta.email_templates.map((t: { id: string, name: string }) => ({ value: t.id, label: t.name }))}
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {formData.message_type === 'media' && (
                                    <div className="space-y-4 bg-gray-50/50 p-6 rounded-xl border border-dashed border-gray-200">
                                        <Label className="text-base font-bold">WhatsApp Media URL <span className="text-red-500">*</span></Label>
                                        <div className="flex gap-3">
                                            <SettingInput
                                                label="WhatsApp Media URL"
                                                value={formData.media_url}
                                                onChange={(val) => updateField('media_url', val)}
                                                placeholder="https://your-site.com/image.jpg"
                                                className="flex-1"
                                                icon={ImageIcon}
                                                labelHidden
                                            />
                                            <SecondaryButton onClick={() => { }} className="font-bold">Select Media</SecondaryButton>
                                        </div>
                                    </div>
                                )}

                                {formData.message_type === 'wp_post' && (
                                    <div className="space-y-6 bg-gray-50/50 p-6 rounded-xl border border-gray-200">
                                        <div className="space-y-4">
                                            <Label className="text-base font-bold">Select Post/Page <span className="text-red-500">*</span></Label>
                                            <SearchableSelect
                                                value={formData.share_post_id}
                                                onChange={(val) => setFormData((prev: CampaignFormData) => ({ ...prev, share_post_id: val }))}
                                                placeholder="Choose a post or page..."
                                                searchPlaceholder="Search posts/pages..."
                                                options={meta.posts.map((p: { id: string, label: string }) => ({ value: p.id, label: p.label }))}
                                            />
                                        </div>
                                        <div className="bg-white p-5 rounded-lg border border-gray-200 space-y-5">
                                            <div className="flex items-center gap-3">
                                                <Checkbox checked={Number(formData.append_post) === 1} onCheckedChange={(val) => updateField('append_post', val ? 1 : 0)} />
                                                <Label className="font-bold">Append post info to message text?</Label>
                                            </div>
                                            <div className="grid grid-cols-2 gap-4 pl-8">
                                                {['title', 'excerpt', 'link', 'image'].map(f => (
                                                    <div key={f} className="flex items-center gap-2">
                                                        <Checkbox checked={formData.post_info?.[f] === 1} onCheckedChange={(val) => updateField('post_info', { ...formData.post_info, [f]: val ? 1 : 0 })} />
                                                        <span className="text-sm capitalize">{f}</span>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {formData.message_type === 'woo_product' && (
                                    <div className="space-y-6 bg-gray-50/50 p-6 rounded-xl border border-gray-200">
                                        <div className="space-y-4">
                                            <Label className="text-base font-bold">Select Product <span className="text-red-500">*</span></Label>
                                            <SearchableSelect
                                                value={formData.share_product_id}
                                                onChange={(val: string) => updateField('share_product_id', val)}
                                                placeholder="Choose a product..."
                                                searchPlaceholder="Search products..."
                                                options={meta.products.map((p: { id: string, label: string }) => ({ value: p.id, label: p.label }))}
                                            />
                                        </div>
                                        <div className="bg-white p-5 rounded-lg border border-gray-200 space-y-5">
                                            <div className="flex items-center gap-3">
                                                <Checkbox checked={Number(formData.append_product) === 1} onCheckedChange={(val) => updateField('append_product', val ? 1 : 0)} />
                                                <Label className="font-bold">Append product info to message text?</Label>
                                            </div>
                                            <div className="grid grid-cols-2 gap-4 pl-8">
                                                {['title', 'price', 'description', 'link', 'image'].map(f => (
                                                    <div key={f} className="flex items-center gap-2">
                                                        <Checkbox checked={formData.product_info?.[f] === 1} onCheckedChange={(val) => updateField('product_info', { ...formData.product_info, [f]: val ? 1 : 0 })} />
                                                        <span className="text-sm capitalize">{f}</span>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}

                        {currentStep === 4 && (
                            <div className="space-y-8 animate-in fade-in text-left">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                    <div className="space-y-6 p-6 rounded-lg border bg-slate-50/30">
                                        <label className="text-lg font-bold text-green-800 flex items-center gap-2 mb-2"><Zap className="w-4 h-4" /> WhatsApp Scheduling</label>
                                        <div className="grid grid-cols-2 gap-4">
                                            <SettingInput
                                                label="Min Interval (s)"
                                                type="number"
                                                value={String(formData.min_whatsapp_interval)}
                                                onChange={(val) => updateField('min_whatsapp_interval', val)}
                                            />
                                            <SettingInput
                                                label="Max Interval (s)"
                                                type="number"
                                                value={String(formData.max_whatsapp_interval)}
                                                onChange={(val) => updateField('max_whatsapp_interval', val)}
                                            />
                                        </div>
                                        <SettingInput
                                            label="Daily Send Limit"
                                            type="number"
                                            value={String(formData.wa_daily_limit)}
                                            onChange={(val) => updateField('wa_daily_limit', val)}
                                        />
                                    </div>
                                    <div className="space-y-6 p-6 rounded-lg border bg-slate-50/30">
                                        <label className="text-lg font-bold text-blue-800 flex items-center gap-2 mb-2"><MailIcon className="w-4 h-4" /> Email Scheduling</label>
                                        <div className="grid grid-cols-2 gap-4">
                                            <SettingInput
                                                label="Min Interval (s)"
                                                type="number"
                                                value={String(formData.min_email_interval)}
                                                onChange={(val) => updateField('min_email_interval', val)}
                                            />
                                            <SettingInput
                                                label="Max Interval (s)"
                                                type="number"
                                                value={String(formData.max_email_interval)}
                                                onChange={(val) => updateField('max_email_interval', val)}
                                            />
                                        </div>
                                        <SettingInput
                                            label="Daily Send Limit"
                                            type="number"
                                            value={String(formData.email_daily_limit)}
                                            onChange={(val) => updateField('email_daily_limit', val)}
                                        />
                                    </div>
                                </div>
                                <div className="p-6 rounded-lg border bg-slate-50/30 space-y-6">
                                    <Label className="text-lg font-bold">Common Scheduling</Label>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                        <div className="space-y-2">
                                            <SettingInput
                                                label="Schedule Start"
                                                type="datetime-local"
                                                value={formData.start_datetime}
                                                onChange={(val) => updateField('start_datetime', val)}
                                                icon={Clock}
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <SearchableSelect
                                                value={formData.repeat_campaign}
                                                onChange={(val: string) => updateField('repeat_campaign', val)}
                                                placeholder="Select Repeat Schedule..."
                                                searchPlaceholder="Search frequency..."
                                                options={[
                                                    { value: 'no_repeat', label: 'No Repeat' },
                                                    { value: 'daily', label: 'Daily' },
                                                    { value: 'weekly', label: 'Weekly' },
                                                    { value: 'monthly', label: 'Monthly' },
                                                    { value: 'custom', label: 'Custom Interval' }
                                                ]}
                                            />
                                            {formData.repeat_campaign === 'custom' && (
                                                <div className="flex items-center gap-3 mt-4 animate-in slide-in-from-top-2">
                                                    <SettingInput
                                                        label="Repeat Every (Days)"
                                                        type="number"
                                                        value={String(formData.repeat_days)}
                                                        onChange={(val) => updateField('repeat_days', val)}
                                                        className="w-40"
                                                    />
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                        {currentStep === 5 && (
                            <div className="space-y-8 animate-in fade-in text-left">
                                <div className="text-center space-y-4">
                                    <div className="w-20 h-20 bg-green-50 text-green-500 rounded-full flex items-center justify-center mx-auto mb-4 border-4 border-green-100">
                                        <CheckCircle2 className="w-10 h-10" />
                                    </div>
                                    <h3 className="text-2xl font-bold text-gray-900 leading-tight">Campaign Ready!</h3>
                                    <p className="text-gray-500 max-w-md mx-auto">Please review your settings before launching.</p>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-8 bg-slate-50/50 p-8 rounded-2xl border border-slate-100 shadow-sm">
                                    {/* Audience */}
                                    <div className="space-y-4">
                                        <h4 className="text-sm font-extrabold uppercase tracking-widest text-slate-500 flex items-center gap-2 border-b border-slate-200 pb-2"><Users className="w-4 h-4 text-primary" /> Audience</h4>
                                        <div className="space-y-2.5 text-sm">
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Roles:</span> <span className="font-bold text-slate-900">{Array.isArray(formData.role_ids) && formData.role_ids.length ? (formData.role_ids as string[]).map((id: string) => meta.roles.find(r => String(r.id) === String(id))?.label || id).join(', ') : 'ALL / Global'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Users:</span> <span className="font-bold text-slate-900">{Array.isArray(formData.user_ids) && formData.user_ids.length ? (formData.user_ids as string[]).map((id: string) => meta.users.find(u => String(u.id) === String(id))?.label || id).join(', ') : 'ALL / Global'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Recipients:</span> <span className="font-bold text-primary">{isCalculating ? 'Calculating...' : recipientCount === -1 ? '0 / Error (-1)' : recipientCount !== null ? recipientCount : 'Estimating...'}</span></div>
                                        </div>
                                    </div>

                                    {/* Segmentation & Filters */}
                                    <div className="space-y-4">
                                        <h4 className="text-sm font-extrabold uppercase tracking-widest text-slate-500 flex items-center gap-2 border-b border-slate-200 pb-2"><Rocket className="w-4 h-4 text-orange-500" /> Segmentation & Filters</h4>
                                        <div className="space-y-2.5 text-sm">
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Countries:</span> <span className="font-bold text-slate-900">{Array.isArray(formData.billing_countries) && formData.billing_countries.length ? (formData.billing_countries as string[]).map((c: string) => meta.woo_countries[c] || c).join(', ') : 'ALL / Global'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Languages:</span> <span className="font-bold text-slate-900">{Array.isArray(formData.wp_profile_languages) && formData.wp_profile_languages.length ? formData.wp_profile_languages.join(', ') : 'ALL / Global'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Min. Total Spent:</span> <span className="font-bold text-slate-900">{Number(formData.total_spent_min) > 0 ? formData.total_spent_min : 'Any Amount'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Min. Order Count:</span> <span className="font-bold text-slate-900">{Number(formData.orders_count_min) > 0 ? formData.orders_count_min : 'Any Count'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Purchased Products:</span> <span className="font-bold text-slate-900">{Array.isArray(formData.woo_ordered_products) && formData.woo_ordered_products.length ? (formData.woo_ordered_products as string[]).map((id: string) => meta.products.find(p => String(p.id) === String(id))?.label || id).join(', ') : 'ALL / Global'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Filter Statuses:</span> <span className="font-bold text-slate-900">{Array.isArray(formData.woo_order_statuses) && formData.woo_order_statuses.length ? formData.woo_order_statuses.join(', ') : 'ALL / Global'}</span></div>
                                        </div>
                                    </div>

                                    {/* Content */}
                                    <div className="space-y-4">
                                        <h4 className="text-sm font-extrabold uppercase tracking-widest text-slate-500 flex items-center gap-2 border-b border-slate-200 pb-2"><Type className="w-4 h-4 text-blue-500" /> Content</h4>
                                        <div className="space-y-2.5 text-sm">
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Strategy:</span> <span className="font-bold text-slate-900">
                                                {formData.message_type === 'text' ? 'Standard Text' :
                                                    formData.message_type === 'wp_post' ? 'Share WP Post' :
                                                        formData.message_type === 'woo_product' ? 'Share WooCommerce Product' :
                                                            formData.message_type === 'media' ? 'Media Message' : formData.message_type}
                                            </span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Campaign Name:</span> <span className="text-gray-900 font-semibold">{(formData.name as string || '').substring(0, 30)}{(formData.name as string || '').length > 30 ? '...' : ''}</span></div>
                                            {formData.message_type === 'woo_product' && <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Shared Product:</span> <span className="font-bold text-slate-900">{meta.products.find(p => p.id == formData.share_product_id)?.label || formData.share_product_id || 'None selected'}</span></div>}
                                            {formData.message_type === 'wp_post' && <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Shared Post:</span> <span className="font-bold text-slate-900">{meta.posts.find(p => p.id == formData.share_post_id)?.label || formData.share_post_id || 'None selected'}</span></div>}
                                        </div>
                                    </div>

                                    {/* Scheduling & Timing */}
                                    <div className="space-y-4">
                                        <h4 className="text-sm font-extrabold uppercase tracking-widest text-slate-500 flex items-center gap-2 border-b border-slate-200 pb-2"><Clock className="w-4 h-4 text-purple-500" /> Scheduling & Timing</h4>
                                        <div className="space-y-2.5 text-sm">
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Start Date:</span> <span className="font-bold text-slate-900">{formData.start_datetime ? new Date(formData.start_datetime).toLocaleString() : 'ASAP'}</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Interval:</span> <span className="font-bold text-slate-900">{formData.min_whatsapp_interval}-{formData.max_whatsapp_interval}s</span></div>
                                            <div className="grid grid-cols-[160px_1fr] gap-2"><span className="text-slate-500 font-semibold">Repeat Pattern:</span> <span className="font-bold text-slate-900 capitalize">
                                                {formData.repeat_campaign === 'no_repeat' || !formData.repeat_campaign ? 'No Repeat' : formData.repeat_campaign.toString().replace('_', ' ')}
                                            </span></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </motion.div>
                </AnimatePresence>
            </div>

            <div className="bg-gray-50 border-t border-gray-200 p-6 flex items-center justify-between">
                <GhostButton onClick={handleBack} disabled={currentStep === 0} className="font-bold" icon={ChevronLeft}>
                    Back
                </GhostButton>
                <div className="flex items-center gap-3">
                    <SecondaryButton onClick={onCancel} className="font-bold">Cancel</SecondaryButton>
                    {currentStep === steps.length - 1 ? (
                        <AdminButton onClick={() => onSave(formData)} className="text-white font-bold px-8" icon={Send}>
                            Launch Campaign
                        </AdminButton>
                    ) : (
                        <AdminButton onClick={handleNext} className="text-white font-bold px-8">
                            Next Step <ChevronRight className="w-4 h-4 ml-2" />
                        </AdminButton>
                    )}
                </div>
            </div>
        </SettingCard>
    )
}
