// settings/EmailCampaigns.tsx
import { useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
    Mail,
    Plus,
    Loader2,
    Trash2,
    Edit2,
    Play,
    Pause,
    Users,
    Send,
    CheckCircle2,
    XCircle,
    Clock,
    AlertCircle,
    Eye,
    Search,
    Filter,
    Copy,
    BarChart3,
    Zap,
    ChevronDown,
    MoreHorizontal,
    RefreshCw,
    Calendar,
    FileText,
    Target,
    TrendingUp,
} from 'lucide-react';

import {
    useCampaigns,
    useCreateCampaign,
    useUpdateCampaign,
    useDeleteCampaign,
    usePopulateCampaignRecipients,
    useStartCampaign,
    useSendCampaignBatch,
    Campaign,
    CampaignInsert,
} from '@/hooks/useCampaigns';

import { useTags } from '@/hooks/useContactTags';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';

import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';

import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Checkbox } from '@/components/ui/checkbox';
import { Separator } from '@/components/ui/separator';
import { ScrollArea } from '@/components/ui/scroll-area';

import { toast } from 'sonner';
import { formatDistanceToNow } from 'date-fns';
import { cn } from '@/lib/utils';

const CONTACT_STATUSES = ['lead', 'prospect', 'customer', 'churned'] as const;

const PERSONALIZATION_TOKENS = [
    { token: '{{first_name}}', label: 'First Name' },
    { token: '{{last_name}}', label: 'Last Name' },
    { token: '{{email}}', label: 'Email' },
    { token: '{{company}}', label: 'Company' },
];

type StatusFilter = 'all' | Campaign['status'];

type BusyActionKind = 'populate' | 'start' | 'send' | 'pause' | 'delete' | null;

