import React, { useEffect, useMemo, useRef, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { useDispatch, useSelector } from 'react-redux';
import { Modal, Drawer, TextInput, MultiSelect, Checkbox, SegmentedControl, Menu, Select, Loader, Tooltip } from '@mantine/core';
import { showNotification } from '@mantine/notifications';
import {
    IconWebhook, IconPlus, IconDots, IconSend, IconList, IconEdit, IconKey, IconTrash,
    IconAlertTriangle, IconCheck, IconArrowBarToRight, IconArrowBarRight, IconRefresh, IconChevronDown, IconChevronRight, IconHelpCircle,
} from '@tabler/icons-react';
import {
    fetchWebhookEvents, fetchWebhooks, createWebhook, updateWebhook, deleteWebhook,
    regenerateWebhookSecret, testWebhook, fetchWebhookDeliveries, retryWebhookDelivery,
    clearWebhookTest, clearWebhookDeliveries,
} from '../store/webhookSlice';
import { fetchAllProjects } from '../store/projectSlice';
import { T, formatTime, statusLabel, Badge, Btn, IconBtn, Alert, Code, FieldLabel, SwitchRow, ConfirmModal, CopyBox } from './webhookUi';
import WebhookGuideModal from './WebhookGuideModal';
import IncomingWebhooksPanel from './IncomingWebhooksPanel';
import { fetchIncomingWebhooks } from '../store/incomingWebhookSlice';

const MAX_ATTEMPTS = 5;
const PER_PAGE = 20;
const TEST_EVENT = 'webhook.test';

// Same list as WebhookSecurity::PUBLIC_TEST_HOSTS, so the warning shows while typing;
// the server repeats the check on save and returns it in `warnings`.
const PUBLIC_TEST_HOSTS = ['webhook.site', 'requestbin.com', 'requestbin.net', 'pipedream.net', 'beeceptor.com', 'hookbin.com', 'requestcatcher.com'];

const isTestService = (url) => {
    try {
        const host = new URL(url.trim()).hostname.toLowerCase();
        return PUBLIC_TEST_HOSTS.some(h => host === h || host.endsWith(`.${h}`));
    } catch (e) {
        return false;
    }
};

const groupLabel = (group) => ({
    task: __('Tasks', 'lazytasks-project-task-management'),
    comment: __('Comments', 'lazytasks-project-task-management'),
    project: __('Projects', 'lazytasks-project-task-management'),
}[group] || group);

// -----------------------------------------------------------------------------
// Form
// -----------------------------------------------------------------------------

const emptyForm = { name: '', endpoint_url: '', events: [], project_scope: 'all', project_ids: [], include_private: false, active: true };

function WebhookForm({ opened, webhook, onClose, onCreated }) {
    const dispatch = useDispatch();
    const { events: catalog, isSaving } = useSelector(s => s.settings.webhooks);
    const { projects } = useSelector(s => s.settings.project);

    const [form, setForm] = useState(emptyForm);
    const [errors, setErrors] = useState({});
    const nameRef = useRef(null);
    const urlRef = useRef(null);
    const eventsRef = useRef(null);
    const projectsRef = useRef(null);

    useEffect(() => {
        if (!opened) return;
        setErrors({});
        setForm(webhook ? {
            name: webhook.name,
            endpoint_url: webhook.endpoint_url,
            events: webhook.events,
            project_scope: webhook.project_scope,
            project_ids: webhook.project_ids.map(String),
            include_private: webhook.include_private,
            active: webhook.status === 'active',
        } : emptyForm);
    }, [opened, webhook]);

    const allScope = form.project_scope === 'all';
    const lockedKeys = useMemo(
        () => (allScope ? [] : catalog.filter(e => e.all_projects_only).map(e => e.key)),
        [catalog, allScope]
    );
    const usableKeys = catalog.map(e => e.key).filter(k => !lockedKeys.includes(k));
    const chosen = form.events.filter(k => usableKeys.includes(k));
    const groups = [...new Set(catalog.map(e => e.group))];
    const projectOptions = (projects || []).map(p => ({ value: String(p.id), label: p.name }));

    const set = (key, value) => {
        setForm(f => ({ ...f, [key]: value }));
        if (errors[key]) setErrors(e => ({ ...e, [key]: null }));
    };

    const toggleEvent = (key, on) => set('events', on ? [...new Set([...form.events, key])] : form.events.filter(k => k !== key));
    const allChosen = usableKeys.length > 0 && usableKeys.every(k => chosen.includes(k));

    const focusField = (field) => {
        const target = {
            name: nameRef.current,
            endpoint_url: urlRef.current,
            events: eventsRef.current?.querySelector('input:not(:disabled)'),
            project_ids: projectsRef.current,
            project_scope: projectsRef.current,
        }[field];
        target?.focus();
    };

    const validate = () => {
        const e = {};
        if (!form.name.trim()) e.name = __('Name is required.', 'lazytasks-project-task-management');
        const url = form.endpoint_url.trim();
        if (!url) e.endpoint_url = __('Endpoint URL is required.', 'lazytasks-project-task-management');
        if (!chosen.length) e.events = __('Choose at least one event.', 'lazytasks-project-task-management');
        if (!allScope && !form.project_ids.length) e.project_ids = __('Choose at least one project.', 'lazytasks-project-task-management');
        return e;
    };

    const submit = async () => {
        const local = validate();
        if (Object.keys(local).length) {
            setErrors(local);
            focusField(['name', 'endpoint_url', 'events', 'project_ids'].find(k => local[k]));
            return;
        }

        let status = form.active ? 'active' : 'inactive';
        // Leaving the switch off on an auto-disabled webhook keeps it disabled, so the
        // list still explains why it stopped.
        if (!form.active && webhook?.status === 'disabled') status = 'disabled';

        const data = {
            name: form.name.trim(),
            endpoint_url: form.endpoint_url.trim(),
            events: chosen,
            project_scope: form.project_scope,
            project_ids: allScope ? [] : form.project_ids.map(Number),
            include_private: form.include_private,
            status,
        };

        const res = webhook
            ? await dispatch(updateWebhook({ id: webhook.id, data })).unwrap()
            : await dispatch(createWebhook(data)).unwrap();

        if (res?.status !== 200) {
            // The interceptor has already shown the server's message; mark and focus the field.
            if (res?.field) {
                const field = res.field === 'project_scope' ? 'project_ids' : res.field;
                setErrors({ [field]: res.message });
                focusField(field);
            }
            return;
        }

        (res.warnings || []).forEach(w => showNotification({ title: __('Warning', 'lazytasks-project-task-management'), message: w, color: 'yellow' }));
        if (webhook) {
            showNotification({ title: __('Saved', 'lazytasks-project-task-management'), message: res.message, color: 'green' });
            onClose();
        } else {
            onCreated(res.data);
        }
    };

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={<span style={{ fontWeight: 700 }}>{webhook ? __('Edit webhook', 'lazytasks-project-task-management') : __('Add webhook', 'lazytasks-project-task-management')}</span>}
            centered
            size="lg"
        >
            <TextInput
                ref={nameRef}
                label={__('Name', 'lazytasks-project-task-management')}
                withAsterisk
                placeholder={__('e.g. Slack — #dev-updates', 'lazytasks-project-task-management')}
                maxLength={190}
                value={form.name}
                onChange={e => set('name', e.currentTarget.value)}
                error={errors.name}
                data-autofocus
                mb="md"
            />

            <TextInput
                ref={urlRef}
                label={__('Endpoint URL', 'lazytasks-project-task-management')}
                withAsterisk
                placeholder="https://"
                value={form.endpoint_url}
                onChange={e => set('endpoint_url', e.currentTarget.value)}
                error={errors.endpoint_url}
                description={__('Must start with https://. Addresses on a private network are not allowed.', 'lazytasks-project-task-management')}
                inputWrapperOrder={['label', 'input', 'description', 'error']}
                mb={isTestService(form.endpoint_url) ? 6 : 'md'}
            />
            {isTestService(form.endpoint_url) && (
                <Alert icon={<IconAlertTriangle size={14} />} style={{ fontSize: 12, marginBottom: 16 }}>
                    {__('This looks like a public test service. Anyone with the link can read what is sent there, including task titles, names and emails. Use it for testing only.', 'lazytasks-project-task-management')}
                </Alert>
            )}

            <FieldLabel>{__('Events', 'lazytasks-project-task-management')} <span style={{ color: T.danger }}>*</span></FieldLabel>
            <div ref={eventsRef} style={{ border: `1px solid ${errors.events ? T.danger : T.border}`, borderRadius: 8 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', borderBottom: `1px solid ${T.border}`, background: '#F8FAFC', fontSize: 12, color: T.muted, borderRadius: '8px 8px 0 0' }}>
                    <span>{sprintf(/* translators: 1: number of events selected, 2: number of events available */ __('%1$d of %2$d selected', 'lazytasks-project-task-management'), chosen.length, catalog.length)}</span>
                    <button
                        type="button"
                        onClick={() => set('events', allChosen ? [] : usableKeys)}
                        style={{ background: 'none', border: 'none', color: T.teal, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
                    >
                        {allChosen ? __('Clear all', 'lazytasks-project-task-management') : __('Select all', 'lazytasks-project-task-management')}
                    </button>
                </div>
                {groups.map((g, gi) => (
                    <div key={g} style={{ padding: '8px 12px', borderTop: gi ? `1px solid ${T.border}` : 'none' }}>
                        <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.4px', color: T.light, fontWeight: 600, marginBottom: 4 }}>{groupLabel(g)}</div>
                        {catalog.filter(e => e.group === g).map(e => {
                            const locked = lockedKeys.includes(e.key);
                            return (
                                <Checkbox
                                    key={e.key}
                                    color={T.teal}
                                    disabled={locked}
                                    checked={!locked && form.events.includes(e.key)}
                                    onChange={ev => toggleEvent(e.key, ev.currentTarget.checked)}
                                    styles={{ root: { padding: '5px 0' }, body: { alignItems: 'flex-start' }, label: { cursor: locked ? 'not-allowed' : 'pointer' } }}
                                    label={
                                        <div>
                                            <span style={{ fontSize: 13, fontWeight: 500 }}>{e.label}</span>
                                            <span style={{ fontFamily: T.mono, fontSize: 11, color: T.light, marginLeft: 6 }}>{e.key}</span>
                                            <div style={{ fontSize: 12, color: T.muted }}>{e.description}</div>
                                            {e.all_projects_only && !allScope && (
                                                <div style={{ fontSize: 11, color: T.warningDk }}>{__('Only available with All projects.', 'lazytasks-project-task-management')}</div>
                                            )}
                                        </div>
                                    }
                                />
                            );
                        })}
                    </div>
                ))}
            </div>
            {errors.events && <div style={{ fontSize: 12, color: T.dangerDk, marginTop: 4 }}>{errors.events}</div>}

            <FieldLabel style={{ marginTop: 16 }}>{__('Projects', 'lazytasks-project-task-management')}</FieldLabel>
            <SegmentedControl
                value={form.project_scope}
                onChange={v => { set('project_scope', v); setErrors(e => ({ ...e, project_ids: null })); }}
                color={T.teal}
                data={[
                    { value: 'all', label: __('All projects', 'lazytasks-project-task-management') },
                    { value: 'selected', label: __('Selected projects', 'lazytasks-project-task-management') },
                ]}
            />
            {!allScope && (
                <MultiSelect
                    ref={projectsRef}
                    mt={8}
                    data={projectOptions}
                    value={form.project_ids}
                    onChange={v => set('project_ids', v)}
                    placeholder={form.project_ids.length ? '' : __('Add project…', 'lazytasks-project-task-management')}
                    searchable
                    clearable
                    nothingFoundMessage={__('No projects found', 'lazytasks-project-task-management')}
                    error={errors.project_ids}
                    comboboxProps={{ withinPortal: true, zIndex: 1000 }}
                />
            )}
            <div style={{ fontSize: 12, color: T.muted, marginTop: 4, marginBottom: 12 }}>
                {allScope
                    ? __('Events from every project, including projects created later.', 'lazytasks-project-task-management')
                    : __('Events only from these projects. A task moved into or out of one of them is still sent.', 'lazytasks-project-task-management')}
            </div>

            <SwitchRow
                label={__('Include private tasks', 'lazytasks-project-task-management')}
                hint={__('Off: nothing is sent for private tasks, their subtasks or their comments.', 'lazytasks-project-task-management')}
                checked={form.include_private}
                onChange={v => set('include_private', v)}
            />
            <SwitchRow
                label={__('Active', 'lazytasks-project-task-management')}
                hint={webhook?.status === 'disabled'
                    ? __('This webhook was switched off after repeated failed deliveries. Fix the receiver, then switch it on.', 'lazytasks-project-task-management')
                    : __('Inactive webhooks send nothing. Waiting retries are cancelled.', 'lazytasks-project-task-management')}
                checked={form.active}
                onChange={v => set('active', v)}
            />

            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 16, paddingTop: 12, borderTop: `1px solid ${T.border}` }}>
                <Btn variant="default" onClick={onClose}>{__('Cancel', 'lazytasks-project-task-management')}</Btn>
                <Btn onClick={submit} loading={isSaving}>{webhook ? __('Save changes', 'lazytasks-project-task-management') : __('Create webhook', 'lazytasks-project-task-management')}</Btn>
            </div>
        </Modal>
    );
}

// -----------------------------------------------------------------------------
// Secret, confirm, test result
// -----------------------------------------------------------------------------

function SecretModal({ secret, title, onClose }) {
    return (
        <Modal opened={!!secret} onClose={onClose} title={<span style={{ fontWeight: 700 }}>{title}</span>} centered size="md" closeOnClickOutside={false}>
            <Alert icon={<IconAlertTriangle size={14} />} style={{ marginBottom: 14 }}>
                <b>{__('Copy this signing secret now.', 'lazytasks-project-task-management')}</b>{' '}
                {__('It will not be shown again. The receiving app uses it to check the X-LazyTasks-Signature header.', 'lazytasks-project-task-management')}
            </Alert>
            <CopyBox value={secret} failMessage={__('Select the secret and copy it by hand.', 'lazytasks-project-task-management')} />
            <div style={{ fontSize: 12, color: T.muted, marginTop: 10 }}>
                {__('Signature = HMAC-SHA256 of the timestamp, a dot and the raw body, sent as v1=<hex>.', 'lazytasks-project-task-management')}
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
                <Btn onClick={onClose}>{__("I've copied it", 'lazytasks-project-task-management')}</Btn>
            </div>
        </Modal>
    );
}

function TestModal({ webhook, onClose }) {
    const dispatch = useDispatch();
    const test = useSelector(s => s.settings.webhooks.test);
    const res = test.webhookId === webhook?.id ? test.response : null;
    const r = res?.status === 200 ? res.data : null;
    /* translators: %s: webhook name */
    const title = webhook ? sprintf(__('Send test — %s', 'lazytasks-project-task-management'), webhook.name) : '';

    return (
        <Modal
            opened={!!webhook}
            onClose={onClose}
            title={<span style={{ fontWeight: 700 }}>{title}</span>}
            centered
            size="lg"
        >
            {test.isSending && (
                <Alert tone="info" icon={<Loader size={12} color={T.infoDk} />} style={{ marginBottom: 12 }}>
                    {__('Sending a test message…', 'lazytasks-project-task-management')} <span style={{ fontFamily: T.mono, fontSize: 12 }}>{webhook?.endpoint_url}</span>
                </Alert>
            )}
            {!test.isSending && r && (
                <>
                    {r.success ? (
                        <Alert tone="ok" icon={<IconCheck size={14} />} style={{ marginBottom: 12 }}>
                            <b>{__('Delivered.', 'lazytasks-project-task-management')}</b>{' '}
                            {sprintf(/* translators: 1: HTTP status code, 2: duration in milliseconds */ __('The receiver answered HTTP %1$d in %2$d ms.', 'lazytasks-project-task-management'), r.response_code, r.duration_ms)}
                        </Alert>
                    ) : (
                        <Alert tone="bad" icon={<IconAlertTriangle size={14} />} style={{ marginBottom: 12 }}>
                            <b>{__('Not delivered.', 'lazytasks-project-task-management')}</b>{' '}
                            {r.response_code
                                ? sprintf(/* translators: %d: HTTP status code */ __('The receiver answered HTTP %d. Only 2xx answers count as delivered.', 'lazytasks-project-task-management'), r.response_code)
                                : r.error}
                        </Alert>
                    )}
                    <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '4px 12px', fontSize: 13, marginBottom: 12 }}>
                        <span style={{ color: T.muted }}>{__('Response code', 'lazytasks-project-task-management')}</span><span>{r.response_code ?? '—'}</span>
                        <span style={{ color: T.muted }}>{__('Time', 'lazytasks-project-task-management')}</span><span>{sprintf(/* translators: %d: duration in milliseconds */ __('%d ms', 'lazytasks-project-task-management'), r.duration_ms)}</span>
                        {r.error && r.response_code ? (<><span style={{ color: T.muted }}>{__('Error', 'lazytasks-project-task-management')}</span><span>{r.error}</span></>) : null}
                    </div>
                    <FieldLabel>{__('Response body', 'lazytasks-project-task-management')}</FieldLabel>
                    <Code>{r.response_body || '—'}</Code>
                    <div style={{ fontSize: 12, color: T.muted, marginTop: 8 }}>
                        {__('A test does not count toward the failure limit and works on inactive webhooks. The full message is in the delivery log.', 'lazytasks-project-task-management')}
                    </div>
                </>
            )}
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 16 }}>
                <Btn variant="default" onClick={onClose}>{__('Close', 'lazytasks-project-task-management')}</Btn>
                <Btn loading={test.isSending} onClick={() => dispatch(testWebhook(webhook.id))}><IconSend size={14} />{__('Send again', 'lazytasks-project-task-management')}</Btn>
            </div>
        </Modal>
    );
}

