import React, { useEffect, useState } from 'react';
import { User, UserRole } from '../types';
import { getMe, updateMe, changePassword, uploadPhoto } from '../services/users';

export default function ProfilePanel() {
  const [me, setMe] = useState<User | null>(null);
  const [nome, setNome] = useState('');
  const [email, setEmail] = useState('');
  const [photoUrl, setPhotoUrl] = useState<string | null>(null);
  const [loadingInfo, setLoadingInfo] = useState(false);
  const [loadingPhoto, setLoadingPhoto] = useState(false);
  const [loadingPassword, setLoadingPassword] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newPasswordConfirm, setNewPasswordConfirm] = useState('');

  useEffect(() => {
    const fetchMe = async () => {
      try {
        const res = await getMe();
        setMe(res);
        setNome(res.nome);
        setEmail((res as any).email || '');
        setPhotoUrl((res as any).photo_url || null);
      } catch (err: any) {
        setError('Não foi possível carregar seu perfil.');
      }
    };
    fetchMe();
  }, []);

  const handleSaveInfo = async (e: React.FormEvent) => {
    e.preventDefault();
    setMessage(null); setError(null); setLoadingInfo(true);
    try {
      const updated = await updateMe({ nome, email });
      setMe(updated);
      setMessage('Informações atualizadas com sucesso.');
    } catch (err: any) {
      try { setError(JSON.parse(err.message)?.error || 'Erro ao salvar informações.'); } catch { setError('Erro ao salvar informações.'); }
    } finally {
      setLoadingInfo(false);
    }
  };

  const handlePhotoChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setMessage(null); setError(null); setLoadingPhoto(true);
    try {
      const res = await uploadPhoto(file);
      setPhotoUrl(res.photo_url);
      setMessage('Foto atualizada com sucesso.');
    } catch (err: any) {
      try { setError(JSON.parse(err.message)?.error || 'Erro ao enviar foto.'); } catch { setError('Erro ao enviar foto.'); }
    } finally {
      setLoadingPhoto(false);
    }
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setMessage(null); setError(null);
    if (newPassword !== newPasswordConfirm) { setError('Nova senha e confirmação não conferem.'); return; }
    setLoadingPassword(true);
    try {
      await changePassword({ currentPassword, newPassword });
      setMessage('Senha alterada com sucesso.');
      setCurrentPassword(''); setNewPassword(''); setNewPasswordConfirm('');
    } catch (err: any) {
      try { setError(JSON.parse(err.message)?.error || 'Erro ao alterar senha.'); } catch { setError('Erro ao alterar senha.'); }
    } finally {
      setLoadingPassword(false);
    }
  };

  const handleLogout = () => {
    try {
      localStorage.removeItem('auth_token');
      localStorage.removeItem('currentUser');
      localStorage.removeItem('currentUserId');
    } catch {}
    window.location.reload();
  };

  return (
    <div className="bg-primary-medium/20 border border-primary-medium/50 rounded-2xl p-6 w-full">
      <h3 className="text-xl font-bold text-white mb-4">Meu Perfil</h3>
      {message && <div className="text-green-300 text-sm mb-2">{message}</div>}
      {error && <div className="text-red-300 text-sm mb-2">{error}</div>}

      <div className="flex items-center gap-4 mb-6">
        <div className="w-20 h-20 rounded-full overflow-hidden bg-primary-dark border border-primary-medium/60">
          {photoUrl ? (
            <img src={photoUrl} alt="Foto de perfil" className="w-full h-full object-cover" />
          ) : (
            <div className="w-full h-full flex items-center justify-center text-gray-400 text-sm">Sem foto</div>
          )}
        </div>
        <div>
          <input type="file" accept="image/*" onChange={handlePhotoChange} disabled={loadingPhoto} />
          {loadingPhoto && <p className="text-xs text-gray-400">Enviando foto...</p>}
        </div>
      </div>

      <form onSubmit={handleSaveInfo} className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
        <div>
          <label className="block text-sm mb-1">Nome</label>
          <input value={nome} onChange={e => setNome(e.target.value)} className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none" />
        </div>
        <div>
          <label className="block text-sm mb-1">E-mail</label>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none" />
        </div>
        <div>
          <label className="block text-sm mb-1">Papel</label>
          <input value={me?.role || ''} readOnly className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none opacity-70" />
        </div>
        <div className="flex items-end">
          <button type="submit" className="bg-primary-light text-primary-dark font-semibold px-6 py-2 rounded hover:bg-opacity-90 disabled:opacity-60" disabled={loadingInfo}>
            {loadingInfo ? 'Salvando...' : 'Salvar alterações'}
          </button>
        </div>
      </form>

      <form onSubmit={handleChangePassword} className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div>
          <label className="block text-sm mb-1">Senha atual</label>
          <input type="password" value={currentPassword} onChange={e => setCurrentPassword(e.target.value)} className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none" required />
        </div>
        <div>
          <label className="block text-sm mb-1">Nova senha</label>
          <input type="password" value={newPassword} onChange={e => setNewPassword(e.target.value)} className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none" required />
        </div>
        <div>
          <label className="block text-sm mb-1">Confirmar nova senha</label>
          <input type="password" value={newPasswordConfirm} onChange={e => setNewPasswordConfirm(e.target.value)} className="w-full px-3 py-2 rounded bg-primary-dark border border-primary-medium text-white focus:outline-none" required />
        </div>
        <div className="md:col-span-3">
          <button type="submit" className="bg-primary-light text-primary-dark font-semibold px-6 py-2 rounded hover:bg-opacity-90 disabled:opacity-60" disabled={loadingPassword}>
            {loadingPassword ? 'Alterando...' : 'Alterar senha'}
          </button>
        </div>
      </form>

      <button onClick={handleLogout} className="bg-red-500 text-white font-semibold px-6 py-2 rounded hover:bg-opacity-90">Sair da aplicação</button>
    </div>
  );
}