import React from 'react'
import { getUser, setUser as setUserLS } from '../utils/storage'
import { sfx } from '../utils/audio'
import CustomModal from '../components/CustomModal'

export default function Settings() {
    const [user, setUser] = React.useState(getUser() || {})
    const [username, setUsername] = React.useState(user.username || '')
    const [email, setEmail] = React.useState(user.email || '')
    const [password, setPassword] = React.useState('')
    const [loading, setLoading] = React.useState(false)

    const [modal, setModal] = React.useState({ open: false, title: '', msg: '', type: 'alert', onConfirm: null })

    const showModal = (msg, title = 'Info') => {
        setModal({ open: true, title, msg, type: 'alert', onConfirm: () => setModal(m => ({ ...m, open: false })) })
    }

    const handleSave = async (e) => {
        e.preventDefault()
        setLoading(true)
        try {
            const res = await fetch('http://localhost/landingpage1/lomba/user.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    id: user.id,
                    username,
                    email,
                    password: password || undefined
                })
            })
            const data = await res.json()
            if (res.ok) {
                showModal('Pengaturan berhasil disimpan!', 'Berhasil')
                sfx.play('success')
                // Update local storage
                const newUser = { ...user, username, email }
                setUserLS(newUser)
                setUser(newUser)
                setPassword('')
            } else {
                showModal(data.message, 'Gagal')
            }
        } catch (error) {
            showModal('Gagal menyimpan pengaturan', 'Error')
        } finally {
            setLoading(false)
        }
    }

    return (
        <div className="max-w-2xl mx-auto">
            <CustomModal
                isOpen={modal.open}
                title={modal.title}
                message={modal.msg}
                type={modal.type}
                onConfirm={modal.onConfirm}
                onCancel={() => setModal(m => ({ ...m, open: false }))}
            />
            <h1 className="heading text-3xl text-onme-blue mb-6">Pengaturan Akun</h1>

            <form onSubmit={handleSave} className="bg-white rounded-3xl p-6 border-2 border-slate-200 shadow-sm space-y-4">
                <div>
                    <label className="block font-bold text-slate-700 mb-1">Username</label>
                    <input
                        value={username}
                        onChange={e => setUsername(e.target.value)}
                        className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-indigo-500 outline-none"
                        placeholder="Username unik"
                    />
                </div>

                <div>
                    <label className="block font-bold text-slate-700 mb-1">Email</label>
                    <input
                        value={email}
                        onChange={e => setEmail(e.target.value)}
                        type="email"
                        className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-indigo-500 outline-none"
                        placeholder="email@contoh.com"
                    />
                </div>

                <div>
                    <label className="block font-bold text-slate-700 mb-1">Password Baru (Opsional)</label>
                    <input
                        value={password}
                        onChange={e => setPassword(e.target.value)}
                        type="password"
                        className="w-full border-2 border-slate-200 rounded-xl p-3 focus:border-indigo-500 outline-none"
                        placeholder="Kosongkan jika tidak ingin mengubah"
                    />
                </div>

                <div className="pt-4">
                    <button disabled={loading} className="w-full bg-indigo-600 text-white font-bold py-3 rounded-xl hover:bg-indigo-700 transition-colors disabled:opacity-50">
                        {loading ? 'Menyimpan...' : 'Simpan Perubahan'}
                    </button>
                </div>
            </form>
        </div>
    )
}
