import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { User, Item } from '../types';
import { userAPI, itemAPI } from '../services/api';
import { getImageUrl } from '../services/uploadService';
import { useAuth } from '../contexts/AuthContext';
import ChatWindow from '../components/ChatWindow';
import Avatar from '../components/Avatar';
import BanUserModal from '../components/BanUserModal';
import ConfirmationModal from '../components/ConfirmationModal';

const PublicProfile: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user: currentUser } = useAuth();
  const [user, setUser] = useState<User | null>(null);
  const [items, setItems] = useState<Item[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showChat, setShowChat] = useState(false);
  const [showBanModal, setShowBanModal] = useState(false);
  const [showUnbanModal, setShowUnbanModal] = useState(false);
  const [unbanning, setUnbanning] = useState(false);

  useEffect(() => {
    fetchUserProfile();
    fetchUserItems();
  }, [id]);

  const fetchUserProfile = async () => {
    try {
      const response = await userAPI.getPublicProfile(id!);
      setUser(response.data);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to fetch user profile');
    }
  };

  const fetchUserItems = async () => {
    try {
      const response = await itemAPI.getItems();
      const allItems = response.data.items || response.data || [];
      const userItems = allItems.filter((item: Item) => item.ownerId === id);
      setItems(userItems);
    } catch (err) {
      console.error('Failed to fetch user items:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleBanComplete = (updatedUser: User) => {
    setUser(updatedUser);
  };

  const handleUnban = async () => {
    if (!user) return;

    try {
      setUnbanning(true);
      const response = await userAPI.adminUnbanUser(user.id);
      setUser(response.data.user);
      setShowUnbanModal(false);
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to unban user');
    } finally {
      setUnbanning(false);
    }
  };

  const isAdmin = currentUser?.role === 'admin';
  const canBanUser = isAdmin && user && currentUser?.id !== user.id && user.role !== 'admin';

  if (loading) {
    return (
      <div className="container mt-5">
        <div className="text-center">
          <div className="spinner-border" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      </div>
    );
  }

  if (error || !user) {
    return (
      <div className="container mt-5">
        <div className="alert alert-danger" role="alert">
          {error || 'User not found'}
        </div>
      </div>
    );
  }

  return (
    <div className="container mt-4 mb-5">
      <div className="row justify-content-center">
        <div className="col-md-8">
          <div className="card">
            <div className="card-body">
              <div className="text-center mb-4">
                <Avatar user={user} size="xxxl" className="mb-3 mx-auto" />
                <h3>{user.firstName} {user.lastName}</h3>

                {/* Show ban status badge for admins */}
                {isAdmin && user.isBanned && (
                  <div className="mt-2">
                    <span className="badge bg-danger">Banned</span>
                    {user.bannedAt && (
                      <small className="text-muted d-block mt-1">
                        Banned on {new Date(user.bannedAt).toLocaleDateString()}
                      </small>
                    )}
                  </div>
                )}

                {/* Message button - hide for banned users */}
                {currentUser && currentUser.id !== user.id && !user.isBanned && (
                  <button
                    className="btn btn-primary mt-3"
                    onClick={() => setShowChat(true)}
                  >
                    <i className="bi bi-chat-dots-fill me-2"></i>Message
                  </button>
                )}

                {/* Admin Ban/Unban buttons */}
                {canBanUser && (
                  <div className="mt-3">
                    {user.isBanned ? (
                      <button
                        className="btn btn-success"
                        onClick={() => setShowUnbanModal(true)}
                      >
                        <i className="bi bi-person-check me-2"></i>Unban User
                      </button>
                    ) : (
                      <button
                        className="btn btn-danger"
                        onClick={() => setShowBanModal(true)}
                      >
                        <i className="bi bi-person-x me-2"></i>Ban User
                      </button>
                    )}
                  </div>
                )}

                {/* Show ban reason for admins */}
                {isAdmin && user.isBanned && user.banReason && (
                  <div className="alert alert-warning mt-3 text-start">
                    <strong>Ban Reason:</strong>
                    <p className="mb-0 mt-1">{user.banReason}</p>
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="card mt-4">
            <div className="card-body">
              <h5 className="card-title">Items Listed ({items.length})</h5>
              {items.length > 0 ? (
                <div className="row">
                  {items.map((item) => (
                    <div key={item.id} className="col-md-6 mb-3">
                      <div 
                        className="card h-100 cursor-pointer" 
                        onClick={() => navigate(`/items/${item.id}`)}
                        style={{ cursor: 'pointer' }}
                      >
                        {item.imageFilenames.length > 0 ? (
                          <img
                            src={getImageUrl(item.imageFilenames[0], 'thumbnail')}
                            className="card-img-top"
                            alt={item.name}
                            onError={(e) => {
                              const target = e.currentTarget;
                              if (!target.dataset.fallback) {
                                target.dataset.fallback = 'true';
                                target.src = getImageUrl(item.imageFilenames[0], 'original');
                              }
                            }}
                            style={{ height: '200px', objectFit: 'contain', backgroundColor: '#f8f9fa' }}
                          />
                        ) : (
                          <div className="bg-light d-flex align-items-center justify-content-center" style={{ height: '200px' }}>
                            <span className="text-muted">No image</span>
                          </div>
                        )}
                        <div className="card-body">
                          <h6 className="card-title">{item.name}</h6>
                          <p className="card-text text-muted small">{item.city && item.state ? `${item.city}, ${item.state}` : ''}</p>
                          <div>
                            {item.pricePerDay && (
                              <span className="badge bg-primary">${item.pricePerDay}/day</span>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-muted">No items listed yet.</p>
              )}
            </div>
          </div>

          <div className="text-center mt-4">
            <button className="btn btn-secondary" onClick={() => navigate(-1)}>
              Back
            </button>
          </div>
        </div>
      </div>

      {/* ChatWindow popup */}
      {user && (
        <ChatWindow
          show={showChat}
          onClose={() => setShowChat(false)}
          recipient={user}
        />
      )}

      {/* BanUserModal */}
      {user && (
        <BanUserModal
          show={showBanModal}
          onHide={() => setShowBanModal(false)}
          user={user}
          onBanComplete={handleBanComplete}
        />
      )}

      {/* UnbanModal */}
      {user && (
        <ConfirmationModal
          show={showUnbanModal}
          onClose={() => setShowUnbanModal(false)}
          onConfirm={handleUnban}
          title={`Unban ${user.firstName} ${user.lastName}`}
          message="Are you sure you want to unban this user? They will be able to log in and use the platform again."
          confirmText="Unban User"
          cancelText="Cancel"
          confirmButtonClass="btn-success"
          loading={unbanning}
        />
      )}
    </div>
  );
};

export default PublicProfile;