import React, { useState, useEffect } from 'react';
import { Mail, User, Lock, Edit, Save } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { API_BASE_URL } from "../config";
import { useAuth } from "../AuthContext";
import axios from "axios";

function Profil() {
  const [userData, setUserData] = useState({});

  const { user } = useAuth();
  useEffect(() => {
    if (user) {
      console.log("user.role:", user.id);
    }
  }, [user]);
  const [formData, setFormData] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  const [editMode, setEditMode] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const navigate = useNavigate();

  useEffect(() => {
    axios
      .post(`${API_BASE_URL}/user`, {
        id: user.id,
      })
      .then((response) => {
        setUserData(response.data);
        console.log("Infos récupérées :", response.data);
      })
      .catch((error) => {
        console.error("Erreur lors de la récupération :", error);
      });
  }, [user]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleProfileChange = (e) => {
    const { name, value } = e.target;
    setUserData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrorMessage('');
    setSuccessMessage('');

    if (formData.newPassword !== formData.confirmPassword) {
      setErrorMessage("Les nouveaux mots de passe ne correspondent pas !");
      return;
    }

    try {
      axios
      .post(`${API_BASE_URL}/changePassword`, {
        id: userData.id,
        oldPassword: formData.oldPassword,
        newPassword: formData.newPassword
      })
      .then((response) => {
        console.log("Modification du mot de passe réussie :", response.data);
        setSuccessMessage("Mot de passe modifié avec succès !");
        setFormData({
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        });
      })
      .catch((error) => {
        console.error("Erreur lors de la modification du mot de passe :", error);
        setErrorMessage(error.response?.data?.error || "Une erreur est survenue");
      });

      setSuccessMessage("Mot de passe modifié avec succès !");
      setFormData({
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      });
    } catch (error) {
      setErrorMessage(error.message || "Une erreur est survenue");
    }
  };

  const handleProfileSubmit = async (e) => {
    e.preventDefault();
    setErrorMessage('');
    setSuccessMessage('');

    axios
    .post(`${API_BASE_URL}/updateProfil`, {
      id: userData.id,
      name: userData.name,
      surname: userData.surname,
      pseudo:userData.pseudo,
      email: userData.email
    })
    
    .catch((error) => {
      console.error("Erreur lors de la mise à jour du profil :", error);
      setErrorMessage(error.response?.data?.error || "Une erreur est survenue");
    })
    .then((response) => {
      console.log("Mise à jour du profil réussie :", response.data);
      setSuccessMessage("Profil mis à jour avec succès !");
      setEditMode(false);
    });
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto">
        <h1 className="text-3xl font-bold text-gray-900 mb-8 text-center">Mon Profil</h1>

        {errorMessage && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4">
            {errorMessage}
          </div>
        )}

        {successMessage && (
          <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4">
            {successMessage}
          </div>
        )}

        <div className="grid md:grid-cols-2 gap-8">
          {/* Informations du profil */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-semibold text-gray-800">Informations Personnelles</h2>
              <button 
                onClick={() => setEditMode(!editMode)} 
                className="text-indigo-600 hover:text-indigo-800"
              >
                {editMode ? <Save className="h-5 w-5" /> : <Edit className="h-5 w-5" />}
              </button>
            </div>

            <form onSubmit={handleProfileSubmit} className="space-y-4">
              <div className="flex items-center space-x-4 mb-4">
                <div className="w-20 h-20 bg-indigo-100 rounded-full flex items-center justify-center">
                  <User className="h-10 w-10 text-indigo-600" />
                </div>
                <div>
                  <h3 className="text-lg font-medium">{userData.name} {userData.surname} ({userData.pseudo})</h3>
                  <p className="text-gray-500">{userData.email}</p>
                </div>
              </div>

              <div className="bg-indigo-50 p-3 rounded-lg mb-4">
                <p className="text-sm text-gray-700">Points de fidélité: <span className="font-semibold">{userData.points}</span>  ({userData.role})</p>
              </div>

              {editMode ? (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Prénom:</label>
                    <input
                      type="text"
                      name="name"
                      value={userData.name}
                      onChange={handleProfileChange}
                      className="block w-full rounded-lg border-gray-300 border p-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Nom:</label>
                    <input
                      type="text"
                      name="surname"
                      value={userData.surname}
                      onChange={handleProfileChange}
                      className="block w-full rounded-lg border-gray-300 border p-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Pseudo:</label>
                    <input
                      type="text"
                      name="pseudo"
                      value={userData.pseudo}
                      onChange={handleProfileChange}
                      className="block w-full rounded-lg border-gray-300 border p-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Email:</label>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <Mail className="h-5 w-5 text-gray-400" />
                      </div>
                      <input
                        type="email"
                        name="email"
                        value={userData.email}
                        disabled
                        className="pl-10 block w-full rounded-lg border-gray-300 border p-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                      />
                    </div>
                  </div>

                  <button
                    type="submit"
                    className="w-full flex justify-center py-2 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  >
                    Sauvegarder
                  </button>
                </>
              ) : (
                <div className="space-y-3">
                  <div>
                    <p className="text-sm font-medium text-gray-500">Prénom</p>
                    <p className="mt-1">{userData.name}</p>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">Nom</p>
                    <p className="mt-1">{userData.surname}</p>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">Pseudo</p>
                    <p className="mt-1">{userData.pseudo}</p>
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">Email</p>
                    <p className="mt-1">{userData.email}</p>
                  </div>
                </div>
              )}
            </form>
          </div>

          {/* Changement de mot de passe */}
          <div className="bg-white rounded-lg shadow-md p-6">
            <h2 className="text-xl font-semibold text-gray-800 mb-4">Modifier le mot de passe</h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Mot de passe actuel:
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-gray-400" />
                  </div>
                  <input
                    type="password"
                    name="oldPassword"
                    value={formData.oldPassword}
                    onChange={handleChange}
                    className="pl-10 block w-full rounded-lg border-gray-300 border p-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    required
                    minLength="8"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Nouveau mot de passe:
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-gray-400" />
                  </div>
                  <input
                    type="password"
                    name="newPassword"
                    value={formData.newPassword}
                    onChange={handleChange}
                    className="pl-10 block w-full rounded-lg border-gray-300 border p-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    required
                    minLength="8"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Confirmer le nouveau mot de passe:
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-gray-400" />
                  </div>
                  <input
                    type="password"
                    name="confirmPassword"
                    value={formData.confirmPassword}
                    onChange={handleChange}
                    className="pl-10 block w-full rounded-lg border-gray-300 border p-2.5 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    required
                    minLength="8"
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full flex justify-center py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Modifier le mot de passe
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Profil;