import React, { useEffect, useMemo, useRef, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { Modal, Drawer, TextInput, Menu, Select, Loader } from '@mantine/core';
import { showNotification } from '@mantine/notifications';
import {
    IconPlus, IconDots, IconList, IconEdit, IconKey, IconTrash, IconAlertTriangle, IconInfoCircle,
    IconChevronDown, IconChevronRight, IconArrowBarToRight, IconHelpCircle,
} from '@tabler/icons-react';
import {
    fetchIncomingWebhooks, createIncomingWebhook, updateIncomingWebhook, deleteIncomingWebhook,
    regenerateIncomingWebhookToken, fetchIncomingLog, fetchIncomingCreators, fetchIncomingSections,
    clearIncomingLog, clearIncomingPickers,
} from '../store/incomingWebhookSlice';
import { fetchAllProjects } from '../store/projectSlice';
import appConfig from '../../../configs/app.config';
import { T, formatTime, Badge, Btn, IconBtn, Alert, Code, FieldLabel, SwitchRow, ConfirmModal, CopyBox } from './webhookUi';
import IncomingWebhookGuideModal from './IncomingWebhookGuideModal';

const PER_PAGE = 20;
const PROJECT_ACTIVE = '1';
const RECEIVER_URL = `${appConfig.liveApiUrl}/webhook`;

// Plain words for the error codes the receiver returns (and stores as last_result).
const errorLabel = (code) => ({
    invalid_field: __('Missing or invalid field', 'lazytasks-project-task-management'),
    target_missing: __('Project or section no longer available', 'lazytasks-project-task-management'),
    creator_not_allowed: __('"Created by" user is no longer allowed', 'lazytasks-project-task-management'),
    disabled: __('Webhook is switched off', 'lazytasks-project-task-management'),
    payload_too_large: __('Body larger than 64 KB', 'lazytasks-project-task-management'),
    rate_limited: __('Too many calls (over 60 a minute)', 'lazytasks-project-task-management'),
    not_found: __('Unknown token', 'lazytasks-project-task-management'),
    server_error: __('Server error, task not created', 'lazytasks-project-task-management'),
}[code] || code);

const warningLabel = (code) => ({
    priority_not_found: __('Priority not found, left empty', 'lazytasks-project-task-management'),
    assignee_not_found: __('No user with that email, left unassigned', 'lazytasks-project-task-management'),
    assignee_not_member: __('Assignee is not a project member, left unassigned', 'lazytasks-project-task-management'),
}[code] || code);

const curlExample = (url, token) => [
    `curl -X POST ${url} \\`,
    `  -H "Authorization: Bearer ${token}" \\`,
    '  -H "Content-Type: application/json" \\',
    "  -d '{",
    '    "title": "Website contact: refund request",',
    '    "description": "From jane@example.com",',
    '    "priority": "High",',
    '    "due_date": "2026-11-20",',
    '    "assignee_email": "support@example.com"',
    "  }'",
].join('\n');

const targetLabel = (w) => [w.project?.name, w.section?.name].filter(Boolean).join(' › ');

// Why calls to this webhook are refused, or null when its settings are usable.
const brokenReason = (w) => {
    if (!w.target_ok) {
        return w.status === 'active'
            ? __('The project is archived or deleted, or the section is gone. Calls are refused (409) until you choose another project and section.', 'lazytasks-project-task-management')
            : __('The project is archived or deleted, or the section is gone. Choose another project and section before switching it on.', 'lazytasks-project-task-management');
    }
    if (!w.creator_allowed) {
        const who = w.created_by_user?.name || __('The chosen user', 'lazytasks-project-task-management');
        return w.status === 'active'
            ? sprintf(/* translators: %s: user name */ __('%s is no longer allowed to create tasks here. Calls are refused (403) until you choose another user.', 'lazytasks-project-task-management'), who)
            : sprintf(/* translators: %s: user name */ __('%s is no longer allowed to create tasks here. Choose another user before switching it on.', 'lazytasks-project-task-management'), who);
    }
    return null;
};

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

const emptyForm = { name: '', project_id: '', section_id: '', created_by_user_id: '', active: true };

function IncomingForm({ opened, webhook, onClose, onCreated }) {
    const dispatch = useDispatch();
    const { isSaving, sections, creators } = useSelector(s => s.settings.incomingWebhooks);
    const { projects } = useSelector(s => s.settings.project);

    const [form, setForm] = useState(emptyForm);
    const [errors, setErrors] = useState({});
    const refs = { name: useRef(null), project_id: useRef(null), section_id: useRef(null), created_by_user_id: useRef(null) };

    useEffect(() => {
        if (!opened) return;
        setErrors({});
        dispatch(clearIncomingPickers());
        const next = webhook ? {
            name: webhook.name,
            project_id: webhook.project ? String(webhook.project.id) : '',
            section_id: webhook.section ? String(webhook.section.id) : '',
            created_by_user_id: webhook.created_by_user ? String(webhook.created_by_user.id) : '',
            active: webhook.status === 'active',
        } : emptyForm;
        setForm(next);
        if (next.project_id) dispatch(fetchIncomingSections(Number(next.project_id)));
        if (next.project_id && next.section_id) dispatch(fetchIncomingCreators({ projectId: Number(next.project_id), sectionId: Number(next.section_id) }));
    }, [opened, webhook, dispatch]);

    const projectOptions = useMemo(() => {
        const list = (projects || [])
            .filter(p => String(p.status) === PROJECT_ACTIVE)
            .map(p => ({ value: String(p.id), label: p.name }));
        // Keep a no-longer-usable saved project visible, so the admin sees what to replace.
        if (form.project_id && !list.some(o => o.value === form.project_id) && webhook?.project) {
            list.unshift({ value: form.project_id, label: sprintf(/* translators: %s: project name */ __('%s (not available)', 'lazytasks-project-task-management'), webhook.project.name), disabled: true });
        }
        return list;
    }, [projects, form.project_id, webhook]);

    const sectionItems = sections.projectId === Number(form.project_id) ? sections.items : [];
    const sectionOptions = sectionItems.map(s => ({
        value: String(s.id),
        label: s.mark_is_complete === 'complete'
            ? sprintf(/* translators: %s: section name */ __('%s (complete section)', 'lazytasks-project-task-management'), s.name)
            : s.name,
    }));
    const isComplete = sectionItems.find(s => String(s.id) === form.section_id)?.mark_is_complete === 'complete';
    const creatorOptions = creators.items.map(u => ({ value: String(u.id), label: `${u.name} — ${u.email}` }));

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

    const onProject = (value) => {
        const v = value || '';
        setForm(f => ({ ...f, project_id: v, section_id: '', created_by_user_id: '' }));
        setErrors(e => ({ ...e, project_id: null }));
        if (v) dispatch(fetchIncomingSections(Number(v)));
    };

    const onSection = (value) => {
        const v = value || '';
        // The allowed users depend on the section (a complete section also needs a
        // completion permission), so the list is reloaded and a choice it no longer
        // contains is shown as empty and must be made again.
        setForm(f => ({ ...f, section_id: v }));
        setErrors(e => ({ ...e, section_id: null }));
        if (v) dispatch(fetchIncomingCreators({ projectId: Number(form.project_id), sectionId: Number(v) }));
    };

    const original = webhook ? {
        project_id: webhook.project ? String(webhook.project.id) : '',
        section_id: webhook.section ? String(webhook.section.id) : '',
        created_by_user_id: webhook.created_by_user ? String(webhook.created_by_user.id) : '',
    } : null;
    const targetChanged = !original || ['project_id', 'section_id', 'created_by_user_id'].some(k => form[k] !== original[k]);

    const focusField = (field) => refs[field]?.current?.focus();

    const validate = () => {
        const e = {};
        if (!form.name.trim()) e.name = __('Name is required.', 'lazytasks-project-task-management');
        // Same rule as the server: switching off or renaming a webhook with a broken
        // target is allowed, so the target is only checked when it will be used.
        if (form.active || targetChanged) {
            if (!form.project_id || !projectOptions.some(o => o.value === form.project_id && !o.disabled)) {
                e.project_id = __('Choose a project.', 'lazytasks-project-task-management');
            } else if (!form.section_id || !sectionOptions.some(o => o.value === form.section_id)) {
                e.section_id = __('Choose a section in the selected project.', 'lazytasks-project-task-management');
            } else if (!form.created_by_user_id || !creatorOptions.some(o => o.value === form.created_by_user_id)) {
                e.created_by_user_id = __('Choose the user the tasks are created by.', 'lazytasks-project-task-management');
            }
        }
        return e;
    };

    const submit = async () => {
        if (sections.isLoading || creators.isLoading) return;
        const local = validate();
        if (Object.keys(local).length) {
            setErrors(local);
            focusField(['name', 'project_id', 'section_id', 'created_by_user_id'].find(k => local[k]));
            return;
        }

        const data = { name: form.name.trim(), status: form.active ? 'active' : 'inactive' };
        // The target is sent only when it changed, so an unchanged broken target does
        // not block switching the webhook off.
        if (targetChanged) {
            data.project_id = Number(form.project_id);
            data.section_id = Number(form.section_id);
            data.created_by_user_id = Number(form.created_by_user_id);
        }

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

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

        if (webhook) {
            showNotification({ title: __('Saved', 'lazytasks-project-task-management'), message: res.message, color: 'green' });
            onClose();
        } else {
            onCreated(res.data);
        }
    };

    const brokenNow = webhook && !targetChanged ? brokenReason(webhook) : null;
    const selectProps = { allowDeselect: false, searchable: true, comboboxProps: { withinPortal: true, zIndex: 1000 } };

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={<span style={{ fontWeight: 700 }}>{webhook ? __('Edit incoming webhook', 'lazytasks-project-task-management') : __('Add incoming webhook', 'lazytasks-project-task-management')}</span>}
            centered
            size="lg"
        >
            {brokenNow && (
                <Alert tone="bad" icon={<IconAlertTriangle size={14} />} style={{ marginBottom: 14 }}>{brokenNow}</Alert>
            )}
            <TextInput
                ref={refs.name}
                label={__('Name', 'lazytasks-project-task-management')}
                withAsterisk
                placeholder={__('e.g. Website contact form', 'lazytasks-project-task-management')}
                maxLength={191}
                value={form.name}
                onChange={e => set('name', e.currentTarget.value)}
                error={errors.name}
                mb={16}
                data-autofocus
            />
            <Select
                ref={refs.project_id}
                label={__('Project', 'lazytasks-project-task-management')}
                withAsterisk
                placeholder={__('Choose a project…', 'lazytasks-project-task-management')}
                description={__('Only active projects can be chosen.', 'lazytasks-project-task-management')}
                data={projectOptions}
                value={form.project_id || null}
                onChange={onProject}
                error={errors.project_id}
                nothingFoundMessage={__('No projects found', 'lazytasks-project-task-management')}
                mb={16}
                {...selectProps}
            />
            <Select
                ref={refs.section_id}
                label={__('Section', 'lazytasks-project-task-management')}
                withAsterisk
                placeholder={form.project_id ? __('Choose a section…', 'lazytasks-project-task-management') : __('Choose a project first', 'lazytasks-project-task-management')}
                disabled={!form.project_id}
                rightSection={sections.isLoading ? <Loader size={12} /> : undefined}
                data={sectionOptions}
                value={sectionOptions.some(o => o.value === form.section_id) ? form.section_id : null}
                onChange={onSection}
                error={errors.section_id}
                mb={isComplete ? 6 : 16}
                {...selectProps}
            />
            {isComplete && (
                <Alert tone="info" icon={<IconInfoCircle size={14} />} style={{ marginBottom: 16, fontSize: 12 }}>
                    {__("This is the project's complete section. Tasks added here are created as completed.", 'lazytasks-project-task-management')}
                </Alert>
            )}
            <Select
                ref={refs.created_by_user_id}
                label={__('Created by', 'lazytasks-project-task-management')}
                withAsterisk
                placeholder={form.section_id ? __('Choose a user…', 'lazytasks-project-task-management') : __('Choose a section first', 'lazytasks-project-task-management')}
                disabled={!form.section_id}
                rightSection={creators.isLoading ? <Loader size={12} /> : undefined}
                description={isComplete
                    ? __('Tasks show this user as their creator. Only users allowed to create and complete tasks in the project are listed.', 'lazytasks-project-task-management')
                    : __('Tasks show this user as their creator. Only users allowed to create tasks in the project are listed.', 'lazytasks-project-task-management')}
                data={creatorOptions}
                value={creatorOptions.some(o => o.value === form.created_by_user_id) ? form.created_by_user_id : null}
                onChange={v => set('created_by_user_id', v || '')}
                error={errors.created_by_user_id}
                nothingFoundMessage={__('No users found', 'lazytasks-project-task-management')}
                mb={8}
                {...selectProps}
            />
            <SwitchRow
                label={__('Active', 'lazytasks-project-task-management')}
                hint={__('Inactive webhooks refuse every call.', 'lazytasks-project-task-management')}
                checked={form.active}
                onChange={v => set('active', v)}
            />
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 18 }}>
                <Btn variant="default" onClick={onClose}>{__('Cancel', 'lazytasks-project-task-management')}</Btn>
                <Btn loading={isSaving} onClick={submit}>{webhook ? __('Save changes', 'lazytasks-project-task-management') : __('Create webhook', 'lazytasks-project-task-management')}</Btn>
            </div>
        </Modal>
    );
}

