import React, { useState } from 'react'
import { photoAPI, API_BASE_URL } from '../api'
import '../styles/profilePhotoModal.css'

export default function ProfilePhotoModal({ isOpen, onClose, currentPhoto, onPhotoUpdate, onEditProfile }) {
  const [isUploading, setIsUploading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  const handlePhotoUpload = async (e) => {
    const file = e.target.files[0]
    if (!file) return

    setIsUploading(true)
    setError('')
    setSuccess('')

    try {
      const response = await photoAPI.uploadPhoto(file)
      setSuccess('Photo updated successfully')
      setTimeout(() => {
        if (onPhotoUpdate) {
          onPhotoUpdate(response.data)
        }
        onClose()
      }, 1000)
    } catch (err) {
      setError('Failed to upload photo. Please try again.')
      console.error(err)
    } finally {
      setIsUploading(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className="profile-photo-modal-overlay" onClick={onClose}>
      <div className="profile-photo-modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="profile-photo-modal-header">
          <h2>Update Profile Photo</h2>
          <button className="profile-photo-modal-close" onClick={onClose}>&times;</button>
        </div>

        <div className="profile-photo-modal-body">
          {currentPhoto && (
            <div className="current-photo">
              <p className="label">Current Photo:</p>
              <img 
                src={`${API_BASE_URL}/media/${currentPhoto}`} 
                alt="Current profile"
                className="current-photo-img"
              />
            </div>
          )}

          <div className="photo-upload-section">
            <p className="label">Upload New Photo:</p>
            <label htmlFor="photo-file-input" className="upload-button">
              📸 Choose Photo
            </label>
            <input
              id="photo-file-input"
              type="file"
              accept="image/*"
              onChange={handlePhotoUpload}
              disabled={isUploading}
              className="file-input"
            />
            {isUploading && <p className="uploading">Uploading...</p>}
          </div>

          {error && <div className="error-message">{error}</div>}
          {success && <div className="success-message">{success}</div>}

          <p className="info-text">
            💡 Your profile photo will be displayed on your profile and in the discover section.
          </p>

          <button 
            onClick={() => {
              onClose()
              if (onEditProfile) onEditProfile()
            }}
            className="edit-profile-btn"
          >
            ✏️ Edit Profile
          </button>
        </div>
      </div>
    </div>
  )
}
