import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Modal, Tabs, Accordion } from '@mantine/core';
import { IconArrowRight, IconDots, IconList } from '@tabler/icons-react';
import { C, K, Note, SectionHeading, CopyBlock, Step, FlowBox, tableCell, tableHead } from './WebhookGuideModal';

const curlExample = (url) => [
    `curl -X POST ${url} \\`,
    '  -H "Authorization: Bearer YOUR_TOKEN" \\',
    '  -H "Content-Type: application/json" \\',
    `  -d '{"title":"Call back the client","description":"Asked about pricing","due_date":"2026-12-01","priority":"High","assignee_email":"jane@example.com"}'`,
].join('\n');

const SUCCESS_REPLY = JSON.stringify({
    ok: true,
    task: { id: 806, ref: 541, url: 'https://tasks.example.com/lazytasks/#/task/806' },
    warnings: [{ field: 'priority', code: 'priority_not_found' }],
}, null, 2);

const REFUSED_REPLY = JSON.stringify({
    ok: false,
    code: 'invalid_field',
    message: 'Title is required.',
    field: 'title',
}, null, 2);

const label = (text) => <span style={{ fontSize: 12, color: C.muted, padding: '0 6px' }}>{text}</span>;

const ToolSteps = ({ items }) => (
    <ol style={{ paddingLeft: 18, margin: '10px 0 0', fontSize: 13, color: C.body }}>
        {items.map((item, i) => <li key={i} style={{ margin: '4px 0' }}>{item}</li>)}
    </ol>
);

export default function IncomingWebhookGuideModal({ opened, onClose, url }) {
    const [tool, setTool] = useState('curl');

    const fields = [
        ['title', __('Yes', 'lazytasks-project-task-management'), __('The task name, up to 250 characters.', 'lazytasks-project-task-management')],
        ['description', __('No', 'lazytasks-project-task-management'), __('The task description. Basic HTML is kept.', 'lazytasks-project-task-management')],
        ['due_date', __('No', 'lazytasks-project-task-management'), __('A date such as 2026-12-01. Anything that isn’t a date refuses the call.', 'lazytasks-project-task-management')],
        ['priority', __('No', 'lazytasks-project-task-management'), __('The name of one of the project’s priorities, e.g. High (upper or lower case). An unknown name creates the task without a priority and adds a warning.', 'lazytasks-project-task-management')],
        ['assignee_email', __('No', 'lazytasks-project-task-management'), __('The email of a project member. Anyone else leaves the task unassigned and adds a warning. The assignee is notified as usual.', 'lazytasks-project-task-management')],
    ];

    const refusals = [
        ['404', 'not_found', __('The token is missing or wrong, or the webhook was deleted.', 'lazytasks-project-task-management'), __('Copy the token again, or regenerate it.', 'lazytasks-project-task-management')],
        ['403', 'disabled', __('The webhook is switched off.', 'lazytasks-project-task-management'), __('Edit it and turn Active on.', 'lazytasks-project-task-management')],
        ['403', 'creator_not_allowed', __('The Created by user can no longer create tasks in that project.', 'lazytasks-project-task-management'), __('Pick another user, or give their role the permission back.', 'lazytasks-project-task-management')],
        ['409', 'target_missing', __('The project or section was deleted or archived.', 'lazytasks-project-task-management'), __('Edit the webhook and choose a new section.', 'lazytasks-project-task-management')],
        ['413', 'payload_too_large', __('The body is larger than 64 KB.', 'lazytasks-project-task-management'), __('Send only the fields listed above.', 'lazytasks-project-task-management')],
        ['422', 'invalid_field', __('A field is missing or not valid; "field" says which.', 'lazytasks-project-task-management'), __('Fix that field and send again.', 'lazytasks-project-task-management')],
        ['429', 'rate_limited', __('More than 60 calls in a minute.', 'lazytasks-project-task-management'), __('Wait the seconds given in the Retry-After header.', 'lazytasks-project-task-management')],
        ['500', 'server_error', __('The task could not be saved.', 'lazytasks-project-task-management'), __('Try again later.', '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 send tasks to LazyTasks', 'lazytasks-project-task-management')}</span>}
            centered
            size={820}
        >
            <div style={{ fontSize: 13, color: C.muted, marginBottom: 14 }}>
                {__('An incoming webhook lets another app create tasks here — a contact form, Zapier, or your own code sends a request, and the task appears in the project and section you chose.', 'lazytasks-project-task-management')}
            </div>

            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 22 }}>
                <FlowBox title={__('1. Something happens there', 'lazytasks-project-task-management')}>{__('A form is submitted, a deal is won, a ticket comes in.', 'lazytasks-project-task-management')}</FlowBox>
                {arrow}
                <FlowBox title={__('2. The app sends a request', 'lazytasks-project-task-management')}>{__('A POST to the URL below, with your token in the Authorization header.', 'lazytasks-project-task-management')}</FlowBox>
                {arrow}
                <FlowBox title={__('3. LazyTasks creates the task', 'lazytasks-project-task-management')}>{__('As the Created by user, and replies with the task’s link.', 'lazytasks-project-task-management')}</FlowBox>
            </div>

            <SectionHeading>{__('Set it up in 4 steps', 'lazytasks-project-task-management')}</SectionHeading>
            <div style={{ marginBottom: 22 }}>
                <Step n={1} title={__('Add an incoming webhook', 'lazytasks-project-task-management')}>
                    {__('Click Add incoming webhook and choose the project and section the tasks go to, and the Created by user — the tasks are created as this person, so they must be allowed to create tasks in that project.', 'lazytasks-project-task-management')}
                </Step>

                <Step n={2} title={__('Copy the URL and the token', 'lazytasks-project-task-management')}>
                    <div>
                        {__('After you save, the token is shown.', 'lazytasks-project-task-management')}{' '}
                        <b>{__('Copy it right away — it is shown only once.', 'lazytasks-project-task-management')}</b>{' '}
                        {__('Lost it? Use', 'lazytasks-project-task-management')} <IconDots size={14} style={{ verticalAlign: -2 }} /> → {__('Regenerate token.', 'lazytasks-project-task-management')}
                    </div>
                    <Note tone="warn">
                        {__('Anyone with the token can create tasks in that section. Keep it in the sending app only. Regenerating stops the old token at once.', 'lazytasks-project-task-management')}
                    </Note>
                </Step>

                <Step n={3} title={__('Send a request', 'lazytasks-project-task-management')}>
                    <div style={{ marginBottom: 6 }}>{__('Every incoming webhook uses the same URL; the token decides which one:', 'lazytasks-project-task-management')}</div>
                    <ul style={{ paddingLeft: 18, margin: '0 0 10px' }}>
                        <li>{__('Method:', 'lazytasks-project-task-management')} <K>POST</K> <K>{url}</K></li>
                        <li>{__('Header:', 'lazytasks-project-task-management')} <K>Authorization: Bearer YOUR_TOKEN</K></li>
                        <li>{__('Body: JSON, or ordinary form fields, using the field names below.', 'lazytasks-project-task-management')}</li>
                    </ul>
                    <Tabs value={tool} onChange={(v) => v && setTool(v)} color={C.teal}>
                        <Tabs.List>
                            <Tabs.Tab value="curl">curl</Tabs.Tab>
                            <Tabs.Tab value="zapier">Zapier</Tabs.Tab>
                            <Tabs.Tab value="fluent">Fluent Forms</Tabs.Tab>
                        </Tabs.List>

                        <Tabs.Panel value="curl" pt={10}>
                            <CopyBlock text={curlExample(url)} label={label(__('Replace YOUR_TOKEN with your token', 'lazytasks-project-task-management'))} />
                        </Tabs.Panel>

                        <Tabs.Panel value="zapier" pt={4}>
                            <ToolSteps items={[
                                <>{__('Add an action:', 'lazytasks-project-task-management')} <b>Webhooks by Zapier</b> → <b>POST</b>.</>,
                                <>{__('URL: paste the URL above.', 'lazytasks-project-task-management')}</>,
                                <>{__('Payload Type:', 'lazytasks-project-task-management')} <K>json</K></>,
                                <>{__('Data: add', 'lazytasks-project-task-management')} <K>title</K> {__('and map it to a value from your trigger. Add the other fields the same way if you need them.', 'lazytasks-project-task-management')}</>,
                                <>{__('Headers:', 'lazytasks-project-task-management')} <K>Authorization</K> = <K>Bearer YOUR_TOKEN</K></>,
                                <>{__('Test the step. The reply should start with "ok": true.', 'lazytasks-project-task-management')}</>,
                            ]} />
                        </Tabs.Panel>

                        <Tabs.Panel value="fluent" pt={4}>
                            <ToolSteps items={[
                                <>{__('Needs Fluent Forms Pro. Turn on Webhooks under Fluent Forms → Integrations.', 'lazytasks-project-task-management')}</>,
                                <>{__('Open your form → Settings & Integrations → WebHook → Add New.', 'lazytasks-project-task-management')}</>,
                                <>{__('Request URL: paste the URL above. Request Method:', 'lazytasks-project-task-management')} <K>POST</K>. {__('Request Format:', 'lazytasks-project-task-management')} <K>JSON</K>.</>,
                                <>{__('Request Header: With Headers →', 'lazytasks-project-task-management')} <K>Authorization</K> = <K>Bearer YOUR_TOKEN</K></>,
                                <>{__('Request Body: Selected Fields → Field Name', 'lazytasks-project-task-management')} <K>title</K>, {__('Field Value: the form field to use as the task name. Add description, due_date and the others the same way.', 'lazytasks-project-task-management')}</>,
                                <>{__('Save Feed, submit the form once, and check the call log.', 'lazytasks-project-task-management')}</>,
                            ]} />
                        </Tabs.Panel>
                    </Tabs>
                    <Note>
                        {__('Using something else (Make, n8n, Pabbly, your own code)? Any tool that can send a POST with a custom header works.', 'lazytasks-project-task-management')}
                    </Note>
                </Step>

                <Step n={4} title={__('Check the result', 'lazytasks-project-task-management')} last>
                    {__('The reply says whether the task was created. Every call with a valid token is also listed in the webhook’s', 'lazytasks-project-task-management')}{' '}
                    <IconList size={14} style={{ verticalAlign: -2 }} /> <b>{__('Call log', 'lazytasks-project-task-management')}</b>{' '}
                    {__('— created or refused, with the reason and the first 2 KB of what was sent.', 'lazytasks-project-task-management')}
                </Step>
            </div>

            <SectionHeading>{__('Fields you can send', 'lazytasks-project-task-management')}</SectionHeading>
            <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 6 }}>
                <thead>
                    <tr>
                        <th style={tableHead}>{__('Field', 'lazytasks-project-task-management')}</th>
                        <th style={tableHead}>{__('Required', 'lazytasks-project-task-management')}</th>
                        <th style={tableHead}>{__('What it does', 'lazytasks-project-task-management')}</th>
                    </tr>
                </thead>
                <tbody>
                    {fields.map(([f, req, d]) => (
                        <tr key={f}><td style={tableCell}><K>{f}</K></td><td style={tableCell}>{req}</td><td style={tableCell}>{d}</td></tr>
                    ))}
                </tbody>
            </table>
            <div style={{ fontSize: 12, color: C.muted, marginBottom: 22 }}>
                {__('Anything else in the body is ignored, including a project or user — those always come from the webhook’s settings.', 'lazytasks-project-task-management')}
            </div>

            <SectionHeading>{__('Replies', 'lazytasks-project-task-management')}</SectionHeading>
            <Accordion multiple variant="separated" radius="md" chevronPosition="right">
                <Accordion.Item value="created">
                    <Accordion.Control><span style={{ fontSize: 13, fontWeight: 600 }}>{__('Task created (201)', 'lazytasks-project-task-management')}</span></Accordion.Control>
                    <Accordion.Panel>
                        <div style={{ fontSize: 12, color: C.muted, marginBottom: 8 }}>
                            {__('ref is the task’s serial number. warnings lists fields that were skipped; the task is still created.', 'lazytasks-project-task-management')}
                        </div>
                        <CopyBlock text={SUCCESS_REPLY} label={label('JSON')} />
                    </Accordion.Panel>
                </Accordion.Item>
                <Accordion.Item value="refused">
                    <Accordion.Control><span style={{ fontSize: 13, fontWeight: 600 }}>{__('Refused', 'lazytasks-project-task-management')} ({refusals.length})</span></Accordion.Control>
                    <Accordion.Panel>
                        <div style={{ fontSize: 12, color: C.muted, marginBottom: 8 }}>{__('No task is created. The reply looks like this:', 'lazytasks-project-task-management')}</div>
                        <CopyBlock text={REFUSED_REPLY} label={label('JSON')} />
                        <div style={{ overflowX: 'auto', marginTop: 12 }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 560 }}>
                                <thead>
                                    <tr>
                                        <th style={tableHead}>HTTP</th>
                                        <th style={tableHead}>code</th>
                                        <th style={tableHead}>{__('Why', 'lazytasks-project-task-management')}</th>
                                        <th style={tableHead}>{__('What to do', 'lazytasks-project-task-management')}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {refusals.map(([http, code, why, fix]) => (
                                        <tr key={code}><td style={tableCell}>{http}</td><td style={tableCell}><K>{code}</K></td><td style={tableCell}>{why}</td><td style={tableCell}>{fix}</td></tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </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>{__('Each call creates a new task.', 'lazytasks-project-task-management')}</b> {__('Sending the same request twice gives two tasks.', 'lazytasks-project-task-management')}</li>
                <li style={{ margin: '5px 0' }}><b>{__('Tasks behave like any other.', 'lazytasks-project-task-management')}</b> {__('They get a serial number and an activity entry, the assignee is notified, and outgoing webhooks for task.created fire.', 'lazytasks-project-task-management')}</li>
                <li style={{ margin: '5px 0' }}><b>{__('Up to 60 calls a minute', 'lazytasks-project-task-management')}</b> {__('per webhook, and the body can be up to 64 KB.', 'lazytasks-project-task-management')}</li>
                <li style={{ margin: '5px 0' }}><b>{__('Call log entries are kept for 30 days.', 'lazytasks-project-task-management')}</b></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>
    );
}