// -----------------------------------------------------------------------------
// Delivery log
// -----------------------------------------------------------------------------

function DeliveryLog({ webhook, onClose }) {
    const dispatch = useDispatch();
    const { deliveries, events: catalog } = useSelector(s => s.settings.webhooks);
    const [status, setStatus] = useState('');
    const [event, setEvent] = useState('');
    const [page, setPage] = useState(1);
    const [openRow, setOpenRow] = useState(null);
    const [resending, setResending] = useState(null);

    const load = (p = page) => {
        if (!webhook) return;
        const params = { page: p, per_page: PER_PAGE };
        if (status) params.status = status;
        if (event) params.event = event;
        dispatch(fetchWebhookDeliveries({ id: webhook.id, params }));
    };

    useEffect(() => {
        setStatus(''); setEvent(''); setPage(1); setOpenRow(null);
    }, [webhook?.id]);

    useEffect(() => { load(page); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [webhook?.id, status, event, page]);

    const label = (key) => key === TEST_EVENT ? __('Test message', 'lazytasks-project-task-management') : (catalog.find(e => e.key === key)?.label || key);
    const total = deliveries.meta?.total || 0;
    const pages = Math.max(1, Math.ceil(total / PER_PAGE));
    const items = deliveries.webhookId === webhook?.id ? deliveries.items : [];

    const resend = async (d) => {
        setResending(d.id);
        const res = await dispatch(retryWebhookDelivery({ id: webhook.id, deliveryId: d.id })).unwrap();
        setResending(null);
        if (res?.status !== 200) return;
        showNotification({
            title: res.data.success ? __('Delivered', 'lazytasks-project-task-management') : __('Not delivered', 'lazytasks-project-task-management'),
            message: res.data.response_code
                ? sprintf(/* translators: 1: result message, 2: HTTP status code */ __('%1$s HTTP %2$d.', 'lazytasks-project-task-management'), res.message, res.data.response_code)
                : `${res.message} ${res.data.error || ''}`,
            color: res.data.success ? 'green' : 'red',
        });
        load(page);
        dispatch(fetchWebhooks());
    };

    const th = { textAlign: 'left', fontSize: 11, fontWeight: 600, color: T.muted, textTransform: 'uppercase', letterSpacing: '.4px', padding: '10px 14px', background: '#F8FAFC', borderBottom: `1px solid ${T.border}`, position: 'sticky', top: 0, zIndex: 1 };
    const td = { padding: '10px 14px', borderBottom: `1px solid ${T.border}`, fontSize: 13, verticalAlign: 'top' };

    return (
        <Drawer
            opened={!!webhook}
            onClose={onClose}
            position="right"
            size={760}
            title={
                <div>
                    <div style={{ fontWeight: 700 }}>{__('Delivery log', 'lazytasks-project-task-management')}</div>
                    <div style={{ fontSize: 12, color: T.muted }}>{webhook?.name}</div>
                </div>
            }
            styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: 'calc(100% - 64px)' } }}
        >
            <div style={{ display: 'flex', gap: 8, padding: '10px 20px', borderBottom: `1px solid ${T.border}`, alignItems: 'center', flexWrap: 'wrap' }}>
                <Select
                    size="xs"
                    w={160}
                    value={status}
                    onChange={v => { setStatus(v || ''); setPage(1); }}
                    allowDeselect={false}
                    comboboxProps={{ withinPortal: true, zIndex: 1000 }}
                    data={[
                        { value: '', label: __('All statuses', 'lazytasks-project-task-management') },
                        ...['succeeded', 'retrying', 'failed', 'pending'].map(s => ({ value: s, label: statusLabel(s) })),
                    ]}
                />
                <Select
                    size="xs"
                    w={200}
                    value={event}
                    onChange={v => { setEvent(v || ''); setPage(1); }}
                    allowDeselect={false}
                    comboboxProps={{ withinPortal: true, zIndex: 1000 }}
                    data={[
                        { value: '', label: __('All events', 'lazytasks-project-task-management') },
                        ...catalog.map(e => ({ value: e.key, label: e.label })),
                        { value: TEST_EVENT, label: __('Test message', 'lazytasks-project-task-management') },
                    ]}
                />
                <span style={{ marginLeft: 'auto', fontSize: 12, color: T.muted }}>{__('Last 30 days · click a row for details', 'lazytasks-project-task-management')}</span>
            </div>

            <div style={{ flex: 1, overflowY: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                    <thead>
                        <tr>
                            <th style={{ ...th, width: 24 }} />
                            <th style={th}>{__('Event', 'lazytasks-project-task-management')}</th>
                            <th style={th}>{__('Status', 'lazytasks-project-task-management')}</th>
                            <th style={th}>{__('Attempts', 'lazytasks-project-task-management')}</th>
                            <th style={th}>{__('Response', 'lazytasks-project-task-management')}</th>
                            <th style={th}>{__('Time', 'lazytasks-project-task-management')}</th>
                        </tr>
                    </thead>
                    <tbody>
                        {deliveries.isLoading && !items.length && (
                            <tr><td colSpan={6} style={{ ...td, textAlign: 'center', padding: 30 }}><Loader size="sm" color={T.teal} /></td></tr>
                        )}
                        {!deliveries.isLoading && !items.length && (
                            <tr><td colSpan={6} style={{ ...td, textAlign: 'center', padding: 30, color: T.muted }}>{__('No deliveries match these filters.', 'lazytasks-project-task-management')}</td></tr>
                        )}
                        {items.map(d => {
                            const isOpen = openRow === d.id;
                            const canResend = d.status === 'succeeded' || d.status === 'failed';
                            return (
                                <React.Fragment key={d.id}>
                                    <tr onClick={() => setOpenRow(isOpen ? null : d.id)} style={{ cursor: 'pointer', background: isOpen ? '#F8FAFC' : undefined }}>
                                        <td style={{ ...td, color: T.light, paddingRight: 0 }}>{isOpen ? <IconChevronDown size={14} /> : <IconChevronRight size={14} />}</td>
                                        <td style={td}>
                                            <div>{label(d.event_type)}</div>
                                            <div style={{ fontFamily: T.mono, fontSize: 11, color: T.light }}>{d.event_type}</div>
                                        </td>
                                        <td style={td}>
                                            <Badge status={d.status} />
                                            {d.status === 'retrying' && d.next_attempt_at && (
                                                <div style={{ fontSize: 12, color: T.muted }}>{sprintf(/* translators: %s: date and time */ __('Next try %s', 'lazytasks-project-task-management'), formatTime(d.next_attempt_at))}</div>
                                            )}
                                        </td>
                                        <td style={td}>{d.event_type === TEST_EVENT ? d.attempt_count : sprintf(/* translators: 1: attempts made, 2: maximum attempts */ __('%1$d of %2$d', 'lazytasks-project-task-management'), d.attempt_count, MAX_ATTEMPTS)}</td>
                                        <td style={td}>{d.response_code ? `HTTP ${d.response_code}` : <span style={{ color: T.muted }}>{__('No response', 'lazytasks-project-task-management')}</span>}</td>
                                        <td style={{ ...td, color: T.muted, whiteSpace: 'nowrap' }}>{formatTime(d.created_at)}</td>
                                    </tr>
                                    {isOpen && (
                                        <tr>
                                            <td colSpan={6} style={{ ...td, background: '#F8FAFC', padding: '14px 20px' }}>
                                                {d.last_error && (
                                                    <Alert tone="bad" icon={<IconAlertTriangle size={14} />} style={{ marginBottom: 12 }}>{d.last_error}</Alert>
                                                )}
                                                <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '4px 12px', fontSize: 13, marginBottom: 12 }}>
                                                    <span style={{ color: T.muted }}>{__('Event ID', 'lazytasks-project-task-management')}</span><span style={{ fontFamily: T.mono, fontSize: 12 }}>{d.event_id}</span>
                                                    <span style={{ color: T.muted }}>{__('Duration', 'lazytasks-project-task-management')}</span><span>{d.duration_ms != null ? sprintf(/* translators: %d: duration in milliseconds */ __('%d ms', 'lazytasks-project-task-management'), d.duration_ms) : '—'}</span>
                                                </div>
                                                <FieldLabel>{__('Message', 'lazytasks-project-task-management')}</FieldLabel>
                                                <Code>{JSON.stringify(d.payload, null, 2)}</Code>
                                                <FieldLabel style={{ marginTop: 10 }}>{__('Response body', 'lazytasks-project-task-management')} <span style={{ fontWeight: 400, color: T.muted }}>{__('(first 1 KB)', 'lazytasks-project-task-management')}</span></FieldLabel>
                                                <Code>{d.response_body || '—'}</Code>
                                                <div style={{ marginTop: 10, display: 'flex', gap: 8, alignItems: 'center' }}>
                                                    <Btn
                                                        variant="default"
                                                        style={{ height: 28, fontSize: 12, padding: '0 10px' }}
                                                        disabled={!canResend}
                                                        loading={resending === d.id}
                                                        onClick={e => { e.stopPropagation(); resend(d); }}
                                                    >
                                                        <IconRefresh size={14} />{__('Resend now', 'lazytasks-project-task-management')}
                                                    </Btn>
                                                    <span style={{ fontSize: 12, color: T.muted }}>
                                                        {canResend
                                                            ? __('Sends the same message again (same Event ID) and shows the result.', 'lazytasks-project-task-management')
                                                            : __('Waiting for the next automatic try.', 'lazytasks-project-task-management')}
                                                    </span>
                                                </div>
                                            </td>
                                        </tr>
                                    )}
                                </React.Fragment>
                            );
                        })}
                    </tbody>
                </table>
            </div>

            <div style={{ padding: '10px 20px', borderTop: `1px solid ${T.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, color: T.muted }}>
                <span>{sprintf(/* translators: %d: number of deliveries */ __('%d deliveries', 'lazytasks-project-task-management'), total)}</span>
                <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                    <Btn variant="default" style={{ height: 28, fontSize: 12, padding: '0 10px' }} disabled={page <= 1} onClick={() => setPage(p => p - 1)}>{__('Previous', 'lazytasks-project-task-management')}</Btn>
                    <span style={{ padding: '0 6px' }}>{sprintf(/* translators: 1: current page, 2: number of pages */ __('Page %1$d of %2$d', 'lazytasks-project-task-management'), page, pages)}</span>
                    <Btn variant="default" style={{ height: 28, fontSize: 12, padding: '0 10px' }} disabled={page >= pages} onClick={() => setPage(p => p + 1)}>{__('Next', 'lazytasks-project-task-management')}</Btn>
                </div>
            </div>
        </Drawer>
    );
}

// -----------------------------------------------------------------------------
// Tab
// -----------------------------------------------------------------------------

function OutgoingWebhooks() {
    const dispatch = useDispatch();
    const { webhooks, events: catalog, isLoading, isLoaded } = useSelector(s => s.settings.webhooks);
    const { projects } = useSelector(s => s.settings.project);

    const [formOpen, setFormOpen] = useState(false);
    const [editing, setEditing] = useState(null);
    const [secret, setSecret] = useState(null);
    const [secretTitle, setSecretTitle] = useState('');
    const [confirm, setConfirm] = useState(null);
    const [testing, setTesting] = useState(null);
    const [logFor, setLogFor] = useState(null);
    const [guideOpen, setGuideOpen] = useState(false);

    useEffect(() => {
        dispatch(fetchWebhookEvents());
        dispatch(fetchWebhooks());
        dispatch(fetchAllProjects());
    }, [dispatch]);

    const projectName = (id) => (projects || []).find(p => Number(p.id) === Number(id))?.name;
    const eventLabel = (key) => catalog.find(e => e.key === key)?.label || key;

    const openForm = (w = null) => { setEditing(w); setFormOpen(true); };

    const onCreated = (data) => {
        setFormOpen(false);
        setSecretTitle(__('Webhook created', 'lazytasks-project-task-management'));
        setSecret(data.secret);
    };

    const askRegenerate = (w) => setConfirm({
        title: __('Regenerate secret?', 'lazytasks-project-task-management'),
        body: (
            <>
                <p style={{ margin: 0 }}>{sprintf(/* translators: %s: webhook name */ __('A new signing secret is created for %s and the old one stops working at once. Messages still waiting to be retried are signed with the new secret.', 'lazytasks-project-task-management'), w.name)}</p>
                <p style={{ margin: '8px 0 0', fontSize: 12, color: T.muted }}>{__('Update the secret in the receiving app straight away, or it will reject the messages.', 'lazytasks-project-task-management')}</p>
            </>
        ),
        action: __('Regenerate', 'lazytasks-project-task-management'),
        onConfirm: async () => {
            const res = await dispatch(regenerateWebhookSecret(w.id)).unwrap();
            if (res?.status !== 200) return;
            setConfirm(null);
            setSecretTitle(__('New secret created', 'lazytasks-project-task-management'));
            setSecret(res.data.secret);
        },
    });

    const askDelete = (w) => setConfirm({
        title: __('Delete webhook?', 'lazytasks-project-task-management'),
        body: <p style={{ margin: 0 }}>{sprintf(/* translators: %s: webhook name */ __('%s will stop receiving events. Retries that are still waiting are cancelled.', 'lazytasks-project-task-management'), w.name)}</p>,
        action: __('Delete', 'lazytasks-project-task-management'),
        danger: true,
        onConfirm: async () => {
            const res = await dispatch(deleteWebhook(w.id)).unwrap();
            if (res?.status !== 200) return;
            setConfirm(null);
            showNotification({ title: __('Deleted', 'lazytasks-project-task-management'), message: res.message, color: 'green' });
        },
    });

    const startTest = (w) => {
        setTesting(w);
        dispatch(testWebhook(w.id));
    };

    const closeTest = () => { setTesting(null); dispatch(clearWebhookTest()); };
    const closeLog = () => { setLogFor(null); dispatch(clearWebhookDeliveries()); };

    const th = { textAlign: 'left', fontSize: 11, fontWeight: 600, color: T.muted, textTransform: 'uppercase', letterSpacing: '.4px', padding: '10px 14px', background: '#F8FAFC', borderBottom: `1px solid ${T.border}` };
    const td = { padding: '12px 14px', borderBottom: `1px solid ${T.border}`, verticalAlign: 'top', fontSize: 13 };
    const chip = { fontSize: 11, padding: '1px 7px', borderRadius: 10, background: T.tealLt, color: T.tealDk, whiteSpace: 'nowrap' };

    return (
        <div>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 16 }}>
                <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                        <div style={{ fontSize: 15, fontWeight: 700, color: T.text }}>{__('Webhooks', 'lazytasks-project-task-management')}</div>
                        <IconBtn label={__('How to receive webhooks', 'lazytasks-project-task-management')} onClick={() => setGuideOpen(true)}>
                            <IconHelpCircle size={17} stroke={1.7} />
                        </IconBtn>
                    </div>
                    <div style={{ fontSize: 13, color: T.muted, maxWidth: 680 }}>
                        {__('Send a signed message to another app (Slack, Zapier, n8n, your own code) when something happens in LazyTasks.', 'lazytasks-project-task-management')}
                    </div>
                </div>
                {webhooks.length > 0 && <Btn onClick={() => openForm()}><IconPlus size={15} />{__('Add webhook', 'lazytasks-project-task-management')}</Btn>}
            </div>

            {isLoading && !isLoaded && (
                <div style={{ padding: 40, textAlign: 'center' }}><Loader size="sm" color={T.teal} /></div>
            )}

            {isLoaded && webhooks.length === 0 && (
                <div style={{ background: '#fff', border: `1px solid ${T.border}`, borderRadius: T.radius, boxShadow: T.shadow, padding: '48px 20px', textAlign: 'center' }}>
                    <div style={{ width: 48, height: 48, borderRadius: '50%', background: T.tealLt, color: T.teal, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
                        <IconWebhook size={24} stroke={1.6} />
                    </div>
                    <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>{__('No webhooks yet', 'lazytasks-project-task-management')}</div>
                    <div style={{ fontSize: 13, color: T.muted, maxWidth: 460, margin: '0 auto 16px' }}>
                        {__('Add a webhook to send task, comment and project events to another app. Each message is signed so the receiving app can check it came from this site.', 'lazytasks-project-task-management')}
                    </div>
                    <Btn onClick={() => openForm()}><IconPlus size={15} />{__('Add webhook', 'lazytasks-project-task-management')}</Btn>
                </div>
            )}

            {webhooks.length > 0 && (
                <div style={{ background: '#fff', border: `1px solid ${T.border}`, borderRadius: T.radius, boxShadow: T.shadow, overflow: 'hidden' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                            <tr>
                                <th style={th}>{__('Webhook', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Events', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Projects', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Status', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Last delivery', 'lazytasks-project-task-management')}</th>
                                <th style={{ ...th, width: 110 }} />
                            </tr>
                        </thead>
                        <tbody>
                            {webhooks.map((w, i) => {
                                const last = i === webhooks.length - 1;
                                const cell = last ? { ...td, borderBottom: 'none' } : td;
                                const allEvents = catalog.length > 0 && w.events.length >= catalog.length;
                                return (
                                    <tr key={w.id}>
                                        <td style={cell}>
                                            <div style={{ fontWeight: 600 }}>{w.name}</div>
                                            <div style={{ fontFamily: T.mono, fontSize: 12, color: T.muted, wordBreak: 'break-all' }}>{w.endpoint_url}</div>
                                            {w.include_private && <div style={{ fontSize: 12, color: T.muted }}>{__('Includes private tasks', 'lazytasks-project-task-management')}</div>}
                                            {w.status === 'disabled' && (
                                                <div style={{ marginTop: 6, fontSize: 12, color: T.dangerDk, display: 'flex', gap: 5 }}>
                                                    <IconAlertTriangle size={14} style={{ flexShrink: 0, marginTop: 2 }} />
                                                    <span>
                                                        {sprintf(/* translators: %d: number of failed deliveries */ __('Switched off after %d failed deliveries in a row. Fix the receiver, then edit and switch it back on.', 'lazytasks-project-task-management'), w.consecutive_failures)}
                                                    </span>
                                                </div>
                                            )}
                                        </td>
                                        <td style={cell}>
                                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                                                {allEvents
                                                    ? <span style={chip}>{sprintf(/* translators: %d: number of events */ __('All %d events', 'lazytasks-project-task-management'), catalog.length)}</span>
                                                    : <>
                                                        {w.events.slice(0, 3).map(k => <span key={k} style={chip}>{eventLabel(k)}</span>)}
                                                        {w.events.length > 3 && (
                                                            <Tooltip label={w.events.slice(3).map(eventLabel).join(', ')} withArrow multiline w={220}>
                                                                <span style={chip}>+{w.events.length - 3}</span>
                                                            </Tooltip>
                                                        )}
                                                    </>}
                                            </div>
                                        </td>
                                        <td style={cell}>
                                            {w.project_scope === 'all'
                                                ? __('All projects', 'lazytasks-project-task-management')
                                                : w.project_ids.map(id => projectName(id) || `#${id}`).join(', ')}
                                        </td>
                                        <td style={cell}>
                                            {w.status === 'disabled'
                                                ? <Badge status="disabled">{sprintf(/* translators: %d: number of failures */ __('Disabled · %d failures', 'lazytasks-project-task-management'), w.consecutive_failures)}</Badge>
                                                : <Badge status={w.status} />}
                                        </td>
                                        <td style={cell}>
                                            {w.last_delivery_at ? (
                                                <>
                                                    {w.last_delivery_status && <Badge status={w.last_delivery_status} />}
                                                    <div style={{ fontSize: 12, color: T.muted }}>{formatTime(w.last_delivery_at)}</div>
                                                </>
                                            ) : <span style={{ fontSize: 12, color: T.muted }}>{__('Never', 'lazytasks-project-task-management')}</span>}
                                        </td>
                                        <td style={cell}>
                                            <div style={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
                                                <IconBtn label={__('Send test', 'lazytasks-project-task-management')} onClick={() => startTest(w)}><IconSend size={15} stroke={1.7} /></IconBtn>
                                                <IconBtn label={__('Delivery log', 'lazytasks-project-task-management')} onClick={() => setLogFor(w)}><IconList size={15} stroke={1.7} /></IconBtn>
                                                <Menu width={200} position="bottom-end" withinPortal>
                                                    <Menu.Target>
                                                        <button type="button" aria-label={__('More actions', 'lazytasks-project-task-management')} style={{ width: 28, height: 28, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none', borderRadius: T.radiusSm, color: T.muted, cursor: 'pointer' }}>
                                                            <IconDots size={15} />
                                                        </button>
                                                    </Menu.Target>
                                                    <Menu.Dropdown>
                                                        <Menu.Item leftSection={<IconEdit size={16} color="#6B7280" />} onClick={() => openForm(w)}>{__('Edit', 'lazytasks-project-task-management')}</Menu.Item>
                                                        <Menu.Item leftSection={<IconKey size={16} color="#6B7280" />} onClick={() => askRegenerate(w)}>{__('Regenerate secret', 'lazytasks-project-task-management')}</Menu.Item>
                                                        <Menu.Divider />
                                                        <Menu.Item color="red" leftSection={<IconTrash size={16} />} onClick={() => askDelete(w)}>{__('Delete', 'lazytasks-project-task-management')}</Menu.Item>
                                                    </Menu.Dropdown>
                                                </Menu>
                                            </div>
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            )}

            <WebhookForm opened={formOpen} webhook={editing} onClose={() => setFormOpen(false)} onCreated={onCreated} />
            <SecretModal secret={secret} title={secretTitle} onClose={() => setSecret(null)} />
            <ConfirmModal confirm={confirm} onClose={() => setConfirm(null)} />
            <TestModal webhook={testing} onClose={closeTest} />
            <WebhookGuideModal opened={guideOpen} onClose={() => setGuideOpen(false)} />
            <DeliveryLog webhook={logFor} onClose={closeLog} />
        </div>
    );
}

// -----------------------------------------------------------------------------
// Tab: Outgoing | Incoming
// -----------------------------------------------------------------------------

function DirectionButton({ active, onClick, icon, label, count }) {
    return (
        <button
            type="button"
            onClick={onClick}
            aria-pressed={active}
            style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, background: 'none', border: 'none',
                borderBottom: `2px solid ${active ? T.teal : 'transparent'}`, marginBottom: -1,
                padding: '8px 14px', fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
                color: active ? T.tealDk : T.muted, cursor: 'pointer',
            }}
        >
            {icon}{label}
            {count != null && <span style={{ fontSize: 11, background: T.tealLt, color: T.tealDk, borderRadius: 10, padding: '0 7px' }}>{count}</span>}
        </button>
    );
}

