/**
 * Settings Component — shadcn/ui styled
 */

import { useState, useEffect } from 'react';
import {
    getApiBaseUrl,
    setApiBaseUrl,
    getAuthStatus,
    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 [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(/\/+$/, '');
        await setApiBaseUrl(cleaned);
        setServerUrl(cleaned);
        setSaved(true);
        setTestResult(null);
        setTimeout(() => setSaved(false), 2000);
    };

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

    return (
        <div className="content">
            {/* Server */}
            <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="http://172.16.2.210:5230"
                        />
                        <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: '6px' }}>
                    <button
                        className="btn btn-secondary btn-sm btn-full"
                        onClick={handleTestConnection}
                        disabled={testing}
                    >
                        {testing ? (
                            <>
                                <span className="spinner" style={{ width: 12, height: 12 }} /> Testing...
                            </>
                        ) : (
                            'Test Connection'
                        )}
                    </button>
                </div>

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

            {/* Auth Status */}
            <div className="settings-section">
                <div className="settings-title">Authentication</div>
                <div className="settings-item">
                    <div>
                        <div className="settings-item-label">Memos Access Token</div>
                        <div className="settings-item-desc">Auto-synced from Canifa Note tab</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>

            {/* About */}
            <div className="settings-section">
                <div className="settings-title">About</div>
                <div style={{ fontSize: '12px', color: 'var(--muted-foreground)', lineHeight: '1.6' }}>
                    <strong>Canifa Note</strong> v1.0.0
                    <br />
                    Ghi chú nhanh từ bất kỳ trang web nào.
                    <br />
                    Bôi đen → Nhấn Space → Lưu tự động
                </div>
            </div>
        </div>
    );
}
