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

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

    // 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)
            setCharacters(data.characters)
            setError('')
        } catch (err: any) {
            setError(err.response?.data?.detail || 'Failed to load account data')
        } finally {
            setLoading(false)
        }
    }

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

        if (!newEmail || !emailPassword) {
            setEmailError('Please fill in all fields')
            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 || 'Failed to change email')
        } finally {
            setEmailLoading(false)
        }
    }

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

        if (!currentPassword || !newPassword || !confirmNewPassword) {
            setPasswordError('Please fill in all fields')
            return
        }

        if (newPassword !== confirmNewPassword) {
            setPasswordError('New passwords do not match')
            return
        }

        if (newPassword.length < 6) {
            setPasswordError('New password must be at least 6 characters')
            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 || 'Failed to change password')
        } 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">Loading account...</div>
            </div>
        )
    }

    if (error || !account) {
        return (
            <div className="account-page">
                <div className="account-error">
                    <h2>Error</h2>
                    <p>{error || 'Account not found'}</p>
                    <button onClick={() => navigate('/game')}>Back to Game</button>
                </div>
            </div>
        )
    }

    return (
        <div className="account-page">
            <div className="account-container">
                <h1 className="account-title">Account Management</h1>

                {/* Account Information Section */}
                <section className="account-section">
                    <h2 className="section-title">Account Information</h2>
                    <div className="info-grid">
                        <div className="info-item">
                            <span className="info-label">Email:</span>
                            <span className="info-value">{account.email}</span>
                        </div>
                        <div className="info-item">
                            <span className="info-label">Account Type:</span>
                            <span className="info-value">{getAccountTypeDisplay(account.account_type)}</span>
                        </div>
                        <div className="info-item">
                            <span className="info-label">Premium Status:</span>
                            <span className={`info-value ${account.premium_expires_at ? 'premium' : ''}`}>
                                {account.premium_expires_at && Number(account.premium_expires_at) > Date.now() / 1000
                                    ? '✓ Premium Active'
                                    : 'Free Account'}
                            </span>
                        </div>
                        <div className="info-item">
                            <span className="info-label">Created:</span>
                            <span className="info-value">{formatDate(account.created_at)}</span>
                        </div>
                        <div className="info-item">
                            <span className="info-label">Last Login:</span>
                            <span className="info-value">{formatDate(account.last_login_at)}</span>
                        </div>
                    </div>
                </section>

                {/* Characters Section */}
                <section className="account-section">
                    <h2 className="section-title">Your Characters</h2>
                    {characters.length === 0 ? (
                        <p className="no-characters">No characters yet. Create one to start playing!</p>
                    ) : (
                        <div className="characters-grid">
                            {characters.map((char) => (
                                <div key={char.id} className="character-card">
                                    <div className="character-header">
                                        <h3>{char.name}</h3>
                                        <span className="character-level">Level {char.level}</span>
                                    </div>
                                    <div className="character-stats">
                                        <div className="stat">
                                            <span className="stat-label">HP:</span>
                                            <span className="stat-value">{char.hp}/{char.max_hp}</span>
                                        </div>
                                        <div className="stat">
                                            <span className="stat-label">Stamina:</span>
                                            <span className="stat-value">{char.stamina}/{char.max_stamina}</span>
                                        </div>
                                    </div>
                                    <div className="character-attributes">
                                        <span>STR: {char.strength}</span>
                                        <span>AGI: {char.agility}</span>
                                        <span>END: {char.endurance}</span>
                                        <span>INT: {char.intellect}</span>
                                    </div>
                                    <button
                                        className="button-secondary"
                                        onClick={() => navigate(`/profile/${char.id}`)}
                                    >
                                        View Profile
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                    <button
                        className="button-primary"
                        onClick={() => navigate('/create-character')}
                    >
                        Create New Character
                    </button>
                </section>

                {/* Settings Section */}
                <section className="account-section">
                    <h2 className="section-title">Audio Settings</h2>
                    <div className="audio-settings">
                        <div className="setting-item">
                            <div className="setting-header">
                                <h3>Volume Controls</h3>
                                <label className="mute-toggle">
                                    <input
                                        type="checkbox"
                                        checked={isMuted}
                                        onChange={(e) => setIsMuted(e.target.checked)}
                                    />
                                    <span>Mute All</span>
                                </label>
                            </div>
                            <div className="volume-sliders">
                                <div className="slider-group">
                                    <label>Master Volume: {Math.round(masterVolume * 100)}%</label>
                                    <input
                                        type="range"
                                        min="0"
                                        max="1"
                                        step="0.01"
                                        value={masterVolume}
                                        onChange={(e) => setMasterVolume(parseFloat(e.target.value))}
                                        disabled={isMuted}
                                    />
                                </div>
                                <div className="slider-group">
                                    <label>Music Volume: {Math.round(musicVolume * 100)}%</label>
                                    <input
                                        type="range"
                                        min="0"
                                        max="1"
                                        step="0.01"
                                        value={musicVolume}
                                        onChange={(e) => setMusicVolume(parseFloat(e.target.value))}
                                        disabled={isMuted}
                                    />
                                </div>
                                <div className="slider-group">
                                    <label>SFX Volume: {Math.round(sfxVolume * 100)}%</label>
                                    <input
                                        type="range"
                                        min="0"
                                        max="1"
                                        step="0.01"
                                        value={sfxVolume}
                                        onChange={(e) => setSfxVolume(parseFloat(e.target.value))}
                                        disabled={isMuted}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

                <section className="account-section">
                    <h2 className="section-title">Account Settings</h2>

                    {/* Email Change */}
                    <div className="setting-item">
                        <div className="setting-header">
                            <h3>Change Email</h3>
                            <button
                                className="button-link"
                                onClick={() => setShowEmailChange(!showEmailChange)}
                            >
                                {showEmailChange ? 'Cancel' : 'Change'}
                            </button>
                        </div>
                        {showEmailChange && (
                            <form onSubmit={handleEmailChange} className="setting-form">
                                <div className="form-group">
                                    <label htmlFor="newEmail">New Email</label>
                                    <input
                                        type="email"
                                        id="newEmail"
                                        value={newEmail}
                                        onChange={(e) => setNewEmail(e.target.value)}
                                        placeholder="new.email@example.com"
                                        required
                                        disabled={emailLoading}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="emailPassword">Current Password</label>
                                    <input
                                        type="password"
                                        id="emailPassword"
                                        value={emailPassword}
                                        onChange={(e) => setEmailPassword(e.target.value)}
                                        placeholder="Verify your identity"
                                        required
                                        disabled={emailLoading}
                                    />
                                </div>
                                {emailError && <div className="error">{emailError}</div>}
                                {emailSuccess && <div className="success">{emailSuccess}</div>}
                                <button type="submit" className="button-primary" disabled={emailLoading}>
                                    {emailLoading ? 'Updating...' : 'Update Email'}
                                </button>
                            </form>
                        )}
                    </div>

                    {/* Password Change */}
                    <div className="setting-item">
                        <div className="setting-header">
                            <h3>Change Password</h3>
                            <button
                                className="button-link"
                                onClick={() => setShowPasswordChange(!showPasswordChange)}
                            >
                                {showPasswordChange ? 'Cancel' : 'Change'}
                            </button>
                        </div>
                        {showPasswordChange && (
                            <form onSubmit={handlePasswordChange} className="setting-form">
                                <div className="form-group">
                                    <label htmlFor="currentPassword">Current Password</label>
                                    <input
                                        type="password"
                                        id="currentPassword"
                                        value={currentPassword}
                                        onChange={(e) => setCurrentPassword(e.target.value)}
                                        placeholder="Your current password"
                                        required
                                        disabled={passwordLoading}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="newPassword">New Password</label>
                                    <input
                                        type="password"
                                        id="newPassword"
                                        value={newPassword}
                                        onChange={(e) => setNewPassword(e.target.value)}
                                        placeholder="At least 6 characters"
                                        required
                                        disabled={passwordLoading}
                                    />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="confirmNewPassword">Confirm New Password</label>
                                    <input
                                        type="password"
                                        id="confirmNewPassword"
                                        value={confirmNewPassword}
                                        onChange={(e) => setConfirmNewPassword(e.target.value)}
                                        placeholder="Re-enter new password"
                                        required
                                        disabled={passwordLoading}
                                    />
                                </div>
                                {passwordError && <div className="error">{passwordError}</div>}
                                {passwordSuccess && <div className="success">{passwordSuccess}</div>}
                                <button type="submit" className="button-primary" disabled={passwordLoading}>
                                    {passwordLoading ? 'Updating...' : 'Update Password'}
                                </button>
                            </form>
                        )}
                    </div>
                </section>

                {/* Actions Section */}
                <section className="account-actions">
                    <button
                        className="button-secondary"
                        onClick={() => navigate('/game')}
                    >
                        Back to Game
                    </button>
                    <button
                        className="button-danger"
                        onClick={() => {
                            if (confirm('Are you sure you want to logout?')) {
                                logout()
                                navigate('/login')
                            }
                        }}
                    >
                        Logout
                    </button>
                </section>
            </div>
        </div>
    )
}

export default AccountPage
