import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from '../components/Toast';
import { profileService } from '../services/api';

export default function Profile() {
  const { t } = useTranslation();
  const { showToast } = useToast();
  
  const [loading, setLoading] = useState(true);
  const [savingProfile, setSavingProfile] = useState(false);
  const [savingPassword, setSavingPassword] = useState(false);
  
  // Dados do perfil
  const [profile, setProfile] = useState({
    name: '',
    email: '',
  });
  
  // Dados de alteração de senha
  const [passwordData, setPasswordData] = useState({
    current_password: '',
    new_password: '',
    new_password_confirmation: '',
  });
  
  // Erros de validação
  const [profileErrors, setProfileErrors] = useState({});
  const [passwordErrors, setPasswordErrors] = useState({});

  useEffect(() => {
    loadProfile();
  }, []);

  const loadProfile = async () => {
    try {
      setLoading(true);
      const response = await profileService.get();
      if (response.success) {
        setProfile({
          name: response.data.user.name || '',
          email: response.data.user.email || '',
        });
      }
    } catch (error) {
      console.error('Error loading profile:', error);
      showToast(t('profile.loadError'), 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleProfileChange = (field, value) => {
    setProfile(prev => ({
      ...prev,
      [field]: value,
    }));
    // Limpar erro do campo
    if (profileErrors[field]) {
      setProfileErrors(prev => ({ ...prev, [field]: null }));
    }
  };

  const handlePasswordChange = (field, value) => {
    setPasswordData(prev => ({
      ...prev,
      [field]: value,
    }));
    // Limpar erro do campo
    if (passwordErrors[field]) {
      setPasswordErrors(prev => ({ ...prev, [field]: null }));
    }
  };

  const handleSaveProfile = async (e) => {
    e.preventDefault();
    setProfileErrors({});
    
    try {
      setSavingProfile(true);
      const response = await profileService.update({
        name: profile.name,
        email: profile.email,
      });
      
      if (response.success) {
        showToast(t('profile.saveSuccess'), 'success');
      }
    } catch (error) {
      console.error('Error saving profile:', error);
      if (error.response?.data?.errors) {
        setProfileErrors(error.response.data.errors);
      }
      showToast(error.response?.data?.message || t('profile.saveError'), 'error');
    } finally {
      setSavingProfile(false);
    }
  };

  const handleChangePassword = async (e) => {
    e.preventDefault();
    setPasswordErrors({});
    
    // Validação básica no frontend
    if (passwordData.new_password !== passwordData.new_password_confirmation) {
      setPasswordErrors({ new_password_confirmation: [t('profile.passwordMismatch')] });
      return;
    }
    
    if (passwordData.new_password.length < 8) {
      setPasswordErrors({ new_password: [t('profile.passwordTooShort')] });
      return;
    }
    
    try {
      setSavingPassword(true);
      const response = await profileService.update({
        current_password: passwordData.current_password,
        new_password: passwordData.new_password,
        new_password_confirmation: passwordData.new_password_confirmation,
      });
      
      if (response.success) {
        showToast(t('profile.passwordChanged'), 'success');
        // Limpar campos de senha
        setPasswordData({
          current_password: '',
          new_password: '',
          new_password_confirmation: '',
        });
      }
    } catch (error) {
      console.error('Error changing password:', error);
      if (error.response?.data?.errors) {
        setPasswordErrors(error.response.data.errors);
      }
      showToast(error.response?.data?.message || t('profile.passwordError'), 'error');
    } finally {
      setSavingPassword(false);
    }
  };

  if (loading) {
    return (
      <div className="container-fluid py-4">
        <div className="d-flex justify-content-center align-items-center" style={{ minHeight: '400px' }}>
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">{t('common.loading')}</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container-fluid py-4">
      <div className="row justify-content-center">
        <div className="col-lg-8 col-xl-6">
          {/* Header */}
          <div className="d-flex align-items-center mb-4">
            <i className="bi bi-person-circle fs-2 text-primary me-3"></i>
            <div>
              <h2 className="mb-0">{t('profile.title')}</h2>
              <p className="text-muted mb-0">{t('profile.subtitle')}</p>
            </div>
          </div>

          {/* Dados Pessoais */}
          <div className="card mb-4">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="bi bi-person me-2"></i>
                {t('profile.personalData')}
              </h5>
            </div>
            <div className="card-body">
              <form onSubmit={handleSaveProfile}>
                {/* Nome */}
                <div className="mb-3">
                  <label htmlFor="name" className="form-label">
                    {t('profile.name')} <span className="text-danger">*</span>
                  </label>
                  <input
                    type="text"
                    className={`form-control ${profileErrors.name ? 'is-invalid' : ''}`}
                    id="name"
                    value={profile.name}
                    onChange={(e) => handleProfileChange('name', e.target.value)}
                    required
                  />
                  {profileErrors.name && (
                    <div className="invalid-feedback">{profileErrors.name[0]}</div>
                  )}
                </div>

                {/* Email */}
                <div className="mb-3">
                  <label htmlFor="email" className="form-label">
                    {t('profile.email')} <span className="text-danger">*</span>
                  </label>
                  <input
                    type="email"
                    className={`form-control ${profileErrors.email ? 'is-invalid' : ''}`}
                    id="email"
                    value={profile.email}
                    onChange={(e) => handleProfileChange('email', e.target.value)}
                    required
                  />
                  {profileErrors.email && (
                    <div className="invalid-feedback">{profileErrors.email[0]}</div>
                  )}
                </div>

                {/* Botão Salvar Perfil */}
                <div className="d-flex justify-content-end">
                  <button
                    type="submit"
                    className="btn btn-primary"
                    disabled={savingProfile}
                  >
                    {savingProfile ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2" role="status"></span>
                        {t('common.saving')}
                      </>
                    ) : (
                      <>
                        <i className="bi bi-check-lg me-2"></i>
                        {t('profile.saveProfile')}
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>
          </div>

          {/* Alterar Senha */}
          <div className="card">
            <div className="card-header">
              <h5 className="mb-0">
                <i className="bi bi-shield-lock me-2"></i>
                {t('profile.changePassword')}
              </h5>
            </div>
            <div className="card-body">
              <form onSubmit={handleChangePassword}>
                {/* Senha Atual */}
                <div className="mb-3">
                  <label htmlFor="current_password" className="form-label">
                    {t('profile.currentPassword')} <span className="text-danger">*</span>
                  </label>
                  <input
                    type="password"
                    className={`form-control ${passwordErrors.current_password ? 'is-invalid' : ''}`}
                    id="current_password"
                    value={passwordData.current_password}
                    onChange={(e) => handlePasswordChange('current_password', e.target.value)}
                    required
                    autoComplete="current-password"
                  />
                  {passwordErrors.current_password && (
                    <div className="invalid-feedback">{passwordErrors.current_password[0]}</div>
                  )}
                </div>

                {/* Nova Senha */}
                <div className="mb-3">
                  <label htmlFor="new_password" className="form-label">
                    {t('profile.newPassword')} <span className="text-danger">*</span>
                  </label>
                  <input
                    type="password"
                    className={`form-control ${passwordErrors.new_password ? 'is-invalid' : ''}`}
                    id="new_password"
                    value={passwordData.new_password}
                    onChange={(e) => handlePasswordChange('new_password', e.target.value)}
                    required
                    minLength={8}
                    autoComplete="new-password"
                  />
                  {passwordErrors.new_password && (
                    <div className="invalid-feedback">{passwordErrors.new_password[0]}</div>
                  )}
                  <div className="form-text">{t('profile.passwordHint')}</div>
                </div>

                {/* Confirmar Nova Senha */}
                <div className="mb-3">
                  <label htmlFor="new_password_confirmation" className="form-label">
                    {t('profile.confirmPassword')} <span className="text-danger">*</span>
                  </label>
                  <input
                    type="password"
                    className={`form-control ${passwordErrors.new_password_confirmation ? 'is-invalid' : ''}`}
                    id="new_password_confirmation"
                    value={passwordData.new_password_confirmation}
                    onChange={(e) => handlePasswordChange('new_password_confirmation', e.target.value)}
                    required
                    minLength={8}
                    autoComplete="new-password"
                  />
                  {passwordErrors.new_password_confirmation && (
                    <div className="invalid-feedback">{passwordErrors.new_password_confirmation[0]}</div>
                  )}
                </div>

                {/* Botão Alterar Senha */}
                <div className="d-flex justify-content-end">
                  <button
                    type="submit"
                    className="btn btn-warning"
                    disabled={savingPassword}
                  >
                    {savingPassword ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2" role="status"></span>
                        {t('common.saving')}
                      </>
                    ) : (
                      <>
                        <i className="bi bi-key me-2"></i>
                        {t('profile.changePassword')}
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
