import { useState, useEffect } from 'react';
import { useAuth } from '../components/AuthContext';
import type { BotState } from '../hooks/useWebSocket';
import { updateCurrentUserProfile } from '../lib/profileApi';

interface SettingsTabProps {
    botState: BotState;
}

export interface SettingsFormData {
    first_name: string;
    last_name: string;
    ALPACA_API_KEY: string;
    ALPACA_SECRET_KEY: string;
    REAL_ALPACA_API_KEY: string;
    REAL_ALPACA_SECRET_KEY: string;
    trade_enable: boolean;
    drop_threshold_for_buy: string;
    gain_threshold_for_sell: string;
    market_poll_interval_in_seconds: string;
}

export const DEFAULT_SETTINGS_FORM_DATA: SettingsFormData = {
    first_name: '',
    last_name: '',
    ALPACA_API_KEY: '',
    ALPACA_SECRET_KEY: '',
    REAL_ALPACA_API_KEY: '',
    REAL_ALPACA_SECRET_KEY: '',
    trade_enable: false,
    drop_threshold_for_buy: '0.02',
    gain_threshold_for_sell: '0.01',
    market_poll_interval_in_seconds: '60000',
};

export const mapProfileToFormData = (profile?: any): SettingsFormData => ({
    first_name: profile?.first_name || '',
    last_name: profile?.last_name || '',
    ALPACA_API_KEY: profile?.ALPACA_API_KEY || '',
    ALPACA_SECRET_KEY: profile?.ALPACA_SECRET_KEY || '',
    REAL_ALPACA_API_KEY: profile?.REAL_ALPACA_API_KEY || '',
    REAL_ALPACA_SECRET_KEY: profile?.REAL_ALPACA_SECRET_KEY || '',
    trade_enable: profile?.trade_enable ?? false,
    drop_threshold_for_buy: String(profile?.drop_threshold_for_buy || '0.02'),
    gain_threshold_for_sell: String(profile?.gain_threshold_for_sell || '0.01'),
    market_poll_interval_in_seconds: String(profile?.market_poll_interval_in_seconds || '60000'),
});

export const parseNumericSettings = (formData: SettingsFormData) => {
    const buyThreshold = parseFloat(formData.drop_threshold_for_buy);
    const sellThreshold = parseFloat(formData.gain_threshold_for_sell);
    const interval = parseInt(formData.market_poll_interval_in_seconds);

    if (isNaN(buyThreshold) || isNaN(sellThreshold) || isNaN(interval)) {
        throw new Error('Please enter valid numbers for thresholds and interval.');
    }

    return { buyThreshold, sellThreshold, interval };
};

