import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { authService, User } from '../services/membershipService';
import { useToast } from '../contexts/ToastContext';
import { formatLondonDate } from '../utils/timezone';

interface ProfileMenuProps {
  userName: string;
  userRole: string;
  user?: User | null;
  onEditProfile?: () => void;
}

const ProfileMenu: React.FC<ProfileMenuProps> = ({ userName, user, onEditProfile }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [showChangePassword, setShowChangePassword] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleLogout = () => {
    authService.logout();
    navigate('/login');
  };

  const handleChangePassword = () => {
    setShowChangePassword(true);
    setIsOpen(false);
  };

  const formatDate = (dateString: string) => formatLondonDate(dateString);

  return (
    <>
      <div className="profile-menu" ref={menuRef}>
        <button
          className="profile-menu-trigger"
          onClick={() => setIsOpen(!isOpen)}
        >
          <span>{userName}</span>
          <span className="profile-menu-chevron">▼</span>
        </button>

        {isOpen && (
          <div className="profile-menu-dropdown">
            {user && (
              <div className="profile-menu-summary">
                <div className="profile-menu-summary-head">
                  <h4>Profile Details</h4>
                  {onEditProfile && (
                    <button
                      className="profile-menu-edit"
                      onClick={() => {
                        onEditProfile();
                        setIsOpen(false);
                      }}
                    >
                      Edit
                    </button>
                  )}
                </div>
                <div className="profile-menu-details">
                  <p><strong>Name:</strong> {user.first_name} {user.last_name}</p>
                  <p><strong>Email:</strong> {user.email}</p>
                  {user.phone && <p><strong>Phone:</strong> {user.phone}</p>}
                  {user.address && <p><strong>Address:</strong> {user.address}</p>}
                  <p><strong>Member since:</strong> {formatDate(user.created_at)}</p>
                </div>
              </div>
            )}

            <button
              className={`profile-menu-item ${user ? '' : 'first'}`}
              onClick={handleChangePassword}
            >
              Change Password
            </button>
            <button
              className="profile-menu-item last"
              onClick={handleLogout}
            >
              Log Out
            </button>
          </div>
        )}
      </div>

      {showChangePassword && (
        <ChangePasswordModal onClose={() => setShowChangePassword(false)} />
      )}
    </>
  );
};

interface ChangePasswordModalProps {
  onClose: () => void;
}

const ChangePasswordModal: React.FC<ChangePasswordModalProps> = ({ onClose }) => {
  const toast = useToast();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (newPassword !== confirmPassword) {
      setError('New passwords do not match');
      return;
    }

    if (newPassword.length < 8) {
      setError('New password must be at least 8 characters long');
      return;
    }

    setLoading(true);
    setError('');

    try {
      await authService.changePassword({
        current_password: currentPassword,
        new_password: newPassword
      });

      toast.success('Password changed successfully.');
      onClose();
    } catch (error: any) {
      setError(error.response?.data?.detail || 'Failed to change password');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-overlay">
      <div className="modal-content">
        <h3>Change Password</h3>

        <form onSubmit={handleSubmit}>
          <div className="modal-form-group">
            <label>
              Current Password
            </label>
            <input
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              required
            />
          </div>

          <div className="modal-form-group">
            <label>
              New Password
            </label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              required
              minLength={8}
            />
          </div>

          <div className="modal-form-group">
            <label>
              Confirm New Password
            </label>
            <input
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              required
              minLength={8}
            />
          </div>

          {error && (
            <div className="modal-error">
              {error}
            </div>
          )}

          <div className="modal-button-row">
            <button
              className="btn btn-secondary"
              type="button"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </button>
            <button
              className="btn btn-primary"
              type="submit"
              disabled={loading}
            >
              {loading ? 'Changing...' : 'Change Password'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ProfileMenu;
