import React, { useRef, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Modal, Tabs, Accordion } from '@mantine/core';
import { showNotification } from '@mantine/notifications';
import { IconArrowRight, IconCopy, IconCheck, IconSend } from '@tabler/icons-react';
import { copyToClipboard } from '../../../utils/copyText';

export const C = {
    orange: '#ED7D31', teal: '#39758D', tealLt: '#EBF1F4', tealDk: '#2C5C6E',
    border: '#E2E8F0', text: '#1A202C', body: '#334155', muted: '#64748B',
    infoLt: '#E0F2FE', infoDk: '#075985', warningLt: '#FEF3C7', warningDk: '#92400E',
    mono: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
};

// The snippets mirror the signing in WebhookSecurity::sign(): "v1=" + hex HMAC-SHA256
// of "<timestamp>.<raw body>", keyed with the whole whsec_ secret.
const CODE = {
    php: String.raw`<?php
$secret    = 'whsec_your_secret_here';
$body      = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_LAZYTASKS_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_LAZYTASKS_SIGNATURE'] ?? '';

$expected = 'v1=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret);

if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300 || !hash_equals($expected, $signature)) {
    http_response_code(401);
    exit;
}

$message = json_decode($body, true);
// $message['event'] is e.g. "task.completed" — handle it here.
http_response_code(200);
echo 'ok';`,
    laravel: String.raw`// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/lazytasks', function (Request $request) {
    $secret    = config('services.lazytasks.webhook_secret'); // whsec_...
    $body      = $request->getContent();
    $timestamp = (string) $request->header('X-LazyTasks-Timestamp', '');
    $signature = (string) $request->header('X-LazyTasks-Signature', '');

    $expected = 'v1=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret);

    abort_unless(
        ctype_digit($timestamp) && abs(time() - (int) $timestamp) <= 300 && hash_equals($expected, $signature),
        401
    );

    $message = json_decode($body, true);
    // e.g. ProcessLazyTasksEvent::dispatch($message);
    return response('ok', 200);
});`,
    node: String.raw`const express = require('express');
const crypto = require('crypto');

const app = express();
const SECRET = 'whsec_your_secret_here';

// express.raw keeps the body exactly as received.
app.post('/webhooks/lazytasks', express.raw({ type: 'application/json' }), (req, res) => {
    const timestamp = req.get('X-LazyTasks-Timestamp') || '';
    const signature = req.get('X-LazyTasks-Signature') || '';

    const expected = 'v1=' + crypto
        .createHmac('sha256', SECRET)
        .update(timestamp + '.')
        .update(req.body)
        .digest('hex');

    const fresh = /^\d+$/.test(timestamp) && Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300;
    const a = Buffer.from(expected);
    const b = Buffer.from(signature);
    if (!fresh || a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
        return res.sendStatus(401);
    }

    const message = JSON.parse(req.body.toString('utf8'));
    // message.event is e.g. "task.completed" — handle it here.
    res.status(200).send('ok');
});

app.listen(3000);`,
};

const EXAMPLE_JSON = JSON.stringify({
    event: 'task.status_changed',
    event_id: '8f3a2c1e-4b7d-4e2a-9c51-0d6e7f8a9b10',
    occurred_at: '2026-11-11T09:30:12Z',
    site: 'https://tasks.example.com',
    actor: { id: 12, name: 'Jane Doe', email: 'jane@example.com' },
    data: {
        task: {
            id: 4252,
            ref: 3843,
            title: 'Prepare the client proposal',
            project: { id: 2, name: 'Website' },
            section: { id: 319, name: 'In review' },
            status: { id: 5, name: 'In Progress' },
            priority: { id: 6, name: 'High' },
            assignees: [{ id: 12, name: 'Jane Doe' }],
            due_date: '2026-11-20',
            parent: null,
            url: 'https://tasks.example.com/lazytasks/#/task/4252',
        },
    },
    changes: { status: { old: { id: 4, name: 'Active' }, new: { id: 5, name: 'In Progress' } } },
}, null, 2);

