import { useState, useEffect } from '@wordpress/element';
import api from '../utils/api';

const { __ } = wp.i18n;

const providerIcons = {
    openai: (
        <svg fill="currentColor" fillRule="evenodd" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg">
            <path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z" />
        </svg>
    ),
    google: (
        <svg height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg">
            <path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF" />
            <path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#gemini-settings-grad-0)" />
            <path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#gemini-settings-grad-1)" />
            <path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#gemini-settings-grad-2)" />
            <defs>
                <linearGradient gradientUnits="userSpaceOnUse" id="gemini-settings-grad-0" x1="7" x2="11" y1="15.5" y2="12">
                    <stop stopColor="#08B962" />
                    <stop offset="1" stopColor="#08B962" stopOpacity="0" />
                </linearGradient>
                <linearGradient gradientUnits="userSpaceOnUse" id="gemini-settings-grad-1" x1="8" x2="11.5" y1="5.5" y2="11">
                    <stop stopColor="#F94543" />
                    <stop offset="1" stopColor="#F94543" stopOpacity="0" />
                </linearGradient>
                <linearGradient gradientUnits="userSpaceOnUse" id="gemini-settings-grad-2" x1="3.5" x2="17.5" y1="13.5" y2="12">
                    <stop stopColor="#FABC12" />
                    <stop offset=".46" stopColor="#FABC12" stopOpacity="0" />
                </linearGradient>
            </defs>
        </svg>
    ),
    grok: (
        <svg fill="currentColor" fillRule="evenodd" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg">
            <path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815" />
        </svg>
    ),
    deepseek: (
        <svg height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg">
            <path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE" />
        </svg>
    ),
};

export default function Settings() {
    const [settings, setSettings] = useState({
        openai_api_key: '',
        google_api_key: '',
        grok_api_key: '',
        deepseek_api_key: '',
        default_post_status: 'publish',
        default_post_type: 'post',
        log_retention: 90,
    });
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [notification, setNotification] = useState(null);
    const [validating, setValidating] = useState({});

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

    const loadSettings = async () => {
        try {
            const data = await api.getSettings();
            setSettings((prev) => ({ ...prev, ...data }));
        } catch (err) {
            setNotification({ message: err.message, type: 'error' });
        } finally {
            setLoading(false);
        }
    };

    const handleSave = async () => {
        setSaving(true);
        setNotification(null);
        try {
            await api.saveSettings(settings);
            setNotification({
                message: AIBulkPost.i18n.saved,
                type: 'success',
            });
        } catch (err) {
            setNotification({ message: err.message, type: 'error' });
        } finally {
            setSaving(false);
        }
    };

    const handleValidate = async (provider) => {
        const keyField = `${provider}_api_key`;
        const apiKey = settings[keyField];

        if (!apiKey || apiKey.startsWith('***')) {
            setNotification({
                message: __('Please enter a new API key first.', 'ai-bulk-post'),
                type: 'error',
            });
            return;
        }

        setValidating((prev) => ({ ...prev, [provider]: true }));
        try {
            const result = await api.validateKey(provider, apiKey);
            if (result.valid) {
                const toSave = { ...settings };
                Object.keys(toSave).forEach((key) => {
                    if (typeof toSave[key] === 'string' && toSave[key].startsWith('***')) {
                        delete toSave[key];
                    }
                });
                await api.saveSettings(toSave);
                setNotification({
                    message: __('API key is valid and saved.', 'ai-bulk-post'),
                    type: 'success',
                });
            } else {
                setNotification({
                    message: __('API key is invalid.', 'ai-bulk-post'),
                    type: 'error',
                });
            }
        } catch (err) {
            setNotification({ message: err.message, type: 'error' });
        } finally {
            setValidating((prev) => ({ ...prev, [provider]: false }));
        }
    };

    const providers = [
        {
            id: 'openai',
            name: 'OpenAI',
            keyField: 'openai_api_key',
            url: 'https://platform.openai.com/api-keys',
        },
        {
            id: 'google',
            name: 'Google Gemini',
            keyField: 'google_api_key',
            url: 'https://aistudio.google.com/app/apikey',
        },
        {
            id: 'grok',
            name: 'Grok (xAI)',
            keyField: 'grok_api_key',
            url: 'https://console.x.ai',
        },
        {
            id: 'deepseek',
            name: 'DeepSeek',
            keyField: 'deepseek_api_key',
            url: 'https://platform.deepseek.com/api_keys',
        },
    ];

    if (loading) {
        return (
            <div className="aibp-loading">
                <span className="spinner is-active"></span>
                {__('Loading settings...', 'ai-bulk-post')}
            </div>
        );
    }

    return (
        <div className="aibp-settings">
            {notification && (
                <div className={`aibp-notice aibp-notice-${notification.type}`}>
                    {notification.message}
                </div>
            )}

            <h1>{__('Settings', 'ai-bulk-post')}</h1>

            {providers.map((provider) => (
                <div key={provider.id} className="aibp-settings-card">
                    <h2 className="aibp-settings-provider-heading">
                        <span className="aibp-settings-provider-icon">
                            {providerIcons[provider.id]}
                        </span>
                        {provider.name}
                    </h2>
                    <div className="aibp-settings-field">
                        <label htmlFor={provider.keyField}>
                            {__('API Key', 'ai-bulk-post')}
                        </label>
                        <div className="aibp-settings-input-row">
                            <input
                                id={provider.keyField}
                                type="password"
                                value={settings[provider.keyField] || ''}
                                onChange={(e) =>
                                    setSettings((prev) => ({
                                        ...prev,
                                        [provider.keyField]: e.target.value,
                                    }))
                                }
                                className="regular-text"
                                placeholder={__('Enter API key', 'ai-bulk-post')}
                            />
                            <button
                                className="button"
                                onClick={() => handleValidate(provider.id)}
                                disabled={validating[provider.id]}
                            >
                                {validating[provider.id]
                                    ? __('Validating...', 'ai-bulk-post')
                                    : __('Verify', 'ai-bulk-post')}
                            </button>
                        </div>
                        <p className="description">
                            {__('Get your key at', 'ai-bulk-post')}{' '}
                            <a href={provider.url} target="_blank" rel="noopener noreferrer">
                                {provider.url}
                            </a>
                        </p>
                    </div>
                </div>
            ))}

            <div className="aibp-settings-card">
                <h2>{__('General', 'ai-bulk-post')}</h2>

                <div className="aibp-settings-field">
                    <label htmlFor="default_post_status">
                        {__('Default Post Status', 'ai-bulk-post')}
                    </label>
                    <select
                        id="default_post_status"
                        value={settings.default_post_status}
                        onChange={(e) =>
                            setSettings((prev) => ({
                                ...prev,
                                default_post_status: e.target.value,
                            }))
                        }
                    >
                        <option value="publish">{__('Publish', 'ai-bulk-post')}</option>
                        <option value="draft">{__('Draft', 'ai-bulk-post')}</option>
                        <option value="pending">{__('Pending Review', 'ai-bulk-post')}</option>
                    </select>
                </div>

                <div className="aibp-settings-field">
                    <label htmlFor="log_retention">
                        {__('Log Retention (days)', 'ai-bulk-post')}
                    </label>
                    <input
                        id="log_retention"
                        type="number"
                        min="7"
                        max="365"
                        value={settings.log_retention}
                        onChange={(e) =>
                            setSettings((prev) => ({
                                ...prev,
                                log_retention: parseInt(e.target.value, 10),
                            }))
                        }
                        className="small-text"
                    />
                </div>
            </div>

            <div className="aibp-settings-actions">
                <button
                    className="button button-primary"
                    onClick={handleSave}
                    disabled={saving}
                >
                    {saving
                        ? __('Saving...', 'ai-bulk-post')
                        : __('Save Settings', 'ai-bulk-post')}
                </button>
            </div>
        </div>
    );
}