export default function WebhooksTabV3() {
    const dispatch = useDispatch();
    const [direction, setDirection] = useState('outgoing');
    const outgoing = useSelector(s => s.settings.webhooks);
    const incoming = useSelector(s => s.settings.incomingWebhooks);

    // Loaded here as well so the Incoming count shows before that view is opened.
    useEffect(() => { dispatch(fetchIncomingWebhooks()); }, [dispatch]);

    return (
        <div>
            <div style={{ display: 'flex', gap: 4, borderBottom: `1px solid ${T.border}`, marginBottom: 18 }}>
                <DirectionButton
                    active={direction === 'outgoing'}
                    onClick={() => setDirection('outgoing')}
                    icon={<IconArrowBarRight size={15} stroke={1.7} />}
                    label={__('Outgoing', 'lazytasks-project-task-management')}
                    count={outgoing.isLoaded ? outgoing.webhooks.length : null}
                />
                <DirectionButton
                    active={direction === 'incoming'}
                    onClick={() => setDirection('incoming')}
                    icon={<IconArrowBarToRight size={15} stroke={1.7} />}
                    label={__('Incoming', 'lazytasks-project-task-management')}
                    count={incoming.isLoaded ? incoming.webhooks.length : null}
                />
            </div>
            {direction === 'outgoing' ? <OutgoingWebhooks /> : <IncomingWebhooksPanel />}
        </div>
    );
}
