import { useState } from 'react'
import { Shell } from '../layouts/Shell'
import { useAuth } from '../context/AuthContext'
import { adminService } from '../services/adminService'

export function MyProfilePage() {
  const { user, login } = useAuth()
  const [isEditing, setIsEditing] = useState(false)
  const [loading, setLoading] = useState(false)
  const [formData, setFormData] = useState({
    name: user?.name || '',
    email: user?.email || '',
    username: user?.username || ''
  })

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value })
  }

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!user) return
    setLoading(true)
    try {
      const updatedUser = await adminService.updateUser(user.id, {
        name: formData.name,
        email: formData.email,
        username: formData.username
      })

      // Update local auth context
      login(
        user.token,
        user.role,
        updatedUser.name,
        updatedUser.id,
        updatedUser.company_id,
        updatedUser.email,
        updatedUser.username
      )

      setIsEditing(false)
      alert('Perfil atualizado com sucesso!')
    } catch (err) {
      console.error('Error updating profile', err)
      alert('Erro ao atualizar perfil. Tente novamente.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Shell>
      <div className="space-y-6 rounded-lg bg-white p-6 shadow-sm max-w-4xl mx-auto">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-xl font-semibold text-medicalBlue">Meu Perfil</h1>
            <p className="text-sm text-gray-600">Acompanhe as informações básicas da sua conta.</p>
          </div>
          {!isEditing ? (
            <button
              onClick={() => setIsEditing(true)}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 transition-colors"
            >
              Editar Dados
            </button>
          ) : (
            <button
              onClick={() => {
                setIsEditing(false)
                setFormData({
                  name: user?.name || '',
                  email: user?.email || '',
                  username: user?.username || ''
                })
              }}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors"
            >
              Cancelar
            </button>
          )}
        </div>

        <form onSubmit={handleSave} className="grid gap-6">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="rounded-md border border-gray-200 p-4 relative">
              <label className="text-xs uppercase text-gray-400 block mb-1">Nome</label>
              {isEditing ? (
                <input
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  className="w-full p-1 border-b border-blue-500 focus:outline-none text-sm font-semibold text-gray-800"
                />
              ) : (
                <p className="text-sm font-semibold text-gray-800">{user?.name ?? 'Não informado'}</p>
              )}
            </div>

            <div className="rounded-md border border-gray-200 p-4 bg-gray-50">
              <p className="text-xs uppercase text-gray-400 mb-1">Perfil</p>
              <p className="text-sm font-semibold text-gray-800">{user?.role ?? 'Não informado'}</p>
              {isEditing && <span className="text-[10px] text-gray-500 absolute top-2 right-2">(Não editável)</span>}
            </div>

            <div className="rounded-md border border-gray-200 p-4">
              <label className="text-xs uppercase text-gray-400 block mb-1">E-mail</label>
              {isEditing ? (
                <input
                  name="email"
                  type="email"
                  value={formData.email}
                  onChange={handleChange}
                  className="w-full p-1 border-b border-blue-500 focus:outline-none text-sm font-semibold text-gray-800"
                />
              ) : (
                <p className="text-sm font-semibold text-gray-800">{user?.email ?? 'Não informado'}</p>
              )}
            </div>

            <div className="rounded-md border border-gray-200 p-4">
              <label className="text-xs uppercase text-gray-400 block mb-1">Usuário</label>
              {isEditing ? (
                <input
                  name="username"
                  value={formData.username}
                  onChange={handleChange}
                  className="w-full p-1 border-b border-blue-500 focus:outline-none text-sm font-semibold text-gray-800"
                />
              ) : (
                <p className="text-sm font-semibold text-gray-800">{user?.username ?? 'Não informado'}</p>
              )}
            </div>
          </div>

          {isEditing && (
            <div className="flex justify-end pt-4 border-t">
              <button
                type="submit"
                disabled={loading}
                className="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-2 rounded-lg font-medium shadow-sm disabled:opacity-50 transition-all flex items-center gap-2"
              >
                {loading ? 'Salvando...' : 'Salvar Alterações'}
              </button>
            </div>
          )}
        </form>
      </div>
    </Shell>
  )
}