export const SettingsTab = ({ botState }: SettingsTabProps) => {
    const { user, profile, refreshProfile } = useAuth();
    const { settings } = botState;
    const [editing, setEditing] = useState(false);
    const [saving, setSaving] = useState(false);

    // Form State
    const [formData, setFormData] = useState<SettingsFormData>(DEFAULT_SETTINGS_FORM_DATA);

    useEffect(() => {
        // Only initialize form data if we have a profile and we are NOT currently editing
        // This prevents the form from "vanishing" while the user is typing if profile refreshes
        if (profile && !editing) {
            setFormData(mapProfileToFormData(profile));
        }
    }, [profile, editing]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value, type, checked } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

    const handleSave = async () => {
        if (!user) return;
        setSaving(true);
        try {
            const { buyThreshold, sellThreshold, interval } = parseNumericSettings(formData);

            await updateCurrentUserProfile({
                first_name: formData.first_name,
                last_name: formData.last_name,
                ALPACA_API_KEY: formData.ALPACA_API_KEY,
                ALPACA_SECRET_KEY: formData.ALPACA_SECRET_KEY,
                REAL_ALPACA_API_KEY: formData.REAL_ALPACA_API_KEY,
                REAL_ALPACA_SECRET_KEY: formData.REAL_ALPACA_SECRET_KEY,
                trade_enable: formData.trade_enable,
                drop_threshold_for_buy: buyThreshold,
                gain_threshold_for_sell: sellThreshold,
                market_poll_interval_in_seconds: interval,
            });

            await refreshProfile();
            setEditing(false);
            alert('Settings saved successfully!');
        } catch (err: any) {
            alert('Error saving settings: ' + err.message);
        } finally {
            setSaving(false);
        }
    };

    return (
        <div className="settings-tab">
            <div className="tab-header">
                <h2>Settings & Configuration</h2>
                <p>Manage your account, API keys, and global bot parameters.</p>
            </div>

            <div className="settings-grid">
                {/* User Configuration Section */}
                <section className="settings-group" style={{ gridColumn: '1 / -1' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px' }}>
                        <h3>User Configuration</h3>
                        {!editing ? (
                            <button onClick={() => setEditing(true)} className="primary-button">Edit Configuration</button>
                        ) : (
                            <div style={{ display: 'flex', gap: '10px' }}>
                                <button onClick={() => setEditing(false)} className="secondary-button" disabled={saving}>Cancel</button>
                                <button onClick={handleSave} className="primary-button" disabled={saving}>
                                    {saving ? 'Saving...' : 'Save Changes'}
                                </button>
                            </div>
                        )}
                    </div>

                    <div className="form-grid">
                        <div className="form-group">
                            <label>First Name</label>
                            <input
                                name="first_name"
                                value={formData.first_name}
                                onChange={handleChange}
                                disabled={!editing}
                            />
                        </div>
                        <div className="form-group">
                            <label>Last Name</label>
                            <input
                                name="last_name"
                                value={formData.last_name}
                                onChange={handleChange}
                                disabled={!editing}
                            />
                        </div>

                        <div className="form-group">
                            <label>Your Role</label>
                            <input
                                value={profile?.role || 'user'}
                                disabled={true}
                                style={{ background: 'rgba(255, 255, 255, 0.02)', color: '#888', fontStyle: 'italic' }}
                            />
                        </div>

                        <div className="form-group">
                            <label>Trading Enabled</label>
                            <div className="toggle-wrapper">
                                <input
                                    type="checkbox"
                                    name="trade_enable"
                                    checked={formData.trade_enable}
                                    onChange={handleChange}
                                    disabled={!editing}
                                />
                                <span className="toggle-label" style={{ color: formData.trade_enable ? '#00ff88' : '#ff3366' }}>
                                    {formData.trade_enable ? 'Enabled' : 'Disabled'}
                                </span>
                            </div>
                        </div>

                        {/* Threshold Settings */}
                        <div className="form-group">
                            <label>Buy Threshold (e.g. 0.02 for 2%)</label>
                            <input
                                name="drop_threshold_for_buy"
                                value={formData.drop_threshold_for_buy}
                                onChange={handleChange}
                                disabled={!editing}
                                placeholder="0.02"
                            />
                        </div>
                        <div className="form-group">
                            <label>Sell Threshold (e.g. 0.01 for 1%)</label>
                            <input
                                name="gain_threshold_for_sell"
                                value={formData.gain_threshold_for_sell}
                                onChange={handleChange}
                                disabled={!editing}
                                placeholder="0.01"
                            />
                        </div>

                        <div className="form-group">
                            <label>Market Poll Interval (ms)</label>
                            <input
                                name="market_poll_interval_in_seconds"
                                value={formData.market_poll_interval_in_seconds}
                                onChange={handleChange}
                                disabled={!editing}
                            />
                        </div>

                        {/* Break */}
                        <div className="form-group full-width" style={{ marginTop: '10px', opacity: 0.5 }}>
                            <hr style={{ border: '0', borderTop: '1px solid rgba(255,255,255,0.1)' }} />
                            <small>Alpaca Credentials</small>
                        </div>

                        <div className="form-group full-width">
                            <label>Paper ALPACA API Key</label>
                            <input
                                name="ALPACA_API_KEY"
                                value={formData.ALPACA_API_KEY}
                                onChange={handleChange}
                                disabled={!editing}
                                type="password"
                            />
                        </div>
                        <div className="form-group full-width">
                            <label>Paper ALPACA Secret Key</label>
                            <input
                                name="ALPACA_SECRET_KEY"
                                value={formData.ALPACA_SECRET_KEY}
                                onChange={handleChange}
                                disabled={!editing}
                                type="password"
                            />
                        </div>

                        <div className="form-group full-width">
                            <label>Real ALPACA API Key</label>
                            <input
                                name="REAL_ALPACA_API_KEY"
                                value={formData.REAL_ALPACA_API_KEY}
                                onChange={handleChange}
                                disabled={!editing}
                                type="password"
                            />
                        </div>
                        <div className="form-group full-width">
                            <label>Real ALPACA Secret Key</label>
                            <input
                                name="REAL_ALPACA_SECRET_KEY"
                                value={formData.REAL_ALPACA_SECRET_KEY}
                                onChange={handleChange}
                                disabled={!editing}
                                type="password"
                            />
                        </div>
                    </div>
                </section>

                {/* Legacy Bot Status (Read Only) */}
                <section className="settings-group">
                    <h3>Bot Internal Status (WebSocket)</h3>
                    <div className="control-card">
                        <div className="status-indicator">
                            <div className={`dot ${settings.isAlgoEnabled ? 'active' : ''}`}></div>
                            <span>Algorithm: {settings.isAlgoEnabled ? 'ENABLED' : 'PAUSED'}</span>
                        </div>
                        <div className="var"><code>Mode</code>: {settings.executionMode}</div>
                        <div className="var"><code>Risk</code>: {(settings.riskPerTrade * 100).toFixed(1)}%</div>
                    </div>
                </section>
            </div>

            <style>{`
                .primary-button {
                    background: #00ff88;
                    color: #000;
                    border: none;
                    padding: 8px 16px;
                    border-radius: 6px;
                    font-weight: bold;
                    cursor: pointer;
                }
                .secondary-button {
                    background: transparent;
                    color: #ccc;
                    border: 1px solid #ccc;
                    padding: 8px 16px;
                    border-radius: 6px;
                    cursor: pointer;
                }
                .form-grid {
                    display: grid;
                    grid-template-columns: 1fr 1fr;
                    gap: 20px;
                }
                .full-width {
                    grid-column: 1 / -1;
                }
                .form-group {
                    display: flex;
                    flex-direction: column;
                    gap: 8px;
                }
                .form-group label {
                    color: #929292;
                    font-size: 0.85rem;
                }
                .form-group input {
                    background: rgba(255, 255, 255, 0.05);
                    border: 1px solid rgba(255, 255, 255, 0.1);
                    padding: 10px;
                    border-radius: 6px;
                    color: #fff;
                    font-family: monospace;
                }
                .form-group input:disabled {
                    opacity: 0.6;
                    cursor: not-allowed;
                }
                .toggle-wrapper {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    height: 40px;
                }
            `}</style>
        </div>
    );
};
