import { useEffect, useState } from 'react'
import { adminService, User } from '../../services/adminService'
import { useAuth } from '../../context/AuthContext'

export function ProfilePage() {
    const { user, setUser: setAuthUser } = useAuth()
    const [formData, setFormData] = useState({
        name: '',
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
    })
    const [loading, setLoading] = useState(false)
    const [message, setMessage] = useState('')

    useEffect(() => {
        if (user) {
            setFormData(prev => ({
                ...prev,
                name: user.name,
                username: user.username || '',
                email: user.email || ''
            }))
        }
    }, [user])

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        if (!user) return

        if (formData.password && formData.password !== formData.confirmPassword) {
            alert('Senhas não conferem')
            return
        }

        setLoading(true)
        setMessage('')

        try {
            const updateData: any = {
                name: formData.name,
                username: formData.username,
                email: formData.email
            }
            if (formData.password) {
                updateData.password = formData.password
            }

            const updatedUser = await adminService.updateUser(user.id, updateData)

            // Update auth context
            // We need to map AdminService User to AuthContext User (they are similar)
            setAuthUser({
                ...user,
                name: updatedUser.name,
                username: updatedUser.username,
                email: updatedUser.email
            })

            setMessage('Perfil atualizado com sucesso!')
            setFormData(prev => ({ ...prev, password: '', confirmPassword: '' }))
        } catch (err) {
            console.error('Error updating profile:', err)
            setMessage('Erro ao atualizar perfil')
        } finally {
            setLoading(false)
        }
    }

    return (
        <div className="mx-auto max-w-2xl">
            <h1 className="mb-6 text-2xl font-bold text-gray-900">Meu Perfil</h1>

            <div className="rounded-lg bg-white p-6 shadow">
                {message && (
                    <div className={`mb-4 rounded p-3 text-sm ${message.includes('Erro') ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'}`}>
                        {message}
                    </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Nome</label>
                        <input
                            type="text"
                            value={formData.name}
                            onChange={e => setFormData({ ...formData, name: e.target.value })}
                            className="mt-1 block w-full rounded-md border border-gray-300 p-2 focus:border-blue-500 focus:outline-none"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700">Usuário</label>
                        <input
                            type="text"
                            value={formData.username}
                            onChange={e => setFormData({ ...formData, username: e.target.value })}
                            className="mt-1 block w-full rounded-md border border-gray-300 p-2 focus:border-blue-500 focus:outline-none"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700">Email</label>
                        <input
                            type="email"
                            value={formData.email}
                            onChange={e => setFormData({ ...formData, email: e.target.value })}
                            className="mt-1 block w-full rounded-md border border-gray-300 p-2 focus:border-blue-500 focus:outline-none"
                            required
                        />
                    </div>

                    <div className="pt-4">
                        <h3 className="mb-2 text-sm font-medium text-gray-900">Alterar Senha</h3>
                        <p className="mb-3 text-xs text-gray-500">Deixe em branco para manter a senha atual</p>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700">Nova Senha</label>
                                <input
                                    type="password"
                                    value={formData.password}
                                    onChange={e => setFormData({ ...formData, password: e.target.value })}
                                    className="mt-1 block w-full rounded-md border border-gray-300 p-2 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700">Confirmar Nova Senha</label>
                                <input
                                    type="password"
                                    value={formData.confirmPassword}
                                    onChange={e => setFormData({ ...formData, confirmPassword: e.target.value })}
                                    className="mt-1 block w-full rounded-md border border-gray-300 p-2 focus:border-blue-500 focus:outline-none"
                                />
                            </div>
                        </div>
                    </div>

                    <div className="pt-4">
                        <button
                            type="submit"
                            disabled={loading}
                            className="flex w-full justify-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:bg-blue-300"
                        >
                            {loading ? 'Salvando...' : 'Salvar Alterações'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    )
}