export const K = ({ children }) => (
    <code style={{ fontFamily: C.mono, fontSize: 12, background: '#F1F5F9', padding: '1px 5px', borderRadius: 4 }}>{children}</code>
);

export const Note = ({ tone, children }) => {
    const [bg, fg] = tone === 'warn' ? [C.warningLt, C.warningDk] : [C.infoLt, C.infoDk];
    return <div style={{ marginTop: 8, background: bg, color: fg, borderRadius: 6, padding: '8px 10px', fontSize: 12 }}>{children}</div>;
};

export const SectionHeading = ({ children, style }) => (
    <div style={{ fontSize: 13, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.4px', color: C.muted, margin: '4px 0 12px', ...style }}>{children}</div>
);

// A copyable dark code block. Copies from the visible text when the helper's off-screen
// textarea can't take focus, which happens inside the modal's focus trap on http sites.
export function CopyBlock({ text, label, children }) {
    const preRef = useRef(null);
    const [copied, setCopied] = useState(false);

    const copyFromSelection = () => {
        const node = preRef.current;
        if (!node) return false;
        const range = document.createRange();
        range.selectNodeContents(node);
        const sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        let ok = false;
        try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
        sel.removeAllRanges();
        return ok;
    };

    const copy = async () => {
        const ok = (await copyToClipboard(text)) || copyFromSelection();
        if (ok) {
            setCopied(true);
            setTimeout(() => setCopied(false), 1500);
        } else {
            showNotification({ title: __('Copy failed', 'lazytasks-project-task-management'), message: __('Select the code and copy it by hand.', 'lazytasks-project-task-management'), color: 'red' });
        }
    };

    return (
        <div style={{ border: `1px solid ${C.border}`, borderRadius: 8, overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', background: '#F8FAFC', borderBottom: `1px solid ${C.border}`, padding: '0 6px', minHeight: 38 }}>
                <div style={{ flex: 1, minWidth: 0 }}>{label}</div>
                <button
                    type="button"
                    onClick={copy}
                    style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 28, padding: '0 10px', borderRadius: 6, border: `1px solid ${C.border}`, background: '#fff', fontSize: 12, fontWeight: 600, fontFamily: 'inherit', color: C.text, cursor: 'pointer' }}
                >
                    {copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
                    {copied ? __('Copied', 'lazytasks-project-task-management') : __('Copy', 'lazytasks-project-task-management')}
                </button>
            </div>
            <pre ref={preRef} style={{ margin: 0, background: '#0F172A', color: '#E2E8F0', fontFamily: C.mono, fontSize: 12, lineHeight: 1.6, padding: '12px 14px', overflow: 'auto', maxHeight: 320, whiteSpace: 'pre' }}>
                {children || text}
            </pre>
        </div>
    );
}

export function Step({ n, title, last, children }) {
    return (
        <div style={{ display: 'grid', gridTemplateColumns: '28px 1fr', gap: 12, paddingBottom: last ? 0 : 18, position: 'relative' }}>
            {!last && <div style={{ position: 'absolute', left: 13, top: 30, bottom: 2, width: 2, background: C.border }} />}
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: C.orange, color: '#fff', fontWeight: 700, fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{n}</div>
            <div style={{ minWidth: 0, fontSize: 13, color: C.body }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: C.text, margin: '3px 0 4px' }}>{title}</div>
                {children}
            </div>
        </div>
    );
}

export function FlowBox({ title, children }) {
    return (
        <div style={{ flex: '1 1 180px', background: C.tealLt, borderRadius: 8, padding: '10px 12px', fontSize: 12, color: C.tealDk }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: C.text, marginBottom: 2 }}>{title}</div>
            {children}
        </div>
    );
}

export const tableCell = { padding: '7px 10px', fontSize: 12, borderBottom: `1px solid ${C.border}`, verticalAlign: 'top', textAlign: 'left' };
export const tableHead = { ...tableCell, fontSize: 11, fontWeight: 600, color: C.muted, textTransform: 'uppercase', letterSpacing: '.4px', background: '#F8FAFC' };

export default function WebhookGuideModal({ opened, onClose }) {
    const [lang, setLang] = useState('php');

    const events = [
        ['task.created', __('A task is created (also when a Quick Task is converted).', 'lazytasks-project-task-management')],
        ['subtask.created', __('A subtask is created.', 'lazytasks-project-task-management')],
        ['task.assigned', __('A task gets an assignee, or a different one.', 'lazytasks-project-task-management')],
        ['task.status_changed', __('The task’s status changes, e.g. Active → In Progress.', 'lazytasks-project-task-management')],
        ['task.moved', __('The task moves to another section or project.', 'lazytasks-project-task-management')],
        ['task.completed', __('The task is marked complete.', 'lazytasks-project-task-management')],
        ['task.due_date_changed', __('The due date is set, changed or removed.', 'lazytasks-project-task-management')],
        ['comment.added', __('Someone comments or replies on a task.', 'lazytasks-project-task-management')],
        ['project.created', __('A new project is created (only for webhooks on All projects).', 'lazytasks-project-task-management')],
    ];

    const headers = [
        ['X-LazyTasks-Event', __('The event, e.g. task.completed', 'lazytasks-project-task-management')],
        ['X-LazyTasks-Delivery', __('The message id (same as event_id); stays the same on retries', 'lazytasks-project-task-management')],
        ['X-LazyTasks-Timestamp', __('When it was sent (Unix seconds)', 'lazytasks-project-task-management')],
        ['X-LazyTasks-Signature', __('The signature to check in step 3', 'lazytasks-project-task-management')],
    ];

    const arrow = <IconArrowRight size={18} color={C.teal} style={{ alignSelf: 'center', flexShrink: 0 }} />;

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={<span style={{ fontWeight: 700 }}>{__('How to receive webhooks', 'lazytasks-project-task-management')}</span>}
            centered
            size={820}
        >
            <div style={{ fontSize: 13, color: C.muted, marginBottom: 14 }}>
                {__('A webhook lets another app hear about changes in LazyTasks the moment they happen — no polling, no manual export.', 'lazytasks-project-task-management')}
            </div>

            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 22 }}>
                <FlowBox title={__('1. Something happens', 'lazytasks-project-task-management')}>{__('A task is created, assigned, moved or completed, or someone comments.', 'lazytasks-project-task-management')}</FlowBox>
                {arrow}
                <FlowBox title={__('2. LazyTasks sends a message', 'lazytasks-project-task-management')}>{__('A JSON message is posted to your URL, signed with your secret.', 'lazytasks-project-task-management')}</FlowBox>
                {arrow}
                <FlowBox title={__('3. Your app replies "OK"', 'lazytasks-project-task-management')}>{__('It checks the signature, answers 200, then does its own work.', 'lazytasks-project-task-management')}</FlowBox>
            </div>

            <SectionHeading>{__('Set it up in 5 steps', 'lazytasks-project-task-management')}</SectionHeading>
            <div style={{ marginBottom: 22 }}>
                <Step n={1} title={__('Get a URL for your app', 'lazytasks-project-task-management')}>
                    <div>{__('This is the address LazyTasks will send messages to. It must:', 'lazytasks-project-task-management')}</div>
                    <ul style={{ paddingLeft: 18, margin: '4px 0 0' }}>
                        <li>{__('start with', 'lazytasks-project-task-management')} <K>https://</K></li>
                        <li>{__('be reachable from the internet (not localhost or a private network address)', 'lazytasks-project-task-management')}</li>
                    </ul>
                    <Note>
                        <b>{__('Using Zapier, Make or n8n?', 'lazytasks-project-task-management')}</b>{' '}
                        {__('Create a "Webhook" / "Catch hook" trigger there and copy the URL it gives you. You can skip step 3 — those tools receive the message for you.', 'lazytasks-project-task-management')}
                    </Note>
                    <Note tone="warn">
                        <b>{__('Just testing?', 'lazytasks-project-task-management')}</b>{' '}
                        {__('A site like webhook.site gives you a URL instantly and shows every message it receives. Anyone with that link can read the messages, so use it only for testing, never for real projects.', 'lazytasks-project-task-management')}
                    </Note>
                </Step>

                <Step n={2} title={__('Add the webhook here', 'lazytasks-project-task-management')}>
                    <div>{__('Click Add webhook, paste your URL, give it a name, and choose which events and projects it should receive.', 'lazytasks-project-task-management')}</div>
                    <div style={{ marginTop: 6 }}>
                        {__('After you click Create webhook, a signing secret (it starts with whsec_) is shown.', 'lazytasks-project-task-management')}{' '}
                        <b>{__('Copy it right away — it is shown only once.', 'lazytasks-project-task-management')}</b>{' '}
                        {__('Lost it? Use ⋯ → Regenerate secret.', 'lazytasks-project-task-management')}
                    </div>
                </Step>

                <Step n={3} title={__('Check the message really came from LazyTasks', 'lazytasks-project-task-management')}>
                    <div style={{ marginBottom: 10 }}>
                        {__('Every message carries a signature made with your secret. Your app recalculates it and compares. Copy the example for your language and put your secret in it:', 'lazytasks-project-task-management')}
                    </div>
                    <Tabs value={lang} onChange={(v) => v && setLang(v)} color={C.teal}>
                        <CopyBlock
                            text={CODE[lang]}
                            label={(
                                <Tabs.List style={{ borderBottom: 'none' }}>
                                    <Tabs.Tab value="php">PHP</Tabs.Tab>
                                    <Tabs.Tab value="laravel">Laravel</Tabs.Tab>
                                    <Tabs.Tab value="node">Node.js</Tabs.Tab>
                                </Tabs.List>
                            )}
                        />
                    </Tabs>
                    <div style={{ marginTop: 10, fontSize: 12, color: C.muted }}>
                        <b>{__('What this code does:', 'lazytasks-project-task-management')}</b>
                        <ol style={{ paddingLeft: 18, margin: '3px 0 0' }}>
                            <li>{__('Reads the message exactly as it arrived, plus the X-LazyTasks-Timestamp and X-LazyTasks-Signature headers.', 'lazytasks-project-task-management')}</li>
                            <li>{__('Builds the signature again using your secret.', 'lazytasks-project-task-management')}</li>
                            <li>{__('Rejects the message (401) if the signatures don’t match or it is older than 5 minutes.', 'lazytasks-project-task-management')}</li>
                            <li>{__('Otherwise accepts it and replies 200.', 'lazytasks-project-task-management')}</li>
                        </ol>
                        {lang === 'laravel' && (
                            <div style={{ marginTop: 6 }}>
                                {__('Put the route in routes/api.php so Laravel’s CSRF check does not block it.', 'lazytasks-project-task-management')}
                            </div>
                        )}
                    </div>
                </Step>

                <Step n={4} title={__('Reply quickly', 'lazytasks-project-task-management')}>
                    {__('Answer with status 200 (any 2xx works) within 10 seconds. Do slow work — sending emails, calling other APIs — after replying. Anything else, including a redirect, counts as a failed delivery.', 'lazytasks-project-task-management')}
                </Step>

                <Step n={5} title={__('Send a test', 'lazytasks-project-task-management')} last>
                    {__('In the webhook list, click the', 'lazytasks-project-task-management')}{' '}
                    <IconSend size={14} style={{ verticalAlign: -2 }} />{' '}
                    <b>{__('Send test', 'lazytasks-project-task-management')}</b>{' '}
                    {__('button. You’ll see whether your app accepted it. Every message, test or real, is listed in the Delivery log with your app’s reply.', 'lazytasks-project-task-management')}
                </Step>
            </div>

            <SectionHeading>{__('What you’ll receive', 'lazytasks-project-task-management')}</SectionHeading>
            <Accordion multiple variant="separated" radius="md" chevronPosition="right">
                <Accordion.Item value="message">
                    <Accordion.Control><span style={{ fontSize: 13, fontWeight: 600 }}>{__('Example message', 'lazytasks-project-task-management')}</span></Accordion.Control>
                    <Accordion.Panel>
                        <div style={{ fontSize: 12, color: C.muted, marginBottom: 8 }}>
                            {__('An HTTP POST with a JSON body. This one is sent when a task’s status changes:', 'lazytasks-project-task-management')}
                        </div>
                        <CopyBlock text={EXAMPLE_JSON} label={<span style={{ fontSize: 12, color: C.muted, padding: '0 6px' }}>JSON</span>} />
                        <div style={{ fontSize: 12, fontWeight: 600, color: C.muted, margin: '12px 0 6px' }}>{__('Headers sent with every message', 'lazytasks-project-task-management')}</div>
                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                            <tbody>
                                {headers.map(([h, d]) => (
                                    <tr key={h}><td style={tableCell}><K>{h}</K></td><td style={tableCell}>{d}</td></tr>
                                ))}
                            </tbody>
                        </table>
                    </Accordion.Panel>
                </Accordion.Item>
                <Accordion.Item value="events">
                    <Accordion.Control>
                        <span style={{ fontSize: 13, fontWeight: 600 }}>{__('Events', 'lazytasks-project-task-management')} ({events.length})</span>
                    </Accordion.Control>
                    <Accordion.Panel>
                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                            <thead>
                                <tr><th style={tableHead}>{__('Event', 'lazytasks-project-task-management')}</th><th style={tableHead}>{__('Sent when', 'lazytasks-project-task-management')}</th></tr>
                            </thead>
                            <tbody>
                                {events.map(([k, d]) => (
                                    <tr key={k}><td style={tableCell}><K>{k}</K></td><td style={tableCell}>{d}</td></tr>
                                ))}
                            </tbody>
                        </table>
                    </Accordion.Panel>
                </Accordion.Item>
            </Accordion>

            <SectionHeading style={{ marginTop: 20 }}>{__('Good to know', 'lazytasks-project-task-management')}</SectionHeading>
            <ul style={{ paddingLeft: 18, margin: 0, fontSize: 13, color: C.body }}>
                <li style={{ margin: '5px 0' }}><b>{__('Failed messages are retried', 'lazytasks-project-task-management')}</b> {__('after 1 minute, 5 minutes, 30 minutes and 2 hours.', 'lazytasks-project-task-management')}</li>
                <li style={{ margin: '5px 0' }}><b>{__('The same message can arrive twice.', 'lazytasks-project-task-management')}</b> {__('Save each event_id you handle and skip repeats.', 'lazytasks-project-task-management')}</li>
                <li style={{ margin: '5px 0' }}><b>{__('Messages can arrive out of order.', 'lazytasks-project-task-management')}</b> {__('Use occurred_at if order matters.', 'lazytasks-project-task-management')}</li>
                <li style={{ margin: '5px 0' }}><b>{__('After 20 failures in a row', 'lazytasks-project-task-management')}</b> {__('the webhook is switched off and its creator gets an email. Turn it back on by editing it.', 'lazytasks-project-task-management')}</li>
                <li style={{ margin: '5px 0' }}><b>{__('Private tasks', 'lazytasks-project-task-management')}</b> {__('are sent only when the webhook has Include private tasks on.', 'lazytasks-project-task-management')}</li>
            </ul>

            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
                <button
                    type="button"
                    onClick={onClose}
                    style={{ height: 34, padding: '0 14px', borderRadius: 6, border: `1px solid ${C.border}`, background: '#fff', fontSize: 13, fontWeight: 600, fontFamily: 'inherit', color: C.text, cursor: 'pointer' }}
                >
                    {__('Close', 'lazytasks-project-task-management')}
                </button>
            </div>
        </Modal>
    );
}
