import React, { useEffect, useRef, useState } from 'react';
import {
  fetchIslandByUsername,
  uploadProfileAvatar,
  fetchFriendStatus,
  sendFriendRequest,
  removeFriend,
  fetchFriends,
  changePassword,
} from '../../api/client';
import { useAuth } from '../../auth/AuthContext';
import '../../styles/profile.css';
import '../Friends/Friends.css';

/**
 * UserProfile: Modal showing user info with "Visit Island" button
 *
 * Props:
 * - username: string (required)
 * - onClose: function
 * - onVisitIsland: function(island) - called when "Visit Island" is clicked
 */
export default function UserProfile({ username, onClose, onVisitIsland }) {
  const { authenticated, username: authedUser, setAvatarUrl } = useAuth();
  const [island, setIsland] = useState(null);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [avatarVisibility, setAvatarVisibility] = useState("public");
  const [avatarGroupId, setAvatarGroupId] = useState("");
  const [avatarUsers, setAvatarUsers] = useState("");
  const fileRef = useRef(null);

  const isSelf = authenticated && authedUser && authedUser.toLowerCase() === username.toLowerCase();

  // Friend status
  const [friendStatus, setFriendStatus] = useState('none'); // none, pending, accepted
  const [friendDirection, setFriendDirection] = useState(''); // sent, received (for pending)
  const [friendLoading, setFriendLoading] = useState(false);
  const [showFriends, setShowFriends] = useState(false);
  const [friends, setFriends] = useState([]);

  // Password change state
  const [showPasswordForm, setShowPasswordForm] = useState(false);
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [passwordSuccess, setPasswordSuccess] = useState('');
  const [passwordLoading, setPasswordLoading] = useState(false);

  useEffect(() => {
    if (!authenticated || isSelf || !username) return;

    fetchFriendStatus(username).then((res) => {
      if (res?.ok) {
        setFriendStatus(res.status || 'none');
        setFriendDirection(res.direction || '');
      }
    });
  }, [authenticated, isSelf, username]);

  useEffect(() => {
    if (!username) return;

    fetchIslandByUsername(username)
      .then(data => {
        setIsland(data);
        setLoading(false);
      })
      .catch(err => {
        console.error('[UserProfile] Error fetching island:', err);
        setLoading(false);
      });
  }, [username]);

  const handleVisitIsland = () => {
    if (island && onVisitIsland) {
      onVisitIsland(island);
    }
  };

  const handleChooseAvatar = () => {
    if (fileRef.current) fileRef.current.click();
  };

  const handleAddFriend = async () => {
    if (!authenticated || friendLoading) return;
    setFriendLoading(true);
    const res = await sendFriendRequest(username);
    setFriendLoading(false);
    if (res?.ok) {
      setFriendStatus('pending');
      setFriendDirection('sent');
    }
  };

  const handleRemoveFriend = async () => {
    if (!authenticated || friendLoading) return;
    setFriendLoading(true);
    const res = await removeFriend(username);
    setFriendLoading(false);
    if (res?.ok) {
      setFriendStatus('none');
      setFriendDirection('');
    }
  };

  const loadFriends = async () => {
    const res = await fetchFriends();
    setFriends(res?.friends || []);
  };

  const handleChangePassword = async (e) => {
    e.preventDefault();
    setPasswordError('');
    setPasswordSuccess('');

    if (newPassword.length < 8) {
      setPasswordError('Password must be at least 8 characters');
      return;
    }
    if (newPassword !== confirmPassword) {
      setPasswordError('Passwords do not match');
      return;
    }

    setPasswordLoading(true);
    const res = await changePassword(oldPassword, newPassword);
    setPasswordLoading(false);

    if (res.ok) {
      setPasswordSuccess('Password changed successfully!');
      setOldPassword('');
      setNewPassword('');
      setConfirmPassword('');
      setTimeout(() => {
        setShowPasswordForm(false);
        setPasswordSuccess('');
      }, 2000);
    } else {
      if (res.error === 'invalid_old_password') {
        setPasswordError('Current password is incorrect');
      } else {
        setPasswordError(res.error || 'Failed to change password');
      }
    }
  };

  const handleAvatarChange = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setUploading(true);
    const users = avatarUsers
      .split(",")
      .map((u) => u.trim())
      .filter(Boolean);
    const res = await uploadProfileAvatar(file, {
      visibility: avatarVisibility,
      group_id: avatarGroupId.trim(),
      users,
    });
    if (res && res.ok && res.avatar_url) {
      setIsland(prev => (prev ? { ...prev, avatar_url: res.avatar_url } : prev));
      if (setAvatarUrl) setAvatarUrl(res.avatar_url);
    }
    setUploading(false);
  };

  return (
    <div className="user-profile-modal" onClick={onClose}>
      <div className="user-profile-container" onClick={(e) => e.stopPropagation()}>
        <button className="user-profile-close" onClick={onClose}>×</button>

        <div className="user-profile-header">
          <div className="user-profile-avatar">
            {island?.avatar_url ? (
              <img src={island.avatar_url} alt={username} />
            ) : (
              <div className="user-profile-avatar-letter">
                {username[0].toUpperCase()}
              </div>
            )}
          </div>
          <h2 className="user-profile-username">@{username}</h2>
          {island?.display_name && island.display_name !== `${username}'s Island` && (
            <p className="user-profile-display-name">{island.display_name}</p>
          )}
          {isSelf ? (
            <div className="user-profile-avatar-actions">
              <div className="user-profile-privacy-row">
                <label>Visibility</label>
                <select
                  value={avatarVisibility}
                  onChange={(e) => setAvatarVisibility(e.target.value)}
                >
                  <option value="public">Public</option>
                  <option value="private">Private</option>
                  <option value="group">Group</option>
                  <option value="custom">Custom</option>
                </select>
              </div>
              {avatarVisibility === "group" ? (
                <input
                  className="user-profile-input"
                  placeholder="Group ID"
                  value={avatarGroupId}
                  onChange={(e) => setAvatarGroupId(e.target.value)}
                />
              ) : null}
              {avatarVisibility === "custom" ? (
                <input
                  className="user-profile-input"
                  placeholder="Usernames (comma separated)"
                  value={avatarUsers}
                  onChange={(e) => setAvatarUsers(e.target.value)}
                />
              ) : null}
              <button
                className="user-profile-btn user-profile-btn-ghost"
                type="button"
                disabled={uploading}
                onClick={handleChooseAvatar}
              >
                {uploading ? 'Uploading...' : 'Change photo'}
              </button>
              <input
                ref={fileRef}
                type="file"
                accept="image/*"
                style={{ display: 'none' }}
                onChange={handleAvatarChange}
              />
            </div>
          ) : null}
        </div>

        {loading ? (
          <div className="user-profile-loading">Loading profile...</div>
        ) : island ? (
          <>
            <div className="user-profile-bio">
              <p>{island.bio || 'No bio yet.'}</p>
            </div>

            <div className="user-profile-stats">
              <div className="user-profile-stat">
                <span className="user-profile-stat-value">{island.content_count || 0}</span>
                <span className="user-profile-stat-label">Posts</span>
              </div>
              <div className="user-profile-stat">
                <span className="user-profile-stat-value">{island.visitors || 0}</span>
                <span className="user-profile-stat-label">Visitors</span>
              </div>
              <div className="user-profile-stat">
                <span className="user-profile-stat-value">{island.terrain_type || 'tropical'}</span>
                <span className="user-profile-stat-label">Terrain</span>
              </div>
            </div>

            <div className="user-profile-actions">
              <button
                className="user-profile-btn user-profile-btn-primary"
                onClick={handleVisitIsland}
              >
                🏝️ Visit Island
              </button>

              {authenticated && !isSelf && (
                friendStatus === 'none' ? (
                  <button
                    className="friend-btn friend-btn-add"
                    onClick={handleAddFriend}
                    disabled={friendLoading}
                  >
                    <i className="fa-solid fa-user-plus" />
                    {friendLoading ? 'Sending...' : 'Add Friend'}
                  </button>
                ) : friendStatus === 'pending' ? (
                  <button
                    className="friend-btn friend-btn-pending"
                    disabled
                  >
                    <i className="fa-solid fa-clock" />
                    {friendDirection === 'sent' ? 'Request Sent' : 'Pending'}
                  </button>
                ) : friendStatus === 'accepted' ? (
                  <button
                    className="friend-btn friend-btn-remove"
                    onClick={handleRemoveFriend}
                    disabled={friendLoading}
                  >
                    <i className="fa-solid fa-user-minus" />
                    {friendLoading ? 'Removing...' : 'Remove Friend'}
                  </button>
                ) : null
              )}

              {isSelf && (
                <>
                  <button
                    className="user-profile-btn user-profile-btn-ghost"
                    onClick={() => {
                      setShowFriends(!showFriends);
                      if (!showFriends) loadFriends();
                    }}
                  >
                    <i className="fa-solid fa-user-group" /> Friends
                  </button>
                  <button
                    className="user-profile-btn user-profile-btn-ghost"
                    onClick={() => {
                      setShowPasswordForm(!showPasswordForm);
                      setPasswordError('');
                      setPasswordSuccess('');
                    }}
                  >
                    <i className="fa-solid fa-key" /> Change Password
                  </button>
                </>
              )}
            </div>

            {isSelf && showPasswordForm && (
              <div className="user-profile-password-form">
                <form onSubmit={handleChangePassword}>
                  <div className="user-profile-form-group">
                    <label>Current Password</label>
                    <input
                      type="password"
                      className="user-profile-input"
                      value={oldPassword}
                      onChange={(e) => setOldPassword(e.target.value)}
                      placeholder="Enter current password"
                    />
                  </div>
                  <div className="user-profile-form-group">
                    <label>New Password</label>
                    <input
                      type="password"
                      className="user-profile-input"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      placeholder="Enter new password (min 8 chars)"
                      required
                    />
                  </div>
                  <div className="user-profile-form-group">
                    <label>Confirm New Password</label>
                    <input
                      type="password"
                      className="user-profile-input"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      placeholder="Confirm new password"
                      required
                    />
                  </div>
                  {passwordError && (
                    <div className="user-profile-error">{passwordError}</div>
                  )}
                  {passwordSuccess && (
                    <div className="user-profile-success">{passwordSuccess}</div>
                  )}
                  <button
                    type="submit"
                    className="user-profile-btn user-profile-btn-primary"
                    disabled={passwordLoading}
                  >
                    {passwordLoading ? 'Changing...' : 'Change Password'}
                  </button>
                </form>
              </div>
            )}

            {isSelf && showFriends && (
              <div className="user-profile-friends">
                {friends.length === 0 ? (
                  <p className="user-profile-no-friends">No friends yet</p>
                ) : (
                  <div className="user-profile-friends-list">
                    {friends.map((friend) => (
                      <div key={friend.id} className="user-profile-friend">
                        <span>{friend.username}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            <div className="user-profile-footer">
              <p className="user-profile-seed">Seed: {island.seed}</p>
              <p className="user-profile-version">v2026.01.10b</p>
            </div>
          </>
        ) : (
          <div className="user-profile-no-island">
            <p>This user doesn't have an island yet.</p>
          </div>
        )}
      </div>
    </div>
  );
}
