import React, { useEffect, useMemo, useState } from 'react';

type FollowUpRecord = {
    id: string;
    title: string;
    description: string | null;
    priority: string;
    dueAt: string | null;
    assignee: string;
    state: 'overdue' | 'upcoming';
};

type FollowUpBootstrap = {
    companyName: string;
    queueEndpoint: string;
    campaignPreviewEndpoint: string;
    campaignSendEndpoint: string;
    campaignsEndpoint: string;
    campaignApproveBase: string;
    dashboardUrl: string;
    csrfToken: string;
};

type CampaignRecipient = {
    contactId: string;
    name: string;
    phone: string | null;
    instagramHandle: string | null;
    channel: string;
    conversationId: string;
    lastInteractionAt: string | null;
    lastOrderAt: string | null;
    reasons: string[];
};

type CampaignPreviewResponse = {
    summary: {
        totalRecipients: number;
    };
    applied: {
        conditions: string[];
        channel: string;
        inactive_days: number;
        no_purchase_days: number;
        unread_hours: number;
        cooldown_hours: number;
        max_touches_30_days: number;
        limit: number;
    };
    recipients: CampaignRecipient[];
    recommendedPlaybooks: Array<{
        key: string;
        title: string;
        why: string;
    }>;
};

type CampaignHistoryRow = {
    id: string;
    name: string;
    status: string;
    channel: string;
    isAutoEnabled: boolean;
    frequency: string | null;
    requiresApproval: boolean;
    nextRunAt: string | null;
    lastRunAt: string | null;
    lastSentCount: number;
    totalSentCount: number;
    repliedCount: number;
    convertedCount: number;
    replyRate: number;
    conversionRate: number;
    createdBy: string | null;
    approvedBy: string | null;
    approvedAt: string | null;
    createdAt: string | null;
};

type CampaignAnalyticsSummary = {
    totalCampaigns: number;
    totalSent: number;
    totalReplied: number;
    totalConverted: number;
    replyRate: number;
    conversionRate: number;
    pendingApproval: number;
    scheduledCount: number;
};