export default function EmailCampaigns() {
    const { data: campaigns = [], isLoading, isFetching, refetch } = useCampaigns();
    const { data: tags = [] } = useTags();

    const createCampaign = useCreateCampaign();
    const updateCampaign = useUpdateCampaign();
    const deleteCampaign = useDeleteCampaign();
    const populateRecipients = usePopulateCampaignRecipients();
    const startCampaign = useStartCampaign();
    const sendBatch = useSendCampaignBatch();

    const [busyAction, setBusyAction] = useState<{ kind: BusyActionKind; campaignId?: string }>({
        kind: null,
        campaignId: undefined,
    });

    const isBusy = (kind: Exclude<BusyActionKind, null>, campaignId: string) =>
        busyAction.kind === kind && busyAction.campaignId === campaignId;

    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingCampaign, setEditingCampaign] = useState<Campaign | null>(null);
    const [previewCampaign, setPreviewCampaign] = useState<Campaign | null>(null);
    const [deleteConfirm, setDeleteConfirm] = useState<Campaign | null>(null);
    const [sendConfirm, setSendConfirm] = useState<Campaign | null>(null);

    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
    const [activeTab, setActiveTab] = useState('content');

    const [formData, setFormData] = useState<
        CampaignInsert & { selectedTags: string[]; selectedStatuses: string[] }
    >({
        name: '',
        subject: '',
        html_body: '',
        text_body: '',
        batch_size: 50,
        selectedTags: [],
        selectedStatuses: [],
    });

    const [formErrors, setFormErrors] = useState<Record<string, string>>({});

    const stats = useMemo(() => {
        const total = campaigns.length;
        const active = campaigns.filter((c) => c.status === 'active').length;

        const totalSent = campaigns.reduce((sum, c) => sum + (c.sent_count || 0), 0);
        const totalRecipients = campaigns.reduce((sum, c) => sum + (c.total_recipients || 0), 0);

        const avgDeliveryRate =
            totalRecipients > 0 ? Math.round((totalSent / totalRecipients) * 100) : 0;

        return { total, active, totalSent, avgDeliveryRate };
    }, [campaigns]);

    const campaignsByStatus = useMemo(() => {
        return {
            draft: campaigns.filter((c) => c.status === 'draft').length,
            active: campaigns.filter((c) => c.status === 'active').length,
            paused: campaigns.filter((c) => c.status === 'paused').length,
            completed: campaigns.filter((c) => c.status === 'completed').length,
        };
    }, [campaigns]);

    const filteredCampaigns = useMemo(() => {
        const q = searchQuery.trim().toLowerCase();

        return campaigns.filter((campaign) => {
            const matchesSearch =
                q === '' ||
                campaign.name.toLowerCase().includes(q) ||
                campaign.subject.toLowerCase().includes(q);

            const matchesStatus = statusFilter === 'all' || campaign.status === statusFilter;

            return matchesSearch && matchesStatus;
        });
    }, [campaigns, searchQuery, statusFilter]);

    const resetForm = () => {
        setFormData({
            name: '',
            subject: '',
            html_body: '',
            text_body: '',
            batch_size: 50,
            selectedTags: [],
            selectedStatuses: [],
        });
        setFormErrors({});
        setEditingCampaign(null);
        setActiveTab('content');
    };

    const openCreateDialog = () => {
        resetForm();
        setIsDialogOpen(true);
    };

    const openEditDialog = (campaign: Campaign) => {
        setEditingCampaign(campaign);
        setFormData({
            name: campaign.name,
            subject: campaign.subject,
            html_body: campaign.html_body,
            text_body: campaign.text_body || '',
            batch_size: campaign.batch_size,
            selectedTags: campaign.segment_tags || [],
            selectedStatuses: campaign.segment_status || [],
        });
        setFormErrors({});
        setActiveTab('content');
        setIsDialogOpen(true);
    };

    const duplicateCampaign = (campaign: Campaign) => {
        setEditingCampaign(null);
        setFormData({
            name: `${campaign.name} (Copy)`,
            subject: campaign.subject,
            html_body: campaign.html_body,
            text_body: campaign.text_body || '',
            batch_size: campaign.batch_size,
            selectedTags: campaign.segment_tags || [],
            selectedStatuses: campaign.segment_status || [],
        });
        setFormErrors({});
        setActiveTab('content');
        setIsDialogOpen(true);
    };

    const validateForm = () => {
        const errors: Record<string, string> = {};

        if (!formData.name.trim()) errors.name = 'Campaign name is required';
        if (!formData.subject.trim()) errors.subject = 'Email subject is required';
        if (!formData.html_body.trim()) errors.html_body = 'Email body is required';

        setFormErrors(errors);
        return Object.keys(errors).length === 0;
    };

    const handleSubmit = async () => {
        if (!validateForm()) {
            setActiveTab('content');
            toast.error('Please fix the errors before submitting');
            return;
        }

        const payload: CampaignInsert = {
            name: formData.name.trim(),
            subject: formData.subject.trim(),
            html_body: formData.html_body,
            text_body: formData.text_body?.trim() ? formData.text_body : undefined,
            batch_size: formData.batch_size,
            segment_tags: formData.selectedTags.length > 0 ? formData.selectedTags : undefined,
            segment_status: formData.selectedStatuses.length > 0 ? formData.selectedStatuses : undefined,
        };

        try {
            if (editingCampaign) {
                await updateCampaign.mutateAsync({ id: editingCampaign.id, ...payload });
            } else {
                await createCampaign.mutateAsync(payload);
            }

            setIsDialogOpen(false);
            resetForm();
        } catch {
            // Hooks already toast errors
        }
    };

    const handleDelete = async () => {
        if (!deleteConfirm) return;

        const id = deleteConfirm.id;
        setBusyAction({ kind: 'delete', campaignId: id });

        try {
            await deleteCampaign.mutateAsync(id);
        } finally {
            setBusyAction({ kind: null, campaignId: undefined });
            setDeleteConfirm(null);
        }
    };

    const handlePopulateRecipients = async (campaign: Campaign) => {
        setBusyAction({ kind: 'populate', campaignId: campaign.id });

        try {
            await populateRecipients.mutateAsync({
                campaignId: campaign.id,
                tagIds: campaign.segment_tags || undefined,
                statuses: campaign.segment_status || undefined,
            });
        } finally {
            setBusyAction({ kind: null, campaignId: undefined });
        }
    };

    const handleStartCampaign = async (campaign: Campaign) => {
        setBusyAction({ kind: 'start', campaignId: campaign.id });

        try {
            await startCampaign.mutateAsync(campaign.id);
        } finally {
            setBusyAction({ kind: null, campaignId: undefined });
        }
    };

    const handleSendBatch = async () => {
        if (!sendConfirm) return;

        setBusyAction({ kind: 'send', campaignId: sendConfirm.id });

        try {
            await sendBatch.mutateAsync({
                campaignId: sendConfirm.id,
                batchSize: sendConfirm.batch_size,
            });
        } finally {
            setBusyAction({ kind: null, campaignId: undefined });
            setSendConfirm(null);
        }
    };

    const handlePauseCampaign = async (campaign: Campaign) => {
        setBusyAction({ kind: 'pause', campaignId: campaign.id });

        try {
            await updateCampaign.mutateAsync({ id: campaign.id, status: 'paused' });
        } finally {
            setBusyAction({ kind: null, campaignId: undefined });
        }
    };

    const insertToken = (token: string) => {
        setFormData((prev) => ({
            ...prev,
            html_body: prev.html_body + token,
        }));
    };

    const toggleTag = (tagId: string) => {
        setFormData((prev) => ({
            ...prev,
            selectedTags: prev.selectedTags.includes(tagId)
                ? prev.selectedTags.filter((t) => t !== tagId)
                : [...prev.selectedTags, tagId],
        }));
    };

    const toggleStatus = (status: string) => {
        setFormData((prev) => ({
            ...prev,
            selectedStatuses: prev.selectedStatuses.includes(status)
                ? prev.selectedStatuses.filter((s) => s !== status)
                : [...prev.selectedStatuses, status],
        }));
    };

    const getStatusConfig = (status: Campaign['status']) => {
        const configs = {
            draft: {
                color: 'bg-slate-100 text-slate-700 border-slate-200',
                icon: Edit2,
                description: 'Not yet started',
            },
            active: {
                color: 'bg-emerald-100 text-emerald-700 border-emerald-200',
                icon: Play,
                description: 'Currently sending',
            },
            paused: {
                color: 'bg-amber-100 text-amber-700 border-amber-200',
                icon: Pause,
                description: 'Temporarily stopped',
            },
            completed: {
                color: 'bg-blue-100 text-blue-700 border-blue-200',
                icon: CheckCircle2,
                description: 'All emails sent',
            },
            cancelled: {
                color: 'bg-red-100 text-red-700 border-red-200',
                icon: XCircle,
                description: 'Campaign cancelled',
            },
        } as const;

        return configs[status];
    };

    const getProgress = (campaign: Campaign) => {
        if (!campaign.total_recipients) return 0;
        const done = (campaign.sent_count || 0) + (campaign.failed_count || 0) + (campaign.skipped_count || 0);
        return (done / campaign.total_recipients) * 100;
    };

    const getPendingCount = (campaign: Campaign) => {
        return (
            (campaign.total_recipients || 0) -
            (campaign.sent_count || 0) -
            (campaign.failed_count || 0) -
            (campaign.skipped_count || 0)
        );
    };

    if (isLoading) {
        return (
            <div className="flex flex-col items-center justify-center h-[60vh] gap-4">
                <div className="relative">
                    <div className="absolute inset-0 rounded-full bg-primary/20 animate-ping" />
                    <div className="relative rounded-full bg-primary/10 p-4">
                        <Mail className="h-8 w-8 text-primary animate-pulse" />
                    </div>
                </div>
                <p className="text-muted-foreground animate-pulse">Loading campaigns...</p>
            </div>
        );
    }

    return (
        <TooltipProvider>
            <div className="p-6 space-y-6 max-w-7xl mx-auto">
                {/* Header */}
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                    <div>
                        <h1 className="text-3xl font-bold tracking-tight bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">
                            Email Campaigns
                        </h1>
                        <p className="text-muted-foreground mt-1">
                            Create, manage, and track your email marketing campaigns
                        </p>
                    </div>

                    <div className="flex items-center gap-2">
                        <Button variant="outline" size="sm" onClick={() => refetch()} disabled={isFetching}>
                            <RefreshCw className={cn("h-4 w-4 mr-2", isFetching && "animate-spin")} />
                            Refresh
                        </Button>
                        <Button onClick={openCreateDialog} className="shadow-lg shadow-primary/25">
                            <Plus className="mr-2 h-4 w-4" />
                            New Campaign
                        </Button>
                    </div>
                </div>

                {/* Stats */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <Card className="relative overflow-hidden">
                        <div className="absolute top-0 right-0 w-20 h-20 bg-gradient-to-br from-blue-500/10 to-transparent rounded-bl-full" />
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 rounded-lg bg-blue-100">
                                    <FileText className="h-5 w-5 text-blue-600" />
                                </div>
                                <div>
                                    <p className="text-2xl font-bold">{stats.total}</p>
                                    <p className="text-xs text-muted-foreground">Total Campaigns</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="relative overflow-hidden">
                        <div className="absolute top-0 right-0 w-20 h-20 bg-gradient-to-br from-emerald-500/10 to-transparent rounded-bl-full" />
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 rounded-lg bg-emerald-100">
                                    <Zap className="h-5 w-5 text-emerald-600" />
                                </div>
                                <div>
                                    <p className="text-2xl font-bold">{stats.active}</p>
                                    <p className="text-xs text-muted-foreground">Active Now</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="relative overflow-hidden">
                        <div className="absolute top-0 right-0 w-20 h-20 bg-gradient-to-br from-violet-500/10 to-transparent rounded-bl-full" />
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 rounded-lg bg-violet-100">
                                    <Send className="h-5 w-5 text-violet-600" />
                                </div>
                                <div>
                                    <p className="text-2xl font-bold">{stats.totalSent.toLocaleString()}</p>
                                    <p className="text-xs text-muted-foreground">Emails Sent</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="relative overflow-hidden">
                        <div className="absolute top-0 right-0 w-20 h-20 bg-gradient-to-br from-amber-500/10 to-transparent rounded-bl-full" />
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className="p-2 rounded-lg bg-amber-100">
                                    <TrendingUp className="h-5 w-5 text-amber-600" />
                                </div>
                                <div>
                                    <p className="text-2xl font-bold">{stats.avgDeliveryRate}%</p>
                                    <p className="text-xs text-muted-foreground">Delivery Rate</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* Filters */}
                <Card>
                    <CardContent className="py-4">
                        <div className="flex flex-col sm:flex-row gap-4">
                            <div className="relative flex-1">
                                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                                <Input
                                    placeholder="Search campaigns..."
                                    value={searchQuery}
                                    onChange={(e) => setSearchQuery(e.target.value)}
                                    className="pl-9"
                                />
                            </div>

                            <div className="flex gap-2 flex-wrap">
                                <Button
                                    variant={statusFilter === 'all' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setStatusFilter('all')}
                                >
                                    All ({campaigns.length})
                                </Button>

                                <Button
                                    variant={statusFilter === 'draft' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setStatusFilter('draft')}
                                >
                                    Draft ({campaignsByStatus.draft})
                                </Button>

                                <Button
                                    variant={statusFilter === 'active' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setStatusFilter('active')}
                                    className={statusFilter === 'active' ? 'bg-emerald-600 hover:bg-emerald-700' : ''}
                                >
                                    Active ({campaignsByStatus.active})
                                </Button>

                                <Button
                                    variant={statusFilter === 'paused' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setStatusFilter('paused')}
                                >
                                    Paused ({campaignsByStatus.paused})
                                </Button>

                                <Button
                                    variant={statusFilter === 'completed' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setStatusFilter('completed')}
                                >
                                    Completed ({campaignsByStatus.completed})
                                </Button>
                            </div>
                        </div>
                    </CardContent>
                </Card>

                {/* Campaigns List */}
                <AnimatePresence mode="wait">
                    {filteredCampaigns.length === 0 ? (
                        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }}>
                            <Card className="border-dashed">
                                <CardContent className="py-16 text-center">
                                    <div className="mx-auto w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">
                                        <Mail className="h-8 w-8 text-muted-foreground" />
                                    </div>

                                    {searchQuery || statusFilter !== 'all' ? (
                                        <>
                                            <h3 className="font-semibold mb-1">No campaigns found</h3>
                                            <p className="text-muted-foreground text-sm mb-4">
                                                Try adjusting your search or filter criteria
                                            </p>
                                            <Button
                                                variant="outline"
                                                onClick={() => {
                                                    setSearchQuery('');
                                                    setStatusFilter('all');
                                                }}
                                            >
                                                Clear Filters
                                            </Button>
                                        </>
                                    ) : (
                                        <>
                                            <h3 className="font-semibold mb-1">No campaigns yet</h3>
                                            <p className="text-muted-foreground text-sm mb-4">
                                                Create your first email campaign to get started
                                            </p>
                                            <Button onClick={openCreateDialog}>
                                                <Plus className="mr-2 h-4 w-4" />
                                                Create Campaign
                                            </Button>
                                        </>
                                    )}
                                </CardContent>
                            </Card>
                        </motion.div>
                    ) : (
                        <div className="space-y-3">
                            {filteredCampaigns.map((campaign, index) => {
                                const statusConfig = getStatusConfig(campaign.status);
                                const StatusIcon = statusConfig.icon;
                                const progress = getProgress(campaign);
                                const pendingCount = getPendingCount(campaign);

                                return (
                                    <motion.div
                                        key={campaign.id}
                                        initial={{ opacity: 0, y: 20 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        exit={{ opacity: 0, y: -20 }}
                                        transition={{ delay: index * 0.03 }}
                                    >
                                        <Card
                                            className={cn(
                                                'transition-all duration-200 hover:shadow-lg group',
                                                campaign.status === 'active' && 'ring-2 ring-emerald-500/20'
                                            )}
                                        >
                                            <CardContent className="p-5">
                                                <div className="flex flex-col lg:flex-row lg:items-center gap-4">
                                                    {/* Main Info */}
                                                    <div className="flex-1 min-w-0">
                                                        <div className="flex items-start gap-3 mb-3">
                                                            <div
                                                                className={cn(
                                                                    'p-2 rounded-lg shrink-0 transition-colors',
                                                                    campaign.status === 'active' ? 'bg-emerald-100' : 'bg-muted'
                                                                )}
                                                            >
                                                                <Mail
                                                                    className={cn(
                                                                        'h-5 w-5',
                                                                        campaign.status === 'active'
                                                                            ? 'text-emerald-600'
                                                                            : 'text-muted-foreground'
                                                                    )}
                                                                />
                                                            </div>

                                                            <div className="flex-1 min-w-0">
                                                                <div className="flex items-center gap-2 flex-wrap">
                                                                    <h3 className="font-semibold truncate">{campaign.name}</h3>
                                                                    <Badge className={cn('border', statusConfig.color)}>
                                                                        <StatusIcon className="h-3 w-3 mr-1" />
                                                                        {campaign.status}
                                                                    </Badge>
                                                                </div>
                                                                <p className="text-sm text-muted-foreground truncate mt-0.5">
                                                                    {campaign.subject}
                                                                </p>
                                                            </div>
                                                        </div>

                                                        {/* Stats Row */}
                                                        <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                    <span className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground transition-colors cursor-default">
                                                                        <Users className="h-4 w-4" />
                                                                        {campaign.total_recipients.toLocaleString()}
                                                                    </span>
                                                                </TooltipTrigger>
                                                                <TooltipContent>Total Recipients</TooltipContent>
                                                            </Tooltip>

                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                    <span className="flex items-center gap-1.5 text-emerald-600 cursor-default">
                                                                        <CheckCircle2 className="h-4 w-4" />
                                                                        {campaign.sent_count.toLocaleString()}
                                                                    </span>
                                                                </TooltipTrigger>
                                                                <TooltipContent>Sent Successfully</TooltipContent>
                                                            </Tooltip>

                                                            {campaign.failed_count > 0 && (
                                                                <Tooltip>
                                                                    <TooltipTrigger asChild>
                                                                        <span className="flex items-center gap-1.5 text-red-600 cursor-default">
                                                                            <XCircle className="h-4 w-4" />
                                                                            {campaign.failed_count.toLocaleString()}
                                                                        </span>
                                                                    </TooltipTrigger>
                                                                    <TooltipContent>Failed</TooltipContent>
                                                                </Tooltip>
                                                            )}

                                                            {campaign.skipped_count > 0 && (
                                                                <Tooltip>
                                                                    <TooltipTrigger asChild>
                                                                        <span className="flex items-center gap-1.5 text-amber-600 cursor-default">
                                                                            <AlertCircle className="h-4 w-4" />
                                                                            {campaign.skipped_count.toLocaleString()}
                                                                        </span>
                                                                    </TooltipTrigger>
                                                                    <TooltipContent>Skipped (suppressed)</TooltipContent>
                                                                </Tooltip>
                                                            )}

                                                            {pendingCount > 0 && campaign.status !== 'draft' && (
                                                                <Tooltip>
                                                                    <TooltipTrigger asChild>
                                                                        <span className="flex items-center gap-1.5 text-muted-foreground cursor-default">
                                                                            <Clock className="h-4 w-4" />
                                                                            {pendingCount.toLocaleString()} pending
                                                                        </span>
                                                                    </TooltipTrigger>
                                                                    <TooltipContent>Waiting to be sent</TooltipContent>
                                                                </Tooltip>
                                                            )}
                                                        </div>

                                                        {/* Progress Bar */}
                                                        {campaign.total_recipients > 0 && campaign.status !== 'draft' && (
                                                            <div className="mt-3">
                                                                <div className="flex items-center justify-between text-xs text-muted-foreground mb-1">
                                                                    <span>Progress</span>
                                                                    <span>{Math.round(progress)}%</span>
                                                                </div>
                                                                <Progress value={progress} className="h-1.5" />
                                                            </div>
                                                        )}

                                                        {campaign.last_batch_at && (
                                                            <p className="text-xs text-muted-foreground mt-2 flex items-center gap-1">
                                                                <Calendar className="h-3 w-3" />
                                                                Last batch:{' '}
                                                                {formatDistanceToNow(new Date(campaign.last_batch_at), { addSuffix: true })}
                                                            </p>
                                                        )}
                                                    </div>

                                                    {/* Actions */}
                                                    <div className="flex items-center gap-2 lg:flex-col lg:items-end">
                                                        {campaign.status === 'draft' && (
                                                            <div className="flex gap-2">
                                                                <Button
                                                                    variant="outline"
                                                                    size="sm"
                                                                    onClick={() => handlePopulateRecipients(campaign)}
                                                                    disabled={isBusy('populate', campaign.id)}
                                                                >
                                                                    {isBusy('populate', campaign.id) ? (
                                                                        <Loader2 className="h-4 w-4 animate-spin" />
                                                                    ) : (
                                                                        <>
                                                                            <Users className="h-4 w-4 mr-1.5" />
                                                                            Load Recipients
                                                                        </>
                                                                    )}
                                                                </Button>

                                                                <Button
                                                                    size="sm"
                                                                    onClick={() => handleStartCampaign(campaign)}
                                                                    disabled={campaign.total_recipients === 0 || isBusy('start', campaign.id)}
                                                                    className="bg-emerald-600 hover:bg-emerald-700"
                                                                >
                                                                    {isBusy('start', campaign.id) ? (
                                                                        <Loader2 className="h-4 w-4 animate-spin" />
                                                                    ) : (
                                                                        <>
                                                                            <Play className="h-4 w-4 mr-1.5" />
                                                                            Activate
                                                                        </>
                                                                    )}
                                                                </Button>
                                                            </div>
                                                        )}

                                                        {campaign.status === 'active' && (
                                                            <div className="flex gap-2">
                                                                <Button
                                                                    size="sm"
                                                                    onClick={() => setSendConfirm(campaign)}
                                                                    disabled={pendingCount === 0 || isBusy('send', campaign.id)}
                                                                    className="bg-primary"
                                                                >
                                                                    {isBusy('send', campaign.id) ? (
                                                                        <Loader2 className="h-4 w-4 animate-spin" />
                                                                    ) : (
                                                                        <>
                                                                            <Send className="h-4 w-4 mr-1.5" />
                                                                            Send Batch ({campaign.batch_size})
                                                                        </>
                                                                    )}
                                                                </Button>

                                                                <Button
                                                                    variant="outline"
                                                                    size="sm"
                                                                    onClick={() => handlePauseCampaign(campaign)}
                                                                    disabled={isBusy('pause', campaign.id)}
                                                                >
                                                                    {isBusy('pause', campaign.id) ? (
                                                                        <Loader2 className="h-4 w-4 animate-spin" />
                                                                    ) : (
                                                                        <>
                                                                            <Pause className="h-4 w-4 mr-1.5" />
                                                                            Pause
                                                                        </>
                                                                    )}
                                                                </Button>
                                                            </div>
                                                        )}

                                                        {campaign.status === 'paused' && (
                                                            <Button
                                                                size="sm"
                                                                onClick={() => handleStartCampaign(campaign)}
                                                                className="bg-emerald-600 hover:bg-emerald-700"
                                                                disabled={isBusy('start', campaign.id)}
                                                            >
                                                                {isBusy('start', campaign.id) ? (
                                                                    <Loader2 className="h-4 w-4 animate-spin" />
                                                                ) : (
                                                                    <>
                                                                        <Play className="h-4 w-4 mr-1.5" />
                                                                        Resume
                                                                    </>
                                                                )}
                                                            </Button>
                                                        )}

                                                        {/* More Actions Dropdown */}
                                                        <DropdownMenu>
                                                            <DropdownMenuTrigger asChild>
                                                                <Button variant="ghost" size="icon" className="h-8 w-8">
                                                                    <MoreHorizontal className="h-4 w-4" />
                                                                </Button>
                                                            </DropdownMenuTrigger>

                                                            <DropdownMenuContent align="end">
                                                                <DropdownMenuItem onClick={() => setPreviewCampaign(campaign)}>
                                                                    <Eye className="h-4 w-4 mr-2" />
                                                                    Preview Email
                                                                </DropdownMenuItem>

                                                                {campaign.status === 'draft' && (
                                                                    <DropdownMenuItem onClick={() => openEditDialog(campaign)}>
                                                                        <Edit2 className="h-4 w-4 mr-2" />
                                                                        Edit Campaign
                                                                    </DropdownMenuItem>
                                                                )}

                                                                <DropdownMenuItem onClick={() => duplicateCampaign(campaign)}>
                                                                    <Copy className="h-4 w-4 mr-2" />
                                                                    Duplicate
                                                                </DropdownMenuItem>

                                                                <DropdownMenuSeparator />

                                                                <DropdownMenuItem
                                                                    onClick={() => setDeleteConfirm(campaign)}
                                                                    disabled={campaign.status === 'active'}
                                                                    className="text-destructive focus:text-destructive"
                                                                >
                                                                    <Trash2 className="h-4 w-4 mr-2" />
                                                                    Delete
                                                                </DropdownMenuItem>
                                                            </DropdownMenuContent>
                                                        </DropdownMenu>
                                                    </div>
                                                </div>
                                            </CardContent>
                                        </Card>
                                    </motion.div>
                                );
                            })}
                        </div>
                    )}
                </AnimatePresence>

                {/* Create/Edit Dialog */}
                <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                    <DialogContent className="max-w-4xl max-h-[90vh] p-0 gap-0 overflow-hidden">
                        <DialogHeader className="px-6 py-4 border-b bg-muted/30">
                            <DialogTitle className="text-xl">
                                {editingCampaign ? 'Edit Campaign' : 'Create New Campaign'}
                            </DialogTitle>
                            <DialogDescription>
                                {editingCampaign ? 'Update your campaign details and settings' : 'Set up a new email campaign with recipient targeting'}
                            </DialogDescription>
                        </DialogHeader>

                        <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1">
                            <div className="px-6 pt-4 border-b">
                                <TabsList className="grid w-full max-w-md grid-cols-3">
                                    <TabsTrigger value="content" className="flex items-center gap-2">
                                        <FileText className="h-4 w-4" />
                                        Content
                                    </TabsTrigger>
                                    <TabsTrigger value="recipients" className="flex items-center gap-2">
                                        <Target className="h-4 w-4" />
                                        Recipients
                                    </TabsTrigger>
                                    <TabsTrigger value="settings" className="flex items-center gap-2">
                                        <BarChart3 className="h-4 w-4" />
                                        Settings
                                    </TabsTrigger>
                                </TabsList>
                            </div>

                            <ScrollArea className="h-[calc(90vh-220px)]">
                                <div className="p-6">
                                    <TabsContent value="content" className="mt-0 space-y-6">
                                        <div className="grid gap-6 md:grid-cols-2">
                                            <div className="space-y-2">
                                                <Label htmlFor="name">
                                                    Campaign Name <span className="text-destructive">*</span>
                                                </Label>
                                                <Input
                                                    id="name"
                                                    value={formData.name}
                                                    onChange={(e) => {
                                                        setFormData((prev) => ({ ...prev, name: e.target.value }));
                                                        if (formErrors.name) setFormErrors((prev) => ({ ...prev, name: '' }));
                                                    }}
                                                    placeholder="e.g., Spring Newsletter 2024"
                                                    className={cn(formErrors.name && 'border-destructive')}
                                                />
                                                {formErrors.name && <p className="text-xs text-destructive">{formErrors.name}</p>}
                                            </div>

                                            <div className="space-y-2">
                                                <Label htmlFor="subject">
                                                    Email Subject <span className="text-destructive">*</span>
                                                </Label>
                                                <Input
                                                    id="subject"
                                                    value={formData.subject}
                                                    onChange={(e) => {
                                                        setFormData((prev) => ({ ...prev, subject: e.target.value }));
                                                        if (formErrors.subject) setFormErrors((prev) => ({ ...prev, subject: '' }));
                                                    }}
                                                    placeholder="e.g., Check out our latest updates!"
                                                    className={cn(formErrors.subject && 'border-destructive')}
                                                />
                                                {formErrors.subject && <p className="text-xs text-destructive">{formErrors.subject}</p>}
                                            </div>
                                        </div>

                                        <div className="space-y-2">
                                            <div className="flex items-center justify-between">
                                                <Label htmlFor="html_body">
                                                    HTML Body <span className="text-destructive">*</span>
                                                </Label>

                                                <DropdownMenu>
                                                    <DropdownMenuTrigger asChild>
                                                        <Button variant="outline" size="sm">
                                                            <Zap className="h-3 w-3 mr-1.5" />
                                                            Insert Variable
                                                            <ChevronDown className="h-3 w-3 ml-1.5" />
                                                        </Button>
                                                    </DropdownMenuTrigger>
                                                    <DropdownMenuContent align="end">
                                                        {PERSONALIZATION_TOKENS.map(({ token, label }) => (
                                                            <DropdownMenuItem key={token} onClick={() => insertToken(token)}>
                                                                <code className="text-xs bg-muted px-1 py-0.5 rounded mr-2">{token}</code>
                                                                {label}
                                                            </DropdownMenuItem>
                                                        ))}
                                                    </DropdownMenuContent>
                                                </DropdownMenu>
                                            </div>

                                            <Textarea
                                                id="html_body"
                                                value={formData.html_body}
                                                onChange={(e) => {
                                                    setFormData((prev) => ({ ...prev, html_body: e.target.value }));
                                                    if (formErrors.html_body) setFormErrors((prev) => ({ ...prev, html_body: '' }));
                                                }}
                                                placeholder="<html><body><h1>Hello {{first_name}}!</h1><p>Your email content here...</p></body></html>"
                                                rows={12}
                                                className={cn('font-mono text-sm resize-none', formErrors.html_body && 'border-destructive')}
                                            />
                                            {formErrors.html_body && <p className="text-xs text-destructive">{formErrors.html_body}</p>}
                                        </div>

                                        <div className="space-y-2">
                                            <Label htmlFor="text_body">Plain Text Body (fallback)</Label>
                                            <Textarea
                                                id="text_body"
                                                value={formData.text_body}
                                                onChange={(e) => setFormData((prev) => ({ ...prev, text_body: e.target.value }))}
                                                placeholder="Hello {{first_name}}! Your email content here..."
                                                rows={5}
                                                className="resize-none"
                                            />
                                            <p className="text-xs text-muted-foreground">
                                                Used when the recipient&apos;s email client doesn&apos;t support HTML
                                            </p>
                                        </div>
                                    </TabsContent>

                                    <TabsContent value="recipients" className="mt-0 space-y-6">
                                        <Card>
                                            <CardHeader className="pb-3">
                                                <CardTitle className="text-base flex items-center gap-2">
                                                    <Filter className="h-4 w-4" />
                                                    Contact Status Filter
                                                </CardTitle>
                                                <CardDescription>Target contacts based on their status in your pipeline</CardDescription>
                                            </CardHeader>
                                            <CardContent>
                                                <div className="flex flex-wrap gap-3">
                                                    {CONTACT_STATUSES.map((status) => (
                                                        <label
                                                            key={status}
                                                            className={cn(
                                                                'flex items-center gap-2 px-4 py-2 rounded-lg border cursor-pointer transition-all',
                                                                formData.selectedStatuses.includes(status)
                                                                    ? 'border-primary bg-primary/5 text-primary'
                                                                    : 'border-input hover:bg-muted'
                                                            )}
                                                        >
                                                            <Checkbox
                                                                checked={formData.selectedStatuses.includes(status)}
                                                                onCheckedChange={() => toggleStatus(status)}
                                                            />
                                                            <span className="capitalize font-medium">{status}</span>
                                                        </label>
                                                    ))}
                                                </div>
                                                <p className="text-xs text-muted-foreground mt-3">
                                                    Leave all unchecked to include contacts of any status
                                                </p>
                                            </CardContent>
                                        </Card>

                                        <Card>
                                            <CardHeader className="pb-3">
                                                <CardTitle className="text-base flex items-center gap-2">
                                                    <Target className="h-4 w-4" />
                                                    Tag Filter
                                                </CardTitle>
                                                <CardDescription>
                                                    Target contacts with specific tags (contacts must have at least one selected tag)
                                                </CardDescription>
                                            </CardHeader>
                                            <CardContent>
                                                {tags.length === 0 ? (
                                                    <p className="text-sm text-muted-foreground py-4 text-center">
                                                        No tags available. Create tags in Contact Tags settings first.
                                                    </p>
                                                ) : (
                                                    <div className="flex flex-wrap gap-2">
                                                        {tags.map((tag) => (
                                                            <Badge
                                                                key={tag.id}
                                                                variant="outline"
                                                                className={cn(
                                                                    'cursor-pointer transition-all px-3 py-1.5 text-sm',
                                                                    formData.selectedTags.includes(tag.id) && 'ring-2 ring-offset-2'
                                                                )}
                                                                onClick={() => toggleTag(tag.id)}
                                                                style={{
                                                                    backgroundColor: formData.selectedTags.includes(tag.id)
                                                                        ? tag.color
                                                                        : 'transparent',
                                                                    borderColor: tag.color,
                                                                    color: formData.selectedTags.includes(tag.id) ? 'white' : 'inherit',
                                                                }}
                                                            >
                                                                {tag.name}
                                                            </Badge>
                                                        ))}
                                                    </div>
                                                )}
                                                <p className="text-xs text-muted-foreground mt-3">
                                                    Leave all unchecked to include all contacts regardless of tags
                                                </p>
                                            </CardContent>
                                        </Card>

                                        <Card className="bg-blue-50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-900">
                                            <CardContent className="py-4">
                                                <div className="flex gap-3">
                                                    <AlertCircle className="h-5 w-5 text-blue-600 shrink-0 mt-0.5" />
                                                    <div className="text-sm">
                                                        <p className="font-medium text-blue-900 dark:text-blue-100">
                                                            Automatic Suppression
                                                        </p>
                                                        <p className="text-blue-700 dark:text-blue-300 mt-1">
                                                            Contacts who have unsubscribed, bounced, or filed complaints will be
                                                            automatically excluded when you load recipients.
                                                        </p>
                                                    </div>
                                                </div>
                                            </CardContent>
                                        </Card>
                                    </TabsContent>

                                    <TabsContent value="settings" className="mt-0 space-y-6">
                                        <Card>
                                            <CardHeader className="pb-3">
                                                <CardTitle className="text-base">Batch Settings</CardTitle>
                                                <CardDescription>Control how many emails are sent in each batch</CardDescription>
                                            </CardHeader>
                                            <CardContent className="space-y-4">
                                                <div className="space-y-2">
                                                    <Label htmlFor="batch_size">Emails per Batch</Label>
                                                    <Select
                                                        value={String(formData.batch_size)}
                                                        onValueChange={(value) =>
                                                            setFormData((prev) => ({ ...prev, batch_size: Number(value) }))
                                                        }
                                                    >
                                                        <SelectTrigger id="batch_size">
                                                            <SelectValue />
                                                        </SelectTrigger>
                                                        <SelectContent>
                                                            <SelectItem value="10">10 emails</SelectItem>
                                                            <SelectItem value="25">25 emails</SelectItem>
                                                            <SelectItem value="50">50 emails (recommended)</SelectItem>
                                                            <SelectItem value="100">100 emails</SelectItem>
                                                            <SelectItem value="200">200 emails</SelectItem>
                                                        </SelectContent>
                                                    </Select>
                                                    <p className="text-xs text-muted-foreground">
                                                        Smaller batches help avoid rate limits and let you monitor deliverability.
                                                    </p>
                                                </div>
                                            </CardContent>
                                        </Card>

                                        <Card className="bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-900">
                                            <CardContent className="py-4">
                                                <div className="flex gap-3">
                                                    <Clock className="h-5 w-5 text-amber-600 shrink-0 mt-0.5" />
                                                    <div className="text-sm">
                                                        <p className="font-medium text-amber-900 dark:text-amber-100">
                                                            Manual Sending
                                                        </p>
                                                        <p className="text-amber-700 dark:text-amber-300 mt-1">
                                                            Each batch must be manually triggered by clicking “Send Batch”.
                                                            This gives you control over sending pace and timing.
                                                        </p>
                                                    </div>
                                                </div>
                                            </CardContent>
                                        </Card>
                                    </TabsContent>
                                </div>
                            </ScrollArea>
                        </Tabs>

                        <DialogFooter className="px-6 py-4 border-t bg-muted/30">
                            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                                Cancel
                            </Button>
                            <Button onClick={handleSubmit} disabled={createCampaign.isPending || updateCampaign.isPending}>
                                {(createCampaign.isPending || updateCampaign.isPending) && (
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                )}
                                {editingCampaign ? 'Save Changes' : 'Create Campaign'}
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>

                {/* Preview Dialog */}
                <Dialog open={!!previewCampaign} onOpenChange={() => setPreviewCampaign(null)}>
                    <DialogContent className="max-w-3xl max-h-[90vh]">
                        <DialogHeader>
                            <DialogTitle className="flex items-center gap-2">
                                <Eye className="h-5 w-5" />
                                Email Preview
                            </DialogTitle>
                            <DialogDescription>{previewCampaign?.name}</DialogDescription>
                        </DialogHeader>

                        <div className="space-y-4">
                            <div className="flex items-center gap-2 text-sm">
                                <span className="text-muted-foreground">Subject:</span>
                                <span className="font-medium">{previewCampaign?.subject}</span>
                            </div>

                            <Separator />

                            <div className="border rounded-lg overflow-hidden bg-white">
                                <div className="bg-muted px-4 py-2 border-b flex items-center gap-2">
                                    <div className="flex gap-1.5">
                                        <div className="w-3 h-3 rounded-full bg-red-400" />
                                        <div className="w-3 h-3 rounded-full bg-yellow-400" />
                                        <div className="w-3 h-3 rounded-full bg-green-400" />
                                    </div>
                                    <span className="text-xs text-muted-foreground ml-2">Email Preview</span>
                                </div>

                                <ScrollArea className="h-[400px]">
                                    <div
                                        className="p-6"
                                        dangerouslySetInnerHTML={{ __html: previewCampaign?.html_body || '' }}
                                    />
                                </ScrollArea>
                            </div>
                        </div>
                    </DialogContent>
                </Dialog>

                {/* Delete Confirmation */}
                <AlertDialog open={!!deleteConfirm} onOpenChange={() => setDeleteConfirm(null)}>
                    <AlertDialogContent>
                        <AlertDialogHeader>
                            <AlertDialogTitle>Delete Campaign</AlertDialogTitle>
                            <AlertDialogDescription>
                                Are you sure you want to delete “{deleteConfirm?.name}”? This will also remove all recipient records and cannot be undone.
                            </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                            <AlertDialogCancel>Cancel</AlertDialogCancel>
                            <AlertDialogAction
                                onClick={handleDelete}
                                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                                disabled={deleteConfirm ? isBusy('delete', deleteConfirm.id) : false}
                            >
                                {deleteConfirm && isBusy('delete', deleteConfirm.id) ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        Deleting…
                                    </>
                                ) : (
                                    'Delete Campaign'
                                )}
                            </AlertDialogAction>
                        </AlertDialogFooter>
                    </AlertDialogContent>
                </AlertDialog>

                {/* Send Batch Confirmation */}
                <AlertDialog open={!!sendConfirm} onOpenChange={() => setSendConfirm(null)}>
                    <AlertDialogContent>
                        <AlertDialogHeader>
                            <AlertDialogTitle className="flex items-center gap-2">
                                <Send className="h-5 w-5" />
                                Send Email Batch
                            </AlertDialogTitle>

                            {/* IMPORTANT: asChild avoids <p> nesting warnings */}
                            <AlertDialogDescription asChild>
                                <div className="space-y-3">
                                    <p>
                                        You’re about to send up to{' '}
                                        <strong>
                                            {sendConfirm
                                                ? Math.min(sendConfirm.batch_size, getPendingCount(sendConfirm)).toLocaleString()
                                                : 0}{' '}
                                            emails
                                        </strong>
                                        .
                                    </p>

                                    <div className="bg-muted rounded-lg p-3">
                                        <p className="font-medium">{sendConfirm?.name}</p>
                                        <p className="text-sm text-muted-foreground">{sendConfirm?.subject}</p>
                                    </div>

                                    <p>
                                        {sendConfirm ? getPendingCount(sendConfirm).toLocaleString() : 0} recipients are still waiting.
                                    </p>
                                </div>
                            </AlertDialogDescription>
                        </AlertDialogHeader>

                        <AlertDialogFooter>
                            <AlertDialogCancel>Cancel</AlertDialogCancel>
                            <AlertDialogAction
                                onClick={handleSendBatch}
                                disabled={sendConfirm ? isBusy('send', sendConfirm.id) : false}
                            >
                                {sendConfirm && isBusy('send', sendConfirm.id) ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        Sending…
                                    </>
                                ) : (
                                    <>
                                        <Send className="h-4 w-4 mr-2" />
                                        Send Batch
                                    </>
                                )}
                            </AlertDialogAction>
                        </AlertDialogFooter>
                    </AlertDialogContent>
                </AlertDialog>
            </div>
        </TooltipProvider>
    );
}