import React, { useEffect, useRef, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Modal, Switch, Loader, Tooltip } from '@mantine/core';
import { showNotification } from '@mantine/notifications';
import { IconCheck, IconCopy } from '@tabler/icons-react';
import { copyToClipboard } from '../../../utils/copyText';

// Look and building blocks shared by the outgoing and incoming webhook screens.

export const T = {
    orange: '#ED7D31', orangeDk: '#D46A1E',
    teal: '#39758D', tealLt: '#EBF1F4', tealDk: '#2C5C6E',
    border: '#E2E8F0', text: '#1A202C', muted: '#64748B', light: '#94A3B8',
    successLt: '#D1FAE5', successDk: '#065F46',
    dangerLt: '#FEE2E2', dangerDk: '#991B1B', danger: '#EF4444',
    warningLt: '#FEF3C7', warningDk: '#92400E',
    infoLt: '#E0F2FE', infoDk: '#075985',
    radius: 12, radiusSm: 6,
    shadow: '0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.05)',
    mono: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
};

export const formatTime = (iso) => {
    if (!iso) return '';
    const d = new Date(iso);
    return Number.isNaN(d.getTime()) ? '' : d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
};

export const statusLabel = (status) => ({
    active: __('Active', 'lazytasks-project-task-management'),
    inactive: __('Inactive', 'lazytasks-project-task-management'),
    disabled: __('Disabled', 'lazytasks-project-task-management'),
    pending: __('Pending', 'lazytasks-project-task-management'),
    processing: __('Sending', 'lazytasks-project-task-management'),
    retrying: __('Retrying', 'lazytasks-project-task-management'),
    succeeded: __('Succeeded', 'lazytasks-project-task-management'),
    failed: __('Failed', 'lazytasks-project-task-management'),
    created: __('Created', 'lazytasks-project-task-management'),
    rejected: __('Refused', 'lazytasks-project-task-management'),
}[status] || status);

export const BADGE = {
    active: [T.successLt, T.successDk], succeeded: [T.successLt, T.successDk],
    inactive: ['#F1F5F9', T.muted],
    disabled: [T.dangerLt, T.dangerDk], failed: [T.dangerLt, T.dangerDk],
    pending: [T.warningLt, T.warningDk], processing: [T.warningLt, T.warningDk], retrying: [T.warningLt, T.warningDk],
    created: [T.successLt, T.successDk], rejected: [T.dangerLt, T.dangerDk], warning: [T.warningLt, T.warningDk],
};

export function Badge({ status, children }) {
    const [bg, fg] = BADGE[status] || BADGE.inactive;
    return (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 600, padding: '2px 9px', borderRadius: 10, background: bg, color: fg, whiteSpace: 'nowrap' }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: fg }} />
            {children || statusLabel(status)}
        </span>
    );
}

export function Btn({ children, variant = 'primary', loading, disabled, style, ...props }) {
    const variants = {
        primary: { background: T.orange, color: '#fff', border: '1px solid transparent' },
        default: { background: '#fff', color: T.text, border: `1px solid ${T.border}` },
        danger: { background: T.danger, color: '#fff', border: '1px solid transparent' },
    };
    const off = disabled || loading;
    return (
        <button
            type="button"
            disabled={off}
            style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, height: 34, padding: '0 14px',
                borderRadius: T.radiusSm, fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
                cursor: off ? 'not-allowed' : 'pointer', opacity: off ? 0.6 : 1, whiteSpace: 'nowrap',
                ...variants[variant], ...style,
            }}
            {...props}
        >
            {loading && <Loader size={12} color="currentColor" />}
            {children}
        </button>
    );
}

