import React, { useState, useEffect } from 'react';
import { __ } from '@/lib/i18n';
import { Shield, AlertTriangle, ExternalLink } from 'lucide-react';
import { SettingsLayout } from './components/SettingsLayout';
import { SettingsCard } from './components/SettingsCard';
import { ToggleField } from './components/ToggleField';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';

interface SecuritySettings {
    enable_checkout_rate_limit: boolean;
    rate_limit_orders: number;
    rate_limit_minutes: number;
    captcha_provider: 'none' | 'recaptcha' | 'turnstile';
    recaptcha_site_key: string;
    recaptcha_secret_key: string;
    turnstile_site_key: string;
    turnstile_secret_key: string;
}

export default function SecuritySettings() {
    const [settings, setSettings] = useState<SecuritySettings>({
        enable_checkout_rate_limit: true,
        rate_limit_orders: 5,
        rate_limit_minutes: 10,
        captcha_provider: 'none',
        recaptcha_site_key: '',
        recaptcha_secret_key: '',
        turnstile_site_key: '',
        turnstile_secret_key: '',
    });
    const [isLoading, setIsLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [message, setMessage] = useState('');

    useEffect(() => {
        fetchSettings();
    }, []);

    const fetchSettings = async () => {
        try {
            setIsLoading(true);
            const response = await fetch(
                `${(window as any).WNW_CONFIG?.restUrl || ''}/store/security-settings`,
                {
                    credentials: 'include',
                    headers: {
                        'X-WP-Nonce': (window as any).WNW_CONFIG?.nonce || (window as any).wpApiSettings?.nonce || '',
                    },
                }
            );

            if (!response.ok) throw new Error('Failed to fetch');
            const data = await response.json();
            setSettings(data);
        } catch (error) {
            console.error('Error:', error);
            setMessage('Failed to load settings');
        } finally {
            setIsLoading(false);
        }
    };

    const handleSave = async () => {
        try {
            setIsSaving(true);
            setMessage('');
            const response = await fetch(
                `${(window as any).WNW_CONFIG?.restUrl || ''}/store/security-settings`,
                {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': (window as any).WNW_CONFIG?.nonce || (window as any).wpApiSettings?.nonce || '',
                    },
                    body: JSON.stringify(settings),
                }
            );

            if (!response.ok) throw new Error('Failed to save');
            const data = await response.json();
            setMessage(data.message || 'Settings saved successfully');
            if (data.settings) setSettings(data.settings);
        } catch (error) {
            console.error('Error:', error);
            setMessage('Failed to save settings');
        } finally {
            setIsSaving(false);
        }
    };

    if (isLoading) {
        return (
            <SettingsLayout
                title={__('Security Settings')}
                description={__('Configure checkout security and spam protection')}
                isLoading={true}
            >
                <div className="animate-pulse h-64 bg-muted rounded-lg"></div>
            </SettingsLayout>
        );
    }

    return (
        <SettingsLayout
            title={__('Security Settings')}
            description={__('Configure checkout security and spam protection')}
            onSave={handleSave}
            saveLabel={__('Save Changes')}
        >
            {message && (
                <div className={`p-4 rounded-lg ${message.includes('success') ? 'bg-green-50 text-green-900' : 'bg-red-50 text-red-900'}`}>
                    {message}
                </div>
            )}

            {/* Rate Limiting */}
            <SettingsCard
                title={__('Rate Limiting')}
                description={__('Prevent order bombing by limiting orders per IP')}
            >
                <div className="space-y-6">
                    <ToggleField
                        id="enable_checkout_rate_limit"
                        label={__('Enable checkout rate limiting')}
                        description={__('Limit the number of orders that can be placed from a single IP address within a time window.')}
                        checked={settings.enable_checkout_rate_limit}
                        onCheckedChange={(checked) => setSettings({ ...settings, enable_checkout_rate_limit: checked })}
                    />

                    {settings.enable_checkout_rate_limit && (
                        <div className="grid grid-cols-2 gap-4 pl-6 border-l-2 border-muted">
                            <div className="space-y-2">
                                <Label htmlFor="rate_limit_orders">{__('Maximum orders')}</Label>
                                <Input
                                    id="rate_limit_orders"
                                    type="number"
                                    min={1}
                                    max={100}
                                    value={settings.rate_limit_orders}
                                    onChange={(e) => setSettings({ ...settings, rate_limit_orders: parseInt(e.target.value) || 5 })}
                                />
                                <p className="text-sm text-muted-foreground">
                                    {__('Number of orders allowed per IP')}
                                </p>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="rate_limit_minutes">{__('Time window (minutes)')}</Label>
                                <Input
                                    id="rate_limit_minutes"
                                    type="number"
                                    min={1}
                                    max={1440}
                                    value={settings.rate_limit_minutes}
                                    onChange={(e) => setSettings({ ...settings, rate_limit_minutes: parseInt(e.target.value) || 10 })}
                                />
                                <p className="text-sm text-muted-foreground">
                                    {__('Reset period in minutes')}
                                </p>
                            </div>
                        </div>
                    )}
                </div>
            </SettingsCard>

            {/* CAPTCHA */}
            <SettingsCard
                title={__('CAPTCHA Protection')}
                description={__('Add invisible bot protection to checkout')}
            >
                <div className="space-y-6">
                    <div className="flex gap-3 p-4 bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-900 rounded-lg">
                        <AlertTriangle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                        <div className="text-sm text-amber-900 dark:text-amber-100">
                            <p className="font-medium mb-1">{__('Invisible CAPTCHA')}</p>
                            <p className="text-amber-700 dark:text-amber-300">
                                {__('Both options use invisible verification - no user interaction required. They detect bots automatically in the background.')}
                            </p>
                        </div>
                    </div>

                    <RadioGroup
                        value={settings.captcha_provider}
                        onValueChange={(value: SecuritySettings['captcha_provider']) =>
                            setSettings({ ...settings, captcha_provider: value })
                        }
                        className="space-y-4"
                    >
                        <div className="flex items-start space-x-3">
                            <RadioGroupItem value="none" id="captcha_none" className="mt-1" />
                            <div>
                                <Label htmlFor="captcha_none" className="font-medium cursor-pointer">
                                    {__('None')}
                                </Label>
                                <p className="text-sm text-muted-foreground">
                                    {__('No CAPTCHA verification')}
                                </p>
                            </div>
                        </div>

                        <div className="flex items-start space-x-3">
                            <RadioGroupItem value="recaptcha" id="captcha_recaptcha" className="mt-1" />
                            <div className="flex-1">
                                <Label htmlFor="captcha_recaptcha" className="font-medium cursor-pointer">
                                    {__('Google reCAPTCHA v3')}
                                </Label>
                                <p className="text-sm text-muted-foreground mb-3">
                                    {__('Invisible verification by Google')}
                                    <a
                                        href="https://www.google.com/recaptcha/admin/create"
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="ml-2 text-primary hover:underline inline-flex items-center gap-1"
                                    >
                                        {__('Get API keys')} <ExternalLink className="w-3 h-3" />
                                    </a>
                                </p>

                                {settings.captcha_provider === 'recaptcha' && (
                                    <div className="space-y-4 pt-2">
                                        <div className="space-y-2">
                                            <Label htmlFor="recaptcha_site_key">{__('Site Key')}</Label>
                                            <Input
                                                id="recaptcha_site_key"
                                                type="text"
                                                placeholder="6Le..."
                                                value={settings.recaptcha_site_key}
                                                onChange={(e) => setSettings({ ...settings, recaptcha_site_key: e.target.value })}
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <Label htmlFor="recaptcha_secret_key">{__('Secret Key')}</Label>
                                            <Input
                                                id="recaptcha_secret_key"
                                                type="password"
                                                placeholder="6Le..."
                                                value={settings.recaptcha_secret_key}
                                                onChange={(e) => setSettings({ ...settings, recaptcha_secret_key: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>

                        <div className="flex items-start space-x-3">
                            <RadioGroupItem value="turnstile" id="captcha_turnstile" className="mt-1" />
                            <div className="flex-1">
                                <Label htmlFor="captcha_turnstile" className="font-medium cursor-pointer">
                                    {__('Cloudflare Turnstile')}
                                </Label>
                                <p className="text-sm text-muted-foreground mb-3">
                                    {__('Privacy-focused invisible verification by Cloudflare')}
                                    <a
                                        href="https://dash.cloudflare.com/?to=/:account/turnstile"
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="ml-2 text-primary hover:underline inline-flex items-center gap-1"
                                    >
                                        {__('Get API keys')} <ExternalLink className="w-3 h-3" />
                                    </a>
                                </p>

                                {settings.captcha_provider === 'turnstile' && (
                                    <div className="space-y-4 pt-2">
                                        <div className="space-y-2">
                                            <Label htmlFor="turnstile_site_key">{__('Site Key')}</Label>
                                            <Input
                                                id="turnstile_site_key"
                                                type="text"
                                                placeholder="0x..."
                                                value={settings.turnstile_site_key}
                                                onChange={(e) => setSettings({ ...settings, turnstile_site_key: e.target.value })}
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <Label htmlFor="turnstile_secret_key">{__('Secret Key')}</Label>
                                            <Input
                                                id="turnstile_secret_key"
                                                type="password"
                                                placeholder="0x..."
                                                value={settings.turnstile_secret_key}
                                                onChange={(e) => setSettings({ ...settings, turnstile_secret_key: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </RadioGroup>
                </div>
            </SettingsCard>
        </SettingsLayout>
    );
}