// -----------------------------------------------------------------------------
// Token (shown once)
// -----------------------------------------------------------------------------

function TokenModal({ shown, onClose }) {
    if (!shown) return null;
    const url = shown.url || RECEIVER_URL;
    return (
        <Modal opened onClose={onClose} title={<span style={{ fontWeight: 700 }}>{shown.title}</span>} centered size="lg" closeOnClickOutside={false}>
            <Alert icon={<IconAlertTriangle size={14} />} style={{ marginBottom: 14 }}>
                <b>{__('Copy the token now.', 'lazytasks-project-task-management')}</b>{' '}
                {sprintf(/* translators: %s: project › section */ __('It will not be shown again. Anyone who has it can create tasks in %s, so keep it secret.', 'lazytasks-project-task-management'), shown.target)}
            </Alert>
            <FieldLabel>{__('URL', 'lazytasks-project-task-management')}</FieldLabel>
            <CopyBox value={url} />
            <FieldLabel style={{ marginTop: 12 }}>{__('Token', 'lazytasks-project-task-management')}</FieldLabel>
            <CopyBox value={shown.token} failMessage={__('Select the token and copy it by hand.', 'lazytasks-project-task-management')} />
            <div style={{ fontSize: 12, color: T.muted, marginTop: 4 }}>
                {__('Send it in the Authorization header as "Bearer <token>". Never put it in the URL.', 'lazytasks-project-task-management')}
            </div>
            <FieldLabel style={{ marginTop: 14 }}>{__('Try it', 'lazytasks-project-task-management')}</FieldLabel>
            <CopyBox value={curlExample(url, shown.token)} />
            <div style={{ fontSize: 12, color: T.muted, marginTop: 8 }}>
                {__("Only title is required. A priority or assignee that doesn't match still creates the task, without that value, and the reply lists a warning.", '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>
    );
}

// -----------------------------------------------------------------------------
// Call log
// -----------------------------------------------------------------------------

function CallLog({ webhook, onClose }) {
    const dispatch = useDispatch();
    const { log } = useSelector(s => s.settings.incomingWebhooks);
    const [result, setResult] = useState('');
    const [page, setPage] = useState(1);
    const [openRow, setOpenRow] = useState(null);

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

    useEffect(() => {
        if (!webhook) return;
        const params = { page, per_page: PER_PAGE };
        if (result) params.result = result;
        dispatch(fetchIncomingLog({ id: webhook.id, params }));
    }, [webhook?.id, result, page, dispatch]); // eslint-disable-line react-hooks/exhaustive-deps

    const items = log.webhookId === webhook?.id ? log.items : [];
    const total = log.meta?.total || 0;
    const pages = Math.max(1, Math.ceil(total / PER_PAGE));

    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' };
    const small = { height: 28, fontSize: 12, padding: '0 10px' };

    return (
        <Drawer
            opened={!!webhook}
            onClose={onClose}
            position="right"
            size={760}
            title={
                <div>
                    <div style={{ fontWeight: 700 }}>{__('Call 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={180}
                    value={result}
                    onChange={v => { setResult(v || ''); setPage(1); }}
                    allowDeselect={false}
                    comboboxProps={{ withinPortal: true, zIndex: 1000 }}
                    data={[
                        { value: '', label: __('All calls', 'lazytasks-project-task-management') },
                        { value: 'created', label: __('Created a task', 'lazytasks-project-task-management') },
                        { value: 'rejected', label: __('Refused', '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}>{__('Result', 'lazytasks-project-task-management')}</th>
                            <th style={th}>{__('Task / reason', 'lazytasks-project-task-management')}</th>
                            <th style={th}>{__('From', 'lazytasks-project-task-management')}</th>
                            <th style={th}>{__('Time', 'lazytasks-project-task-management')}</th>
                        </tr>
                    </thead>
                    <tbody>
                        {log.isLoading && !items.length && (
                            <tr><td colSpan={5} style={{ ...td, textAlign: 'center', padding: 30 }}><Loader size="sm" color={T.teal} /></td></tr>
                        )}
                        {!log.isLoading && !items.length && (
                            <tr><td colSpan={5} style={{ ...td, textAlign: 'center', padding: 30, color: T.muted }}>{__('No calls match this filter.', 'lazytasks-project-task-management')}</td></tr>
                        )}
                        {items.map(c => {
                            const isOpen = openRow === c.id;
                            const created = c.result === 'created';
                            return (
                                <React.Fragment key={c.id}>
                                    <tr onClick={() => setOpenRow(isOpen ? null : c.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}>
                                            <Badge status={created ? 'created' : 'rejected'} />
                                            <div style={{ fontSize: 12, color: T.muted }}>HTTP {c.http_code}</div>
                                        </td>
                                        <td style={td}>
                                            {created && c.task_id ? (
                                                <Link to={`/task/${c.task_id}`} onClick={e => e.stopPropagation()} style={{ color: T.teal, fontWeight: 600, textDecoration: 'none' }}>
                                                    {sprintf(/* translators: %d: task id */ __('Open task %d', 'lazytasks-project-task-management'), c.task_id)}
                                                </Link>
                                            ) : <span>{errorLabel(c.error_code)}{c.error_field && <>: <code>{c.error_field}</code></>}</span>}
                                            {c.warnings.length > 0 && (
                                                <div style={{ marginTop: 3 }}>
                                                    <Badge status="warning">{sprintf(/* translators: %d: number of warnings */ __('%d warnings', 'lazytasks-project-task-management'), c.warnings.length)}</Badge>
                                                </div>
                                            )}
                                        </td>
                                        <td style={{ ...td, fontFamily: T.mono, fontSize: 12, color: T.muted }}>{c.source_ip || '—'}</td>
                                        <td style={{ ...td, color: T.muted, whiteSpace: 'nowrap' }}>{formatTime(c.created_at)}</td>
                                    </tr>
                                    {isOpen && (
                                        <tr>
                                            <td colSpan={5} style={{ ...td, background: '#F8FAFC', padding: '14px 20px' }}>
                                                {c.warnings.length > 0 && (
                                                    <>
                                                        <FieldLabel>{__('Warnings', 'lazytasks-project-task-management')}</FieldLabel>
                                                        <ul style={{ margin: '0 0 12px', paddingLeft: 18, fontSize: 12, color: T.warningDk }}>
                                                            {c.warnings.map((w, i) => <li key={i}><code>{w.field}</code> — {warningLabel(w.code)}</li>)}
                                                        </ul>
                                                    </>
                                                )}
                                                {c.error_code && (
                                                    <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '4px 12px', fontSize: 13, marginBottom: 12 }}>
                                                        <span style={{ color: T.muted }}>{__('Error code', 'lazytasks-project-task-management')}</span>
                                                        <span style={{ fontFamily: T.mono, fontSize: 12 }}>{c.error_code}</span>
                                                        {c.error_field && (
                                                            <>
                                                                <span style={{ color: T.muted }}>{__('Field', 'lazytasks-project-task-management')}</span>
                                                                <span style={{ fontFamily: T.mono, fontSize: 12 }}>{c.error_field}</span>
                                                            </>
                                                        )}
                                                    </div>
                                                )}
                                                <FieldLabel>{__('Request body', 'lazytasks-project-task-management')} <span style={{ fontWeight: 400, color: T.muted }}>{__('(first 2 KB)', 'lazytasks-project-task-management')}</span></FieldLabel>
                                                <Code>{c.request_body || '—'}</Code>
                                            </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 calls */ __('%d calls', 'lazytasks-project-task-management'), total)}</span>
                <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                    <Btn variant="default" style={small} 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={small} disabled={page >= pages} onClick={() => setPage(p => p + 1)}>{__('Next', 'lazytasks-project-task-management')}</Btn>
                </div>
            </div>
        </Drawer>
    );
}

// -----------------------------------------------------------------------------
// Panel
// -----------------------------------------------------------------------------

export default function IncomingWebhooksPanel() {
    const dispatch = useDispatch();
    const { webhooks, isLoading, isLoaded } = useSelector(s => s.settings.incomingWebhooks);

    const [formOpen, setFormOpen] = useState(false);
    const [editing, setEditing] = useState(null);
    const [token, setToken] = useState(null);
    const [confirm, setConfirm] = useState(null);
    const [logFor, setLogFor] = useState(null);
    const [guideOpen, setGuideOpen] = useState(false);

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

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

    const onCreated = (data) => {
        setFormOpen(false);
        setToken({ title: __('Incoming webhook created', 'lazytasks-project-task-management'), token: data.token, url: data.url, target: targetLabel(data) });
    };

    const askRegenerate = (w) => setConfirm({
        title: __('Regenerate token?', 'lazytasks-project-task-management'),
        body: (
            <>
                <p style={{ margin: 0 }}>{sprintf(/* translators: %s: webhook name */ __('A new token is created for %s. The old token stops working at once, and calls that still use it are refused.', 'lazytasks-project-task-management'), w.name)}</p>
                <p style={{ margin: '8px 0 0', fontSize: 12, color: T.muted }}>{__('Update the token in the sending app straight away.', 'lazytasks-project-task-management')}</p>
            </>
        ),
        action: __('Regenerate', 'lazytasks-project-task-management'),
        onConfirm: async () => {
            const res = await dispatch(regenerateIncomingWebhookToken(w.id)).unwrap();
            if (res?.status !== 200) return;
            setConfirm(null);
            setToken({ title: __('New token created', 'lazytasks-project-task-management'), token: res.data.token, url: res.data.url, target: targetLabel(res.data) });
        },
    });

    const askDelete = (w) => setConfirm({
        title: __('Delete incoming webhook?', 'lazytasks-project-task-management'),
        body: <p style={{ margin: 0 }}>{sprintf(/* translators: %s: webhook name */ __('%s will stop accepting calls straight away. Tasks it already created are not affected.', 'lazytasks-project-task-management'), w.name)}</p>,
        action: __('Delete', 'lazytasks-project-task-management'),
        danger: true,
        onConfirm: async () => {
            const res = await dispatch(deleteIncomingWebhook(w.id)).unwrap();
            if (res?.status !== 200) return;
            setConfirm(null);
            showNotification({ title: __('Deleted', 'lazytasks-project-task-management'), message: res.message, color: 'green' });
        },
    });

    const closeLog = () => { setLogFor(null); dispatch(clearIncomingLog()); };

    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 card = { background: '#fff', border: `1px solid ${T.border}`, borderRadius: T.radius, boxShadow: T.shadow };

    return (
        <div>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
                <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                        <div style={{ fontSize: 15, fontWeight: 700, color: T.text }}>{__('Incoming webhooks', 'lazytasks-project-task-management')}</div>
                        <IconBtn label={__('How to send tasks to LazyTasks', 'lazytasks-project-task-management')} onClick={() => setGuideOpen(true)}>
                            <IconHelpCircle size={17} stroke={1.7} />
                        </IconBtn>
                    </div>
                    <div style={{ fontSize: 13, color: T.muted, maxWidth: 680 }}>
                        {__('Let another app (a contact form, Zapier, n8n, your own code) create tasks in LazyTasks by sending a request.', 'lazytasks-project-task-management')}
                    </div>
                </div>
                {webhooks.length > 0 && <Btn onClick={() => openForm()}><IconPlus size={15} />{__('Add incoming webhook', 'lazytasks-project-task-management')}</Btn>}
            </div>

            <div style={{ ...card, display: 'flex', gap: 12, alignItems: 'center', padding: '12px 14px', marginBottom: 14, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 12, fontWeight: 600, color: T.muted, textTransform: 'uppercase', letterSpacing: '.4px' }}>{__('Send to', 'lazytasks-project-task-management')}</span>
                <div style={{ flex: 1, minWidth: 240 }}><CopyBox value={`POST ${RECEIVER_URL}`} /></div>
                <div style={{ flexBasis: '100%', fontSize: 12, color: T.muted }}>
                    {__('Every incoming webhook uses this URL. The token in the "Authorization: Bearer" header decides which webhook, and so which project and section, the task goes to.', 'lazytasks-project-task-management')}
                </div>
            </div>

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

            {isLoaded && webhooks.length === 0 && (
                <div style={{ ...card, 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 }}>
                        <IconArrowBarToRight size={24} stroke={1.6} />
                    </div>
                    <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>{__('No incoming webhooks yet', 'lazytasks-project-task-management')}</div>
                    <div style={{ fontSize: 13, color: T.muted, maxWidth: 460, margin: '0 auto 16px' }}>
                        {__('Add one to turn form submissions, emails from Zapier, or alerts from your own systems into tasks. Each webhook has its own token and always files tasks into the project and section you choose.', 'lazytasks-project-task-management')}
                    </div>
                    <Btn onClick={() => openForm()}><IconPlus size={15} />{__('Add incoming webhook', 'lazytasks-project-task-management')}</Btn>
                </div>
            )}

            {webhooks.length > 0 && (
                <div style={{ ...card, overflow: 'hidden' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                            <tr>
                                <th style={th}>{__('Webhook', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Creates tasks in', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Created by', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Status', 'lazytasks-project-task-management')}</th>
                                <th style={th}>{__('Last call', 'lazytasks-project-task-management')}</th>
                                <th style={{ ...th, width: 80 }} />
                            </tr>
                        </thead>
                        <tbody>
                            {webhooks.map((w, i) => {
                                const cell = i === webhooks.length - 1 ? { ...td, borderBottom: 'none' } : td;
                                const reason = brokenReason(w);
                                const lastOk = w.last_result === 'created';
                                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 }}>
                                                {sprintf(/* translators: %s: last four characters of the token */ __('Token ••••%s', 'lazytasks-project-task-management'), w.token_hint)}
                                            </div>
                                            {reason && (
                                                <div style={{ marginTop: 6, fontSize: 12, color: T.dangerDk, display: 'flex', gap: 5 }}>
                                                    <IconAlertTriangle size={14} style={{ flexShrink: 0, marginTop: 2 }} />
                                                    <span>{reason}</span>
                                                </div>
                                            )}
                                        </td>
                                        <td style={cell}>{targetLabel(w) || '—'}</td>
                                        <td style={cell}>{w.created_by_user?.name || '—'}</td>
                                        <td style={cell}><Badge status={w.status} /></td>
                                        <td style={cell}>
                                            {w.last_called_at ? (
                                                <>
                                                    <Badge status={lastOk ? 'created' : 'rejected'} />
                                                    <div style={{ fontSize: 12, color: T.muted }}>{formatTime(w.last_called_at)}</div>
                                                    {!lastOk && w.last_result && <div style={{ fontSize: 12, color: T.muted }}>{errorLabel(w.last_result)}</div>}
                                                </>
                                            ) : <span style={{ fontSize: 12, color: T.muted }}>{__('Never called', 'lazytasks-project-task-management')}</span>}
                                        </td>
                                        <td style={cell}>
                                            <div style={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
                                                <IconBtn label={__('Call 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 token', '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>
            )}

            <IncomingForm opened={formOpen} webhook={editing} onClose={() => setFormOpen(false)} onCreated={onCreated} />
            <TokenModal shown={token} onClose={() => setToken(null)} />
            <ConfirmModal confirm={confirm} onClose={() => setConfirm(null)} />
            <CallLog webhook={logFor} onClose={closeLog} />
            <IncomingWebhookGuideModal opened={guideOpen} onClose={() => setGuideOpen(false)} url={RECEIVER_URL} />
        </div>
    );
}