export function IconBtn({ label, onClick, children }) {
    return (
        <Tooltip label={label} withArrow openDelay={300}>
            <button
                type="button"
                aria-label={label}
                onClick={onClick}
                style={{ width: 28, height: 28, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none', borderRadius: T.radiusSm, color: T.muted, cursor: 'pointer' }}
                onMouseEnter={e => { e.currentTarget.style.background = T.tealLt; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'none'; }}
            >
                {children}
            </button>
        </Tooltip>
    );
}

export function Alert({ tone = 'warn', icon, children, style }) {
    const tones = { warn: [T.warningLt, T.warningDk], ok: [T.successLt, T.successDk], bad: [T.dangerLt, T.dangerDk], info: [T.infoLt, T.infoDk] };
    const [bg, fg] = tones[tone];
    return (
        <div style={{ display: 'flex', gap: 8, padding: '9px 12px', borderRadius: T.radiusSm, fontSize: 13, background: bg, color: fg, ...style }}>
            {icon && <span style={{ flexShrink: 0, marginTop: 2 }}>{icon}</span>}
            <div style={{ minWidth: 0 }}>{children}</div>
        </div>
    );
}

export function Code({ children }) {
    return (
        <pre style={{ background: '#0F172A', color: '#E2E8F0', fontFamily: T.mono, fontSize: 12, padding: '10px 12px', borderRadius: T.radiusSm, overflow: 'auto', maxHeight: 260, whiteSpace: 'pre', margin: 0 }}>
            {children}
        </pre>
    );
}

export const FieldLabel = ({ children, style }) => (
    <div style={{ fontSize: 13, fontWeight: 600, color: T.text, marginBottom: 5, ...style }}>{children}</div>
);

export function SwitchRow({ label, hint, checked, onChange }) {
    return (
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, alignItems: 'flex-start', padding: '10px 0', borderTop: `1px solid ${T.border}` }}>
            <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{label}</div>
                <div style={{ fontSize: 12, color: T.muted }}>{hint}</div>
            </div>
            <Switch color={T.teal} checked={checked} onChange={e => onChange(e.currentTarget.checked)} aria-label={label} />
        </div>
    );
}

export function ConfirmModal({ confirm, onClose }) {
    const [busy, setBusy] = useState(false);
    if (!confirm) return null;
    const run = async () => {
        setBusy(true);
        try { await confirm.onConfirm(); } finally { setBusy(false); }
    };
    return (
        <Modal opened onClose={onClose} title={<span style={{ fontWeight: 700 }}>{confirm.title}</span>} centered size="md">
            <div style={{ fontSize: 13 }}>{confirm.body}</div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 18 }}>
                <Btn variant="default" onClick={onClose}>{__('Cancel', 'lazytasks-project-task-management')}</Btn>
                <Btn variant={confirm.danger ? 'danger' : 'primary'} loading={busy} onClick={run}>{confirm.action}</Btn>
            </div>
        </Modal>
    );
}

// A dark box with a value and a Copy button. Falls back to copying from the visible
// text when the helper's off-screen textarea can't take focus, which happens inside
// a modal's focus trap on plain-http sites.
export function CopyBox({ value, label, failMessage }) {
    const [copied, setCopied] = useState(false);
    const ref = useRef(null);
    useEffect(() => { setCopied(false); }, [value]);

    const copyFromSelection = () => {
        const node = ref.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(value)) || copyFromSelection();
        if (ok) {
            setCopied(true);
        } else {
            showNotification({ title: __('Copy failed', 'lazytasks-project-task-management'), message: failMessage || __('Select the text and copy it by hand.', 'lazytasks-project-task-management'), color: 'red' });
        }
    };

    return (
        <div style={{ display: 'flex', gap: 6, alignItems: 'center', background: '#0F172A', color: '#E2E8F0', borderRadius: T.radiusSm, padding: '10px 12px', fontFamily: T.mono, fontSize: 12.5, wordBreak: 'break-all' }}>
            <span ref={ref} style={{ flex: 1, userSelect: 'all', whiteSpace: 'pre-wrap' }}>{value}</span>
            <Btn variant="default" aria-label={label} style={{ height: 28, fontSize: 12, padding: '0 10px', alignSelf: 'flex-start' }} onClick={copy}>
                {copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
                {copied ? __('Copied', 'lazytasks-project-task-management') : __('Copy', 'lazytasks-project-task-management')}
            </Btn>
        </div>
    );
}
