import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useAuth } from '../hooks/useAuth'
import { useAudio } from '../contexts/AudioContext'
import { authApi, Account } from '../services/api'
import { GameButton } from './common/GameButton'
import './AccountPage.css'

function AccountPage() {
    const { t } = useTranslation()
    const navigate = useNavigate()
    const { currentCharacter } = useAuth()
    const [account, setAccount] = useState<Account | null>(null)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState('')

    // Tab State
    const [activeTab, setActiveTab] = useState<'general' | 'audio' | 'security'>('general')

    // Email change state
    const [showEmailChange, setShowEmailChange] = useState(false)
    const [newEmail, setNewEmail] = useState('')
    const [emailPassword, setEmailPassword] = useState('')
    const [emailLoading, setEmailLoading] = useState(false)
    const [emailError, setEmailError] = useState('')
    const [emailSuccess, setEmailSuccess] = useState('')

    // Password change state
    const [showPasswordChange, setShowPasswordChange] = useState(false)
    const [currentPassword, setCurrentPassword] = useState('')
    const [newPassword, setNewPassword] = useState('')
    const [confirmNewPassword, setConfirmNewPassword] = useState('')
    const [passwordLoading, setPasswordLoading] = useState(false)
    const [passwordError, setPasswordError] = useState('')
    const [passwordSuccess, setPasswordSuccess] = useState('')

    // Audio state
    const {
        masterVolume, setMasterVolume,
        musicVolume, setMusicVolume,
        sfxVolume, setSfxVolume,
        isMuted, setIsMuted
    } = useAudio()

    useEffect(() => {
        fetchAccountData()
    }, [])

    const fetchAccountData = async () => {
        try {
            setLoading(true)
            const data = await authApi.getAccount()
            setAccount(data.account)
            // characters are returned as data.characters but we don't display the list here anymore
            setError('')
        } catch (err: any) {
            setError(err.response?.data?.detail || t('common.error'))
        } finally {
            setLoading(false)
        }
    }

    const handleEmailChange = async (e: React.FormEvent) => {
        e.preventDefault()
        setEmailError('')
        setEmailSuccess('')

        if (!newEmail || !emailPassword) {
            setEmailError(t('common.error'))
            return
        }

        setEmailLoading(true)
        try {
            const response = await authApi.changeEmail(emailPassword, newEmail)
            setEmailSuccess(response.message)
            setNewEmail('')
            setEmailPassword('')
            setShowEmailChange(false)
            // Refresh account data
            await fetchAccountData()
        } catch (err: any) {
            setEmailError(err.response?.data?.detail || t('common.error'))
        } finally {
            setEmailLoading(false)
        }
    }

    const handlePasswordChange = async (e: React.FormEvent) => {
        e.preventDefault()
        setPasswordError('')
        setPasswordSuccess('')

        if (!currentPassword || !newPassword || !confirmNewPassword) {
            setPasswordError(t('common.error'))
            return
        }

        if (newPassword !== confirmNewPassword) {
            setPasswordError(t('auth.errors.passwordMatch'))
            return
        }

        if (newPassword.length < 6) {
            setPasswordError(t('auth.errors.passwordLength'))
            return
        }

        setPasswordLoading(true)
        try {
            const response = await authApi.changePassword(currentPassword, newPassword)
            setPasswordSuccess(response.message)
            setCurrentPassword('')
            setNewPassword('')
            setConfirmNewPassword('')
            setShowPasswordChange(false)
        } catch (err: any) {
            setPasswordError(err.response?.data?.detail || t('common.error'))
        } finally {
            setPasswordLoading(false)
        }
    }

    const formatDate = (timestamp: string | number) => {
        if (!timestamp) return 'Never'
        const date = typeof timestamp === 'number' ? new Date(timestamp * 1000) : new Date(timestamp)
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
    }

    const getAccountTypeDisplay = (type: string) => {
        const types: { [key: string]: string } = {
            'web': 'Web',
            'standalone': 'Standalone',
            'steam': 'Steam'
        }
        return types[type] || type
    }

    if (loading) {
        return (
            <div className="account-page">
                <div className="account-loading game-panel">{t('common.loading')}</div>
            </div>
        )
    }

    if (error || !account) {
        return (
            <div className="account-page">
                <div className="account-error game-panel">
                    <h2 className="error-title">{t('common.error')}</h2>
                    <p>{error || t('common.error')}</p>
                    <GameButton variant="secondary" onClick={() => navigate(currentCharacter ? '/game' : '/characters')}>
                        {t('common.back')}
                    </GameButton>
                </div>
            </div>
        )
    }

    return (
        <div className="account-page">
            <div className="account-container game-panel account-panel-override">
                <div className="account-header-top">
                    <h1 className="account-title">{t('common.accountSettings')}</h1>
                    <div className="account-top-actions">
                        <GameButton variant="secondary" onClick={() => navigate(currentCharacter ? '/game' : '/characters')}>
                            {currentCharacter ? t('game.dialog.back') : t('common.back')}
                        </GameButton>
                        {/* Logout removed from here, user wants it only in header */}
                    </div>
                </div>

                <div className="account-layout">
                    {/* Tabs Navigation */}
                    <div className="account-tabs">
                        <button
                            className={`account-tab ${activeTab === 'general' ? 'active' : ''}`}
                            onClick={() => setActiveTab('general')}
                        >
                            <span className="tab-icon">👤</span> {t('common.general')}
                        </button>
                        <button
                            className={`account-tab ${activeTab === 'audio' ? 'active' : ''}`}
                            onClick={() => setActiveTab('audio')}
                        >
                            <span className="tab-icon">🎵</span> {t('common.audio')}
                        </button>
                        <button
                            className={`account-tab ${activeTab === 'security' ? 'active' : ''}`}
                            onClick={() => setActiveTab('security')}
                        >
                            <span className="tab-icon">🔒</span> {t('common.security')}
                        </button>
                    </div>

                    {/* Tab Content Areas */}
                    <div className="account-content">
                        {/* GENERAL TAB */}
                        {activeTab === 'general' && (
                            <section className="account-section animate-fade-in fixed-height-section">
                                <h2 className="section-title">{t('auth.accountInfo')}</h2>
                                <div className="info-grid game-panel inner">
                                    <div className="info-item">
                                        <span className="info-label">{t('auth.email')}</span>
                                        <span className="info-value">{account.email}</span>
                                    </div>
                                    <div className="info-item">
                                        <span className="info-label">{t('auth.accountType')}</span>
                                        <span className="info-value">{getAccountTypeDisplay(account.account_type)}</span>
                                    </div>
                                    <div className="info-item">
                                        <span className="info-label">{t('auth.premiumStatus')}</span>
                                        <span className={`info-value ${account.premium_expires_at ? 'premium' : ''}`}>
                                            {account.premium_expires_at && Number(account.premium_expires_at) > Date.now() / 1000
                                                ? t('auth.premiumActive')
                                                : t('auth.freeAccount')}
                                        </span>
                                    </div>
                                    <div className="info-item">
                                        <span className="info-label">{t('auth.created')}</span>
                                        <span className="info-value">{formatDate(account.created_at)}</span>
                                    </div>
                                    <div className="info-item">
                                        <span className="info-label">{t('auth.lastLogin')}</span>
                                        <span className="info-value">{formatDate(account.last_login_at)}</span>
                                    </div>
                                </div>

                                <div className="character-actions-area">
                                    <h3 className="subsection-title">{t('auth.gameActions')}</h3>
                                    <GameButton variant="primary" onClick={() => navigate('/characters')}>
                                        {t('auth.switchCharacter')}
                                    </GameButton>
                                </div>
                            </section>
                        )}

                        {/* AUDIO TAB */}
                        {activeTab === 'audio' && (
                            <section className="account-section animate-fade-in fixed-height-section">
                                <h2 className="section-title">{t('auth.audioSettings')}</h2>
                                <div className="audio-settings game-panel inner">
                                    <div className="setting-header-ui">
                                        <h3>{t('auth.volumeControls')}</h3>
                                        <label className="mute-toggle-ui">
                                            <input
                                                type="checkbox"
                                                checked={isMuted}
                                                onChange={(e) => setIsMuted(e.target.checked)}
                                            />
                                            <span>{t('auth.muteAll')}</span>
                                        </label>
                                    </div>
                                    <div className="volume-sliders-ui">
                                        <div className="slider-group-ui">
                                            <label>{t('auth.masterVolume')}: {Math.round(masterVolume * 100)}%</label>
                                            <div className="slider-wrapper">
                                                <input
                                                    type="range"
                                                    min="0"
                                                    max="1"
                                                    step="0.01"
                                                    className="game-slider"
                                                    value={masterVolume}
                                                    onChange={(e) => setMasterVolume(parseFloat(e.target.value))}
                                                    disabled={isMuted}
                                                />
                                            </div>
                                        </div>
                                        <div className="slider-group-ui">
                                            <label>{t('auth.musicVolume')}: {Math.round(musicVolume * 100)}%</label>
                                            <div className="slider-wrapper">
                                                <input
                                                    type="range"
                                                    min="0"
                                                    max="1"
                                                    step="0.01"
                                                    className="game-slider"
                                                    value={musicVolume}
                                                    onChange={(e) => setMusicVolume(parseFloat(e.target.value))}
                                                    disabled={isMuted}
                                                />
                                            </div>
                                        </div>
                                        <div className="slider-group-ui">
                                            <label>{t('auth.sfxVolume')}: {Math.round(sfxVolume * 100)}%</label>
                                            <div className="slider-wrapper">
                                                <input
                                                    type="range"
                                                    min="0"
                                                    max="1"
                                                    step="0.01"
                                                    className="game-slider"
                                                    value={sfxVolume}
                                                    onChange={(e) => setSfxVolume(parseFloat(e.target.value))}
                                                    disabled={isMuted}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </section>
                        )}

                        {/* SECURITY TAB */}
                        {activeTab === 'security' && (
                            <section className="account-section animate-fade-in fixed-height-section">
                                <h2 className="section-title">{t('auth.securitySettings')}</h2>

                                {/* Email Change */}
                                <div className="setting-item-ui game-panel inner">
                                    <div className="setting-header-ui">
                                        <h3>{t('auth.changeEmail')}</h3>
                                        <GameButton
                                            variant="secondary"
                                            size="sm"
                                            onClick={() => setShowEmailChange(!showEmailChange)}
                                        >
                                            {showEmailChange ? t('auth.cancel') : t('auth.change')}
                                        </GameButton>
                                    </div>
                                    {showEmailChange && (
                                        <form onSubmit={handleEmailChange} className="setting-form-ui">
                                            <div className="form-group-ui">
                                                <label htmlFor="newEmail">{t('auth.email')}</label>
                                                <input
                                                    type="email"
                                                    id="newEmail"
                                                    className="game-input squared-input"
                                                    value={newEmail}
                                                    onChange={(e) => setNewEmail(e.target.value)}
                                                    placeholder={t('auth.emailPlaceholder')}
                                                    required
                                                    disabled={emailLoading}
                                                />
                                            </div>
                                            <div className="form-group-ui">
                                                <label htmlFor="emailPassword">{t('auth.currentPassword')}</label>
                                                <input
                                                    type="password"
                                                    id="emailPassword"
                                                    className="game-input squared-input"
                                                    value={emailPassword}
                                                    onChange={(e) => setEmailPassword(e.target.value)}
                                                    placeholder={t('auth.verifyIdentity')}
                                                    required
                                                    disabled={emailLoading}
                                                />
                                            </div>
                                            {emailError && <div className="error-message-ui">{emailError}</div>}
                                            {emailSuccess && <div className="message-success-ui">{emailSuccess}</div>}
                                            <GameButton variant="primary" disabled={emailLoading} onClick={() => { }}>
                                                {emailLoading ? t('auth.updating') : t('auth.updateEmail')}
                                            </GameButton>
                                        </form>
                                    )}
                                </div>

                                {/* Password Change */}
                                <div className="setting-item-ui game-panel inner">
                                    <div className="setting-header-ui">
                                        <h3>{t('auth.changePassword')}</h3>
                                        <GameButton
                                            variant="secondary"
                                            size="sm"
                                            onClick={() => setShowPasswordChange(!showPasswordChange)}
                                        >
                                            {showPasswordChange ? t('auth.cancel') : t('auth.change')}
                                        </GameButton>
                                    </div>
                                    {showPasswordChange && (
                                        <form onSubmit={handlePasswordChange} className="setting-form-ui">
                                            <div className="form-group-ui">
                                                <label htmlFor="currentPassword">{t('auth.currentPassword')}</label>
                                                <input
                                                    type="password"
                                                    id="currentPassword"
                                                    className="game-input squared-input"
                                                    value={currentPassword}
                                                    onChange={(e) => setCurrentPassword(e.target.value)}
                                                    placeholder={t('auth.passwordPlaceholderLogin')}
                                                    required
                                                    disabled={passwordLoading}
                                                />
                                            </div>
                                            <div className="form-group-ui">
                                                <label htmlFor="newPassword">{t('auth.newPassword')}</label>
                                                <input
                                                    type="password"
                                                    id="newPassword"
                                                    className="game-input squared-input"
                                                    value={newPassword}
                                                    onChange={(e) => setNewPassword(e.target.value)}
                                                    placeholder={t('auth.passwordPlaceholder')}
                                                    required
                                                    disabled={passwordLoading}
                                                />
                                            </div>
                                            <div className="form-group-ui">
                                                <label htmlFor="confirmNewPassword">{t('auth.confirmNewPassword')}</label>
                                                <input
                                                    type="password"
                                                    id="confirmNewPassword"
                                                    className="game-input squared-input"
                                                    value={confirmNewPassword}
                                                    onChange={(e) => setConfirmNewPassword(e.target.value)}
                                                    placeholder={t('auth.confirmPasswordPlaceholder')}
                                                    required
                                                    disabled={passwordLoading}
                                                />
                                            </div>
                                            {passwordError && <div className="error-message-ui">{passwordError}</div>}
                                            {passwordSuccess && <div className="message-success-ui">{passwordSuccess}</div>}
                                            <GameButton variant="primary" disabled={passwordLoading} onClick={() => { }}>
                                                {passwordLoading ? t('auth.updating') : t('auth.updatePassword')}
                                            </GameButton>
                                        </form>
                                    )}
                                </div>
                            </section>
                        )}
                    </div>
                </div>
            </div>
        </div>
    )
}

export default AccountPage