export function FollowUpQueueWorkspace({ bootstrap }: { bootstrap: FollowUpBootstrap }) {
    const [items, setItems] = useState<FollowUpRecord[]>([]);
    const [loading, setLoading] = useState(true);
    const [previewLoading, setPreviewLoading] = useState(false);
    const [sending, setSending] = useState(false);
    const [campaignError, setCampaignError] = useState<string | null>(null);
    const [campaignNotice, setCampaignNotice] = useState<string | null>(null);
    const [campaigns, setCampaigns] = useState<CampaignHistoryRow[]>([]);
    const [analyticsSummary, setAnalyticsSummary] = useState<CampaignAnalyticsSummary>({
        totalCampaigns: 0,
        totalSent: 0,
        totalReplied: 0,
        totalConverted: 0,
        replyRate: 0,
        conversionRate: 0,
        pendingApproval: 0,
        scheduledCount: 0,
    });
    const [rangeType, setRangeType] = useState<'7' | '30' | '90' | 'custom'>('30');
    const [customStartDate, setCustomStartDate] = useState('');
    const [customEndDate, setCustomEndDate] = useState('');
    const [confirmSend, setConfirmSend] = useState(false);
    const [preview, setPreview] = useState<CampaignPreviewResponse | null>(null);
    const [selectedRecipientIds, setSelectedRecipientIds] = useState<Record<string, boolean>>({});
    const [filters, setFilters] = useState({
        conditions: ['asked_no_purchase_7_days', 'unread_no_reply_24h'],
        channel: 'all',
        inactive_days: 90,
        no_purchase_days: 7,
        unread_hours: 24,
        cooldown_hours: 72,
        max_touches_30_days: 3,
        limit: 200,
    });
    const [campaignName, setCampaignName] = useState('Weekly Smart Follow-up');
    const [schedule, setSchedule] = useState({
        is_auto_enabled: false,
        frequency: 'daily',
        requires_approval: true,
    });
    const [messageTemplate, setMessageTemplate] = useState(
        'Hi {name}, this is a quick follow-up from {company}. We have a special offer this week and can help you complete your order today. Reply here and we will assist you immediately.'
    );

    useEffect(() => {
        async function loadQueue() {
            const response = await fetch(bootstrap.queueEndpoint, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            });

            const json = await response.json();
            setItems(json.data ?? []);
            setLoading(false);
        }

        void loadQueue();
    }, [bootstrap.queueEndpoint]);

    useEffect(() => {
        void loadCampaigns();
    }, [bootstrap.campaignsEndpoint, rangeType, customStartDate, customEndDate]);

    async function loadCampaigns() {
        const params = new URLSearchParams();
        if (rangeType === 'custom' && customStartDate && customEndDate) {
            params.set('start_date', customStartDate);
            params.set('end_date', customEndDate);
        } else {
            params.set('range_days', rangeType === 'custom' ? '30' : rangeType);
        }

        const query = params.toString();
        const response = await fetch(query ? `${bootstrap.campaignsEndpoint}?${query}` : bootstrap.campaignsEndpoint, {
            credentials: 'same-origin',
            headers: { Accept: 'application/json' },
        });
        const json = await response.json();
        setCampaigns(json.data ?? []);
        setAnalyticsSummary(json.meta?.summary ?? {
            totalCampaigns: 0,
            totalSent: 0,
            totalReplied: 0,
            totalConverted: 0,
            replyRate: 0,
            conversionRate: 0,
            pendingApproval: 0,
            scheduledCount: 0,
        });
    }

    const selectedCount = useMemo(
        () => Object.values(selectedRecipientIds).filter(Boolean).length,
        [selectedRecipientIds]
    );

    function toggleCondition(condition: string) {
        setFilters((current) => {
            const exists = current.conditions.includes(condition);
            const next = exists
                ? current.conditions.filter((item) => item !== condition)
                : [...current.conditions, condition];
            return { ...current, conditions: next };
        });
    }

    function applyPlaybook(key: string) {
        if (key === 'asked_no_purchase_7_days') {
            setFilters((current) => ({ ...current, conditions: Array.from(new Set([...current.conditions, 'asked_no_purchase_7_days'])) }));
            return;
        }
        if (key === 'unread_no_reply_24h') {
            setFilters((current) => ({ ...current, conditions: Array.from(new Set([...current.conditions, 'unread_no_reply_24h'])) }));
            return;
        }
        if (key === 'inactive_90_days') {
            setFilters((current) => ({ ...current, conditions: Array.from(new Set([...current.conditions, 'inactive_90_days'])) }));
        }
    }

    async function runPreview() {
        if (filters.conditions.length === 0) {
            setCampaignError('Select at least one condition.');
            return;
        }

        setPreviewLoading(true);
        setCampaignError(null);
        setCampaignNotice(null);
        setConfirmSend(false);
        try {
            const response = await fetch(bootstrap.campaignPreviewEndpoint, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify(filters),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not preview campaign recipients.');
            }
            setPreview(json.data as CampaignPreviewResponse);

            const allSelected: Record<string, boolean> = {};
            (json.data.recipients as CampaignRecipient[]).forEach((recipient) => {
                allSelected[recipient.contactId] = true;
            });
            setSelectedRecipientIds(allSelected);
        } catch (error) {
            setCampaignError(error instanceof Error ? error.message : 'Could not preview campaign recipients.');
        } finally {
            setPreviewLoading(false);
        }
    }

    async function sendCampaign() {
        if (!preview) {
            setCampaignError('Run preview first.');
            return;
        }
        if (!confirmSend) {
            setCampaignError('Please confirm sending before continuing.');
            return;
        }

        const ids = Object.keys(selectedRecipientIds).filter((id) => selectedRecipientIds[id]);
        if (ids.length === 0) {
            setCampaignError('Select at least one recipient.');
            return;
        }

        setSending(true);
        setCampaignError(null);
        setCampaignNotice(null);
        try {
            const response = await fetch(bootstrap.campaignSendEndpoint, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({
                    confirm: true,
                    message_template: messageTemplate,
                    filters: preview.applied,
                    recipient_ids: ids,
                }),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not send campaign.');
            }
            setCampaignNotice(`Campaign sent successfully. Messages created: ${json.data.sent}, skipped: ${json.data.skipped}.`);
            setConfirmSend(false);
            await runPreview();
            await loadCampaigns();
        } catch (error) {
            setCampaignError(error instanceof Error ? error.message : 'Could not send campaign.');
        } finally {
            setSending(false);
        }
    }

    async function saveCampaign() {
        if (!preview) {
            setCampaignError('Run preview first so conditions are validated.');
            return;
        }
        setSending(true);
        setCampaignError(null);
        setCampaignNotice(null);
        try {
            const response = await fetch(bootstrap.campaignsEndpoint, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({
                    name: campaignName,
                    message_template: messageTemplate,
                    filters: preview.applied,
                    schedule,
                }),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not save campaign.');
            }
            setCampaignNotice(`Campaign "${json.data.name}" saved (${json.data.status}).`);
            await loadCampaigns();
        } catch (error) {
            setCampaignError(error instanceof Error ? error.message : 'Could not save campaign.');
        } finally {
            setSending(false);
        }
    }

    async function approveCampaign(campaignId: string) {
        setSending(true);
        setCampaignError(null);
        try {
            const response = await fetch(`${bootstrap.campaignApproveBase}/${campaignId}/approve`, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({ run_now: true }),
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message || 'Could not approve campaign.');
            }
            setCampaignNotice('Campaign approved and executed.');
            await Promise.all([loadCampaigns(), runPreview()]);
        } catch (error) {
            setCampaignError(error instanceof Error ? error.message : 'Could not approve campaign.');
        } finally {
            setSending(false);
        }
    }

    return (
        <div className="space-y-6">
            <section className="rounded-[30px] border border-slate-200/80 bg-white p-8 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Follow-up queue</p>
                <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">Records requiring action</h2>
                <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">
                    This queue highlights open tasks that need action soon or are already overdue, helping managers and agents stay on top of follow-up discipline.
                </p>
                <div className="mt-4 rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
                    AI Sales Copilot is available on <a className="font-semibold underline" href={bootstrap.dashboardUrl}>Dashboard</a>. Use this page for smart follow-up campaigns.
                </div>
            </section>

            <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="flex flex-wrap items-start justify-between gap-4">
                    <div>
                        <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Smart campaign assistant</p>
                        <h3 className="mt-2 text-2xl font-semibold tracking-tight text-slate-950">Pick conditions and confirm before sending</h3>
                        <p className="mt-2 max-w-3xl text-sm leading-7 text-slate-600">
                            Best-performing sales follow-up on WhatsApp and Instagram usually targets warm leads first, then unread conversations, then win-back segments.
                        </p>
                    </div>
                    <button
                        type="button"
                        onClick={runPreview}
                        disabled={previewLoading}
                        className="rounded-2xl bg-slate-950 px-5 py-3 text-sm font-semibold text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-400"
                    >
                        {previewLoading ? 'Analyzing audience...' : 'Preview audience'}
                    </button>
                </div>

                <div className="mt-5 grid gap-4 lg:grid-cols-3">
                    <label className="space-y-2 rounded-2xl border border-slate-200 p-4">
                        <span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Channel</span>
                        <select
                            value={filters.channel}
                            onChange={(event) => setFilters((current) => ({ ...current, channel: event.target.value }))}
                            className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                        >
                            <option value="all">All channels</option>
                            <option value="whatsapp">WhatsApp only</option>
                            <option value="instagram">Instagram only</option>
                        </select>
                    </label>
                    <label className="space-y-2 rounded-2xl border border-slate-200 p-4">
                        <span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Inactive days</span>
                        <input
                            type="number"
                            min={30}
                            max={365}
                            value={filters.inactive_days}
                            onChange={(event) => setFilters((current) => ({ ...current, inactive_days: Number(event.target.value) }))}
                            className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                        />
                    </label>
                    <label className="space-y-2 rounded-2xl border border-slate-200 p-4">
                        <span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">No purchase days</span>
                        <input
                            type="number"
                            min={1}
                            max={90}
                            value={filters.no_purchase_days}
                            onChange={(event) => setFilters((current) => ({ ...current, no_purchase_days: Number(event.target.value) }))}
                            className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                        />
                    </label>
                </div>

                <div className="mt-4 grid gap-4 lg:grid-cols-2">
                    <label className="space-y-2 rounded-2xl border border-slate-200 p-4">
                        <span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Do not message if contacted in last (hours)</span>
                        <input
                            type="number"
                            min={0}
                            max={720}
                            value={filters.cooldown_hours}
                            onChange={(event) => setFilters((current) => ({ ...current, cooldown_hours: Number(event.target.value) }))}
                            className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                        />
                    </label>
                    <label className="space-y-2 rounded-2xl border border-slate-200 p-4">
                        <span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Max campaign touches per 30 days</span>
                        <input
                            type="number"
                            min={0}
                            max={20}
                            value={filters.max_touches_30_days}
                            onChange={(event) => setFilters((current) => ({ ...current, max_touches_30_days: Number(event.target.value) }))}
                            className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                        />
                    </label>
                </div>

                <div className="mt-4 grid gap-3 md:grid-cols-3">
                    <label className="flex items-start gap-3 rounded-2xl border border-slate-200 p-4 text-sm">
                        <input
                            type="checkbox"
                            checked={filters.conditions.includes('asked_no_purchase_7_days')}
                            onChange={() => toggleCondition('asked_no_purchase_7_days')}
                            className="mt-0.5"
                        />
                        <span>
                            <span className="font-semibold text-slate-900">Asked but no purchase</span>
                            <span className="mt-1 block text-slate-600">Great warm lead segment for quick conversion campaigns.</span>
                        </span>
                    </label>
                    <label className="flex items-start gap-3 rounded-2xl border border-slate-200 p-4 text-sm">
                        <input
                            type="checkbox"
                            checked={filters.conditions.includes('unread_no_reply_24h')}
                            onChange={() => toggleCondition('unread_no_reply_24h')}
                            className="mt-0.5"
                        />
                        <span>
                            <span className="font-semibold text-slate-900">Unread no reply</span>
                            <span className="mt-1 block text-slate-600">Recover dropped conversations quickly (high impact).</span>
                        </span>
                    </label>
                    <label className="flex items-start gap-3 rounded-2xl border border-slate-200 p-4 text-sm">
                        <input
                            type="checkbox"
                            checked={filters.conditions.includes('inactive_90_days')}
                            onChange={() => toggleCondition('inactive_90_days')}
                            className="mt-0.5"
                        />
                        <span>
                            <span className="font-semibold text-slate-900">Inactive customers</span>
                            <span className="mt-1 block text-slate-600">Win-back list for offers after long inactivity.</span>
                        </span>
                    </label>
                </div>

                <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 p-4">
                    <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Message template</p>
                    <p className="mt-1 text-xs text-slate-500">Use placeholders: <code>{'{name}'}</code> and <code>{'{company}'}</code>.</p>
                    <textarea
                        value={messageTemplate}
                        onChange={(event) => setMessageTemplate(event.target.value)}
                        className="mt-3 min-h-[120px] w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                    />
                </div>

                <div className="mt-4 rounded-2xl border border-slate-200 p-4">
                    <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Schedule & approval queue</p>
                    <div className="mt-3 grid gap-3 lg:grid-cols-2">
                        <label className="space-y-2">
                            <span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Campaign name</span>
                            <input
                                value={campaignName}
                                onChange={(event) => setCampaignName(event.target.value)}
                                className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                            />
                        </label>
                        <label className="space-y-2">
                            <span className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Frequency</span>
                            <select
                                value={schedule.frequency}
                                onChange={(event) => setSchedule((current) => ({ ...current, frequency: event.target.value }))}
                                className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                            >
                                <option value="daily">Daily</option>
                                <option value="weekly">Weekly</option>
                            </select>
                        </label>
                    </div>
                    <div className="mt-3 grid gap-2 md:grid-cols-2">
                        <label className="flex items-center gap-2 rounded-xl border border-slate-200 px-3 py-2 text-sm">
                            <input
                                type="checkbox"
                                checked={schedule.is_auto_enabled}
                                onChange={(event) => setSchedule((current) => ({ ...current, is_auto_enabled: event.target.checked }))}
                            />
                            Enable scheduled auto campaign
                        </label>
                        <label className="flex items-center gap-2 rounded-xl border border-slate-200 px-3 py-2 text-sm">
                            <input
                                type="checkbox"
                                checked={schedule.requires_approval}
                                onChange={(event) => setSchedule((current) => ({ ...current, requires_approval: event.target.checked }))}
                            />
                            Require approval before each run
                        </label>
                    </div>
                </div>

                {preview?.recommendedPlaybooks?.length ? (
                    <div className="mt-4 grid gap-3 md:grid-cols-3">
                        {preview.recommendedPlaybooks.map((playbook) => (
                            <button
                                key={playbook.key}
                                type="button"
                                onClick={() => applyPlaybook(playbook.key)}
                                className="rounded-2xl border border-blue-200 bg-blue-50 p-4 text-left text-sm hover:bg-blue-100"
                            >
                                <p className="font-semibold text-slate-900">{playbook.title}</p>
                                <p className="mt-1 text-slate-600">{playbook.why}</p>
                            </button>
                        ))}
                    </div>
                ) : null}

                {campaignError ? (
                    <div className="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{campaignError}</div>
                ) : null}
                {campaignNotice ? (
                    <div className="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">{campaignNotice}</div>
                ) : null}

                {preview ? (
                    <div className="mt-5 space-y-4">
                        <div className="flex flex-wrap items-center justify-between gap-3">
                            <p className="text-sm font-semibold text-slate-900">
                                Recipient preview: {preview.summary.totalRecipients} contacts
                            </p>
                            <div className="flex items-center gap-2">
                                <button
                                    type="button"
                                    onClick={() => {
                                        const all: Record<string, boolean> = {};
                                        preview.recipients.forEach((r) => { all[r.contactId] = true; });
                                        setSelectedRecipientIds(all);
                                    }}
                                    className="rounded-xl border border-slate-300 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                >
                                    Select all
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setSelectedRecipientIds({})}
                                    className="rounded-xl border border-slate-300 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                >
                                    Clear
                                </button>
                            </div>
                        </div>

                        <div className="max-h-[340px] space-y-2 overflow-auto rounded-2xl border border-slate-200 bg-slate-50 p-3">
                            {preview.recipients.map((recipient) => (
                                <label key={recipient.contactId} className="flex items-start gap-3 rounded-xl border border-slate-200 bg-white p-3 text-sm">
                                    <input
                                        type="checkbox"
                                        checked={Boolean(selectedRecipientIds[recipient.contactId])}
                                        onChange={(event) => setSelectedRecipientIds((current) => ({ ...current, [recipient.contactId]: event.target.checked }))}
                                        className="mt-1"
                                    />
                                    <span>
                                        <span className="font-semibold text-slate-900">{recipient.name}</span>
                                        <span className="ml-2 rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600">{recipient.channel}</span>
                                        <span className="mt-1 block text-slate-600">{recipient.phone || recipient.instagramHandle || 'No direct contact shown'}</span>
                                        <span className="mt-1 block text-xs text-slate-500">{recipient.reasons.join(' · ')}</span>
                                    </span>
                                </label>
                            ))}
                        </div>

                        <label className="flex items-center gap-2 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
                            <input type="checkbox" checked={confirmSend} onChange={(event) => setConfirmSend(event.target.checked)} />
                            I confirm sending this campaign to selected recipients ({selectedCount}).
                        </label>

                        <div className="flex flex-wrap items-center gap-3">
                            <button
                                type="button"
                                onClick={sendCampaign}
                                disabled={sending || !confirmSend || selectedCount === 0}
                                className="rounded-2xl bg-emerald-500 px-5 py-3 text-sm font-semibold text-slate-950 hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-300"
                            >
                                {sending ? 'Sending campaign...' : 'Confirm and send campaign'}
                            </button>
                            <button
                                type="button"
                                onClick={saveCampaign}
                                disabled={sending || !preview}
                                className="rounded-2xl border border-slate-300 px-5 py-3 text-sm font-semibold text-slate-800 hover:bg-slate-50 disabled:cursor-not-allowed disabled:bg-slate-200"
                            >
                                Save as reusable campaign
                            </button>
                            <p className="text-xs text-slate-500">Messages are created as outbound conversation replies for auditability.</p>
                        </div>
                    </div>
                ) : null}
            </section>

            <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="flex items-center justify-between gap-3">
                    <div>
                        <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Campaign analytics</p>
                        <h3 className="mt-2 text-2xl font-semibold tracking-tight text-slate-950">Runs, replies, conversions, and performance rate</h3>
                    </div>
                    <button
                        type="button"
                        onClick={loadCampaigns}
                        className="rounded-xl border border-slate-300 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                    >
                        Refresh
                    </button>
                </div>

                <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 p-4">
                    <div className="flex flex-wrap items-center gap-2">
                        <button
                            type="button"
                            onClick={() => setRangeType('7')}
                            className={`rounded-xl px-3 py-2 text-xs font-semibold ${rangeType === '7' ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-700 hover:bg-white'}`}
                        >
                            Last 7 days
                        </button>
                        <button
                            type="button"
                            onClick={() => setRangeType('30')}
                            className={`rounded-xl px-3 py-2 text-xs font-semibold ${rangeType === '30' ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-700 hover:bg-white'}`}
                        >
                            Last 30 days
                        </button>
                        <button
                            type="button"
                            onClick={() => setRangeType('90')}
                            className={`rounded-xl px-3 py-2 text-xs font-semibold ${rangeType === '90' ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-700 hover:bg-white'}`}
                        >
                            Last 90 days
                        </button>
                        <button
                            type="button"
                            onClick={() => setRangeType('custom')}
                            className={`rounded-xl px-3 py-2 text-xs font-semibold ${rangeType === 'custom' ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-700 hover:bg-white'}`}
                        >
                            Custom range
                        </button>
                    </div>
                    {rangeType === 'custom' ? (
                        <div className="mt-3 grid gap-3 md:grid-cols-3">
                            <label className="space-y-1 text-xs text-slate-600">
                                <span className="font-semibold uppercase tracking-[0.16em]">Start date</span>
                                <input
                                    type="date"
                                    value={customStartDate}
                                    onChange={(event) => setCustomStartDate(event.target.value)}
                                    className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                                />
                            </label>
                            <label className="space-y-1 text-xs text-slate-600">
                                <span className="font-semibold uppercase tracking-[0.16em]">End date</span>
                                <input
                                    type="date"
                                    value={customEndDate}
                                    onChange={(event) => setCustomEndDate(event.target.value)}
                                    className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
                                />
                            </label>
                            <div className="flex items-end">
                                <button
                                    type="button"
                                    onClick={loadCampaigns}
                                    disabled={!customStartDate || !customEndDate}
                                    className="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-white disabled:cursor-not-allowed disabled:bg-slate-200"
                                >
                                    Apply date filter
                                </button>
                            </div>
                        </div>
                    ) : null}
                </div>

                <div className="mt-4 grid gap-3 md:grid-cols-4">
                    <div className="rounded-2xl border border-slate-200 bg-white p-4">
                        <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Total sent</p>
                        <p className="mt-2 text-2xl font-semibold text-slate-950">{analyticsSummary.totalSent}</p>
                    </div>
                    <div className="rounded-2xl border border-slate-200 bg-white p-4">
                        <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Reply rate</p>
                        <p className="mt-2 text-2xl font-semibold text-slate-950">{analyticsSummary.replyRate}%</p>
                    </div>
                    <div className="rounded-2xl border border-slate-200 bg-white p-4">
                        <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Conversion rate</p>
                        <p className="mt-2 text-2xl font-semibold text-slate-950">{analyticsSummary.conversionRate}%</p>
                    </div>
                    <div className="rounded-2xl border border-slate-200 bg-white p-4">
                        <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Pending approval</p>
                        <p className="mt-2 text-2xl font-semibold text-slate-950">{analyticsSummary.pendingApproval}</p>
                    </div>
                </div>

                <div className="mt-4 space-y-2">
                    {campaigns.length === 0 ? (
                        <p className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-3 text-sm text-slate-600">No campaigns yet.</p>
                    ) : null}
                    {campaigns.map((campaign) => (
                        <div key={campaign.id} className="rounded-2xl border border-slate-200 p-4">
                            <div className="flex flex-wrap items-center justify-between gap-3">
                                <p className="font-semibold text-slate-900">{campaign.name}</p>
                                <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{campaign.status}</span>
                            </div>
                            <div className="mt-2 grid gap-2 text-xs text-slate-600 md:grid-cols-4">
                                <p>Sent total: <span className="font-semibold text-slate-900">{campaign.totalSentCount}</span></p>
                                <p>Replied: <span className="font-semibold text-slate-900">{campaign.repliedCount}</span></p>
                                <p>Converted: <span className="font-semibold text-slate-900">{campaign.convertedCount}</span></p>
                                <p>Next run: <span className="font-semibold text-slate-900">{campaign.nextRunAt ?? '-'}</span></p>
                            </div>
                            <div className="mt-2 grid gap-2 text-xs text-slate-600 md:grid-cols-3">
                                <p>Reply rate: <span className="font-semibold text-slate-900">{campaign.replyRate}%</span></p>
                                <p>Conversion rate: <span className="font-semibold text-slate-900">{campaign.conversionRate}%</span></p>
                                <p>Frequency: <span className="font-semibold text-slate-900">{campaign.frequency ?? '-'}</span></p>
                            </div>
                            {campaign.status === 'pending_approval' ? (
                                <button
                                    type="button"
                                    onClick={() => approveCampaign(campaign.id)}
                                    className="mt-3 rounded-xl bg-amber-400 px-3 py-2 text-xs font-semibold text-slate-900 hover:bg-amber-300"
                                >
                                    Approve and run now
                                </button>
                            ) : null}
                        </div>
                    ))}
                </div>
            </section>

            <section className="space-y-4">
                {loading ? (
                    <div className="rounded-[28px] border border-slate-200/80 bg-white p-5 text-sm text-slate-500 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                        Loading follow-up queue...
                    </div>
                ) : null}

                {items.map((item) => (
                    <div key={item.id} className="rounded-[28px] border border-slate-200/80 bg-white p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                        <div className="flex flex-wrap items-start justify-between gap-4">
                            <div>
                                <p className="text-lg font-semibold text-slate-950">{item.title}</p>
                                <p className="mt-2 text-sm leading-6 text-slate-500">{item.description ?? 'No description'}</p>
                            </div>

                            <div className="flex flex-wrap gap-2">
                                <span className={`rounded-full px-3 py-1 text-xs font-semibold ${item.state === 'overdue' ? 'bg-rose-100 text-rose-700' : 'bg-blue-100 text-blue-700'}`}>
                                    {item.state}
                                </span>
                                <span className="rounded-full bg-amber-100 px-3 py-1 text-xs font-semibold text-amber-700">
                                    {item.priority}
                                </span>
                            </div>
                        </div>

                        <div className="mt-4 grid gap-3 text-sm text-slate-600 sm:grid-cols-2">
                            <p><span className="font-semibold text-slate-900">Assignee:</span> {item.assignee}</p>
                            <p><span className="font-semibold text-slate-900">Due:</span> {item.dueAt ?? 'No due date'}</p>
                        </div>
                    </div>
                ))}
            </section>
        </div>
    );
}

export type { FollowUpBootstrap };
