import React, { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

const Account = () => {
  const [activeTab, setActiveTab] = useState('profile');
  const [firstName, setFirstName] = useState("Murtadi");
  const [lastName, setLastName] = useState("Mujaidi");
  const [email, setEmail] = useState("Mujaidi@gmail.com");

  // State untuk password
  const [passwords, setPasswords] = useState({
    currentPassword: '',
    newPassword: '',
    confirmNewPassword: ''
  });

  // State untuk visibilitas password
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [newPasswordVisible, setNewPasswordVisible] = useState(false);
  const [confirmNewPasswordVisible, setConfirmNewPasswordVisible] = useState(false);

  // State untuk pesan kesalahan
  const [errorMessages, setErrorMessages] = useState({
    currentPasswordError: '',
    newPasswordError: '',
    confirmNewPasswordError: ''
  });

  // Fungsi untuk toggle visibility password
  const togglePasswordVisibility = (e, type) => {
    e.preventDefault();
    if (type === 'current') {
      setPasswordVisible(prevState => !prevState);
    } else if (type === 'new') {
      setNewPasswordVisible(prevState => !prevState);
    } else if (type === 'confirm') {
      setConfirmNewPasswordVisible(prevState => !prevState);
    }
  };

  // Fungsi untuk menangani perubahan password
  const handlePasswordChange = (e) => {
    const { name, value } = e.target;
    setPasswords(prevState => ({
      ...prevState,
      [name]: value
    }));
  };

  // Validasi password
  const validatePasswords = () => {
    const { currentPassword, newPassword, confirmNewPassword } = passwords;
    let isValid = true;
    let errors = {
      currentPasswordError: '',
      newPasswordError: '',
      confirmNewPasswordError: ''
    };

    if (!currentPassword || !newPassword || !confirmNewPassword) {
      errors.currentPasswordError = 'Please fill in all password fields.';
      isValid = false;
    }
    if (newPassword !== confirmNewPassword) {
      errors.newPasswordError = 'New password and confirm password do not match.';
      isValid = false;
    }
    if (newPassword === currentPassword) {
      errors.newPasswordError = 'New password cannot be the same as the current password.';
      isValid = false;
    }

    setErrorMessages(errors);
    return isValid;
  };

  // Styles untuk elemen-elemen
  const styles = {
    tabContainer: {
      border: '1px solid #d3d3d3',
      borderLeft: '4px solid #0542cc',
      alignItems: 'center',
      justifyContent: 'flex-start',
      display: 'flex',
      boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
    },
    tabButton: {
      display: 'flex',
      justifyContent: 'flex-start',
      alignItems: 'center',
    },
    contentContainer: {
      border: '1px solid #d3d3d3',
      height: '23rem',
      overflowY: 'auto',
      padding: '1rem 0 0 1.7rem',
      boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
    },
    inputGroup: {
      width: '200px',
    },
    errorText: {
      color: 'red',
      fontSize: '0.8rem',
    }
  };

  const renderTabContent = () => {
    switch (activeTab) {
      case 'profile':
        return (
          <div>
            <h3>My Profile</h3>
            <form className='mt-3'>
              <div className='col-6'>
                <div className="input-group mb-3">
                  <span className="input-group-text" style={styles.inputGroup}>First Name</span>
                  <input
                    type="text"
                    className="form-control"
                    id="firstName"
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                  />
                </div>
              </div>

              <div className='col-6'>
                <div className="input-group mb-3">
                  <span className="input-group-text" style={styles.inputGroup}>Last Name</span>
                  <input
                    type="text"
                    className="form-control"
                    id="lastName"
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                  />
                </div>
              </div>

              <div className='col-6'>
                <div className="input-group mb-3">
                  <span className="input-group-text" style={styles.inputGroup}>Email</span>
                  <input
                    type="email"
                    className="form-control"
                    id="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
              </div>
              <button type="button" className="btn btn-primary">
                Edit Profile
              </button>
            </form>
          </div>
        );
      case 'password':
        return (
          <>
            <h3>Update Password</h3>
            <form onSubmit={(e) => { e.preventDefault(); if (validatePasswords()) { alert('Password updated successfully!'); } }}>
              <div className='col-6 mb-2'>
                <div className="input-group mb-3">
                  <span className="input-group-text" style={styles.inputGroup}>Current Password</span>
                  <input
                    type={passwordVisible ? 'text' : 'password'}
                    className="form-control"
                    name="currentPassword"
                    value={passwords.currentPassword}
                    onChange={handlePasswordChange}
                  />
                  <button
                    className="input-group-text"
                    onClick={(e) => togglePasswordVisibility(e, 'current')}
                    style={{ cursor: 'pointer' }}
                  >
                    <FontAwesomeIcon icon={passwordVisible ? "fa-solid fa-eye" : "fa-solid fa-eye-slash"} />
                  </button>
                </div>
                {errorMessages.currentPasswordError && (
                  <small className="text-danger" style={styles.errorText}>{errorMessages.currentPasswordError}</small>
                )}
              </div>

              <div className='col-6 mb-2'>
                <div className="input-group mb-3">
                  <span className="input-group-text" style={styles.inputGroup}>New Password</span>
                  <input
                    type={newPasswordVisible ? 'text' : 'password'}
                    className="form-control"
                    name="newPassword"
                    value={passwords.newPassword}
                    onChange={handlePasswordChange}
                  />
                  <button
                    className="input-group-text"
                    onClick={(e) => togglePasswordVisibility(e, 'new')}
                    style={{ cursor: 'pointer' }}
                  >
                    <FontAwesomeIcon icon={newPasswordVisible ? "fa-solid fa-eye" : "fa-solid fa-eye-slash"} />
                  </button>
                </div>
                {errorMessages.newPasswordError && (
                  <small className="text-danger" style={styles.errorText}>{errorMessages.newPasswordError}</small>
                )}
              </div>

              <div className='col-6 mb-2'>
                <div className="input-group mb-3">
                  <span className="input-group-text" style={styles.inputGroup}>Confirm New Password</span>
                  <input
                    type={confirmNewPasswordVisible ? 'text' : 'password'}
                    className="form-control"
                    name="confirmNewPassword"
                    value={passwords.confirmNewPassword}
                    onChange={handlePasswordChange}
                  />
                  <button
                    className="input-group-text"
                    onClick={(e) => togglePasswordVisibility(e, 'confirm')}
                    style={{ cursor: 'pointer' }}
                  >
                    <FontAwesomeIcon icon={confirmNewPasswordVisible ? "fa-solid fa-eye" : "fa-solid fa-eye-slash"} />
                  </button>
                </div>
                {errorMessages.confirmNewPasswordError && (
                  <small className="text-danger" style={styles.errorText}>{errorMessages.confirmNewPasswordError}</small>
                )}
              </div>

              <button type="submit" className="btn btn-primary">
                Save
              </button>
            </form>
          </>
        );
      default:
        return null;
    }
  };

  return (
    <div className="container mt-5">
      <div className="row gx-5">
        {/* Tab Navigation - 3 Col */}
        <div className="col-md-3 border-end" style={styles.tabContainer}>
          <div className="nav flex-column nav-pills">
            <button
              className={`nav-link ${activeTab === 'profile' ? 'active' : ''}`}
              onClick={() => setActiveTab('profile')}
              style={styles.tabButton}
            >
              <i className="fas fa-user-circle me-2"></i> My Profile
            </button>
            <button
              className={`nav-link ${activeTab === 'password' ? 'active' : ''}`}
              onClick={() => setActiveTab('password')}
              style={styles.tabButton}
            >
              <i className="fas fa-key me-2"></i> Update Password
            </button>
          </div>
        </div>

        {/* Content Area - 9 Col */}
        <div className="col-md-9">
          <div style={styles.contentContainer}>
            {renderTabContent()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Account;
