/**
 * Settings Component
 * Server URL config, auth sync, connection test
 */

import { useState, useEffect } from 'react';
import {
    getApiBaseUrl,
    setApiBaseUrl,
    getAuthStatus,
    syncClerkTokenFromPage,
    testConnection,
} from '../shared/api-client';

export function Settings() {
    const [serverUrl, setServerUrl] = useState('');
    const [authStatus, setAuthStatus] = useState<{ isConnected: boolean; tokenLength: number }>({
        isConnected: false,
        tokenLength: 0,
    });
    const [testResult, setTestResult] = useState<{ ok: boolean; message: string } | null>(null);
    const [syncing, setSyncing] = useState(false);
    const [testing, setTesting] = useState(false);
    const [saved, setSaved] = useState(false);

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

    const loadSettings = async () => {
        const url = await getApiBaseUrl();
        setServerUrl(url);
        const status = await getAuthStatus();
        setAuthStatus(status);
    };

    const handleSaveUrl = async () => {
        const cleaned = serverUrl.trim().replace(/\/+$/, ''); // remove trailing slashes
        await setApiBaseUrl(cleaned);
        setServerUrl(cleaned);
        setSaved(true);
        setTestResult(null);
        setTimeout(() => setSaved(false), 2000);
    };

    const handleSyncAuth = async () => {
        setSyncing(true);
        try {
            const token = await syncClerkTokenFromPage();
            if (token) {
                setAuthStatus({ isConnected: true, tokenLength: token.length });
            } else {
                setAuthStatus({ isConnected: false, tokenLength: 0 });
            }
        } catch {
            setAuthStatus({ isConnected: false, tokenLength: 0 });
        }
        setSyncing(false);
    };

    const handleTestConnection = async () => {
        setTesting(true);
        setTestResult(null);
        const result = await testConnection();
        setTestResult(result);
        setTesting(false);
    };

    return (
        <div className="content">
            {/* Server URL */}
            <div className="settings-section">
                <div className="settings-title">🌐 Server</div>

                <div className="form-group">
                    <label className="label">API URL</label>
                    <div className="settings-input-group">
                        <input
                            type="url"
                            className="input"
                            value={serverUrl}
                            onChange={(e) => {
                                setServerUrl(e.target.value);
                                setSaved(false);
                                setTestResult(null);
                            }}
                            placeholder="https://your-domain.com"
                        />
                        <button className="btn btn-primary btn-sm" onClick={handleSaveUrl}>
                            {saved ? '✓' : 'Save'}
                        </button>
                    </div>
                    <div className="label-hint">
                        Backend server URL (without /api/v1)
                    </div>
                </div>

                <div style={{ marginTop: '8px' }}>
                    <button
                        className="btn btn-secondary btn-sm btn-full"
                        onClick={handleTestConnection}
                        disabled={testing}
                    >
                        {testing ? (
                            <>
                                <span className="spinner" /> Testing...
                            </>
                        ) : (
                            '🔌 Test Connection'
                        )}
                    </button>
                </div>

                {testResult && (
                    <div
                        className={testResult.ok ? 'success' : 'error'}
                        style={{ marginTop: '8px' }}
                    >
                        {testResult.message}
                    </div>
                )}
            </div>

            {/* Auth */}
            <div className="settings-section">
                <div className="settings-title">🔑 Authentication</div>

                <div className="settings-item">
                    <div>
                        <div className="settings-item-label">Clerk Session</div>
                        <div className="settings-item-desc">
                            Sync auth from your OpenNotion app
                        </div>
                    </div>
                    <span className={`badge ${authStatus.isConnected ? 'badge-success' : 'badge-error'}`}>
                        <span
                            className={`status-dot ${authStatus.isConnected ? 'connected' : 'disconnected'}`}
                        />
                        {authStatus.isConnected ? 'Active' : 'Inactive'}
                    </span>
                </div>

                <div style={{ marginTop: '8px' }}>
                    <button
                        className="btn btn-secondary btn-sm btn-full"
                        onClick={handleSyncAuth}
                        disabled={syncing}
                    >
                        {syncing ? (
                            <>
                                <span className="spinner" /> Syncing...
                            </>
                        ) : (
                            '🔄 Sync Auth from Current Page'
                        )}
                    </button>
                    <div className="label-hint" style={{ marginTop: '6px' }}>
                        Open your OpenNotion app first, then click sync
                    </div>
                </div>
            </div>

            {/* About */}
            <div className="settings-section">
                <div className="settings-title">ℹ️ About</div>
                <div
                    style={{
                        fontSize: '12px',
                        color: 'var(--muted-foreground)',
                        lineHeight: '1.6',
                    }}
                >
                    <strong>CuCu Note</strong> v1.0.0
                    <br />
                    Quick note-taking from any web page.
                    <br />
                    Highlight text → Press Space → Auto save!
                </div>
            </div>
        </div>
    );
}
