import React, { useState, useEffect } from 'react';
import { Card, Input, Button, Typography, message, Alert } from 'antd';
import { BellOutlined, ApiOutlined } from '@ant-design/icons';

const { Text, Paragraph } = Typography;

const WebhookSettings = () => {
    const [webhookUrl, setWebhookUrl] = useState('');
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        fetchWebhook();
    }, []);

    const fetchWebhook = async () => {
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/security-features/webhook`, {
                headers: { 'X-WP-Nonce': window.wpApiSettings.nonce }
            });
            const data = await response.json();
            if (response.ok) {
                setWebhookUrl(data.url || '');
            }
        } catch (error) {
            console.error('Error fetching webhook:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSave = async () => {
        // Basic validation
        if (webhookUrl && !webhookUrl.startsWith('http')) {
            message.error('Please enter a valid URL');
            return;
        }

        setSaving(true);
        try {
            const response = await fetch(`${window.wpApiSettings.root}safe-sites/v1/security-features/webhook`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.wpApiSettings.nonce
                },
                body: JSON.stringify({ url: webhookUrl })
            });
            const data = await response.json();

            if (response.ok && data.success) {
                message.success(data.message);
                // URL might be updated/sanitized by backend
                if (data.url !== undefined) setWebhookUrl(data.url);
            } else {
                throw new Error(data.message || 'Failed to save');
            }
        } catch (error) {
            message.error(error.message);
        } finally {
            setSaving(false);
        }
    };

    return (
        <Card
            title={<span><BellOutlined /> Security Notifications</span>}
            loading={loading}
            className="webhook-card"
        >
            <Alert
                message="Receive instant alerts on Discord or Slack when file tampering is detected."
                type="info"
                showIcon
                style={{ marginBottom: 16 }}
            />

            <div style={{ marginBottom: 16 }}>
                <Text strong>Webhook URL</Text>
                <Input
                    placeholder="https://discord.com/api/webhooks/..."
                    prefix={<ApiOutlined />}
                    value={webhookUrl}
                    onChange={(e) => setWebhookUrl(e.target.value)}
                    style={{ marginTop: 8 }}
                />
            </div>

            <Button type="primary" onClick={handleSave} loading={saving}>
                Save & Test
            </Button>

            {!webhookUrl && (
                <div style={{ marginTop: 12 }}>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                        Leave empty to disable.
                    </Text>
                </div>
            )}
        </Card>
    );
};

export default WebhookSettings;
