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

export default function ProfileEditor() {
  const [profile, setProfile] = useState({
    display_name: '',
    age: 0,
    gender: '',
    location: '',
    bio: '',
    interests: [],
  })
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [photos, setPhotos] = useState([])
  const [newInterest, setNewInterest] = useState('')

  useEffect(() => {
    loadProfile()
  }, [])

  const loadProfile = async () => {
    try {
      const response = await profileAPI.getMyProfile()
      setProfile(response.data)
      setPhotos(response.data.photos || [])
    } catch (err) {
      setError('Failed to load profile')
    }
  }

  const handleInputChange = (e) => {
    const { name, value } = e.target
    setProfile((prev) => ({ ...prev, [name]: value }))
  }

  const handleAddInterest = () => {
    if (newInterest && !profile.interests.includes(newInterest)) {
      setProfile((prev) => ({
        ...prev,
        interests: [...prev.interests, newInterest],
      }))
      setNewInterest('')
    }
  }

  const handleRemoveInterest = (interest) => {
    setProfile((prev) => ({
      ...prev,
      interests: prev.interests.filter((i) => i !== interest),
    }))
  }

  const handleSaveProfile = async (e) => {
    e.preventDefault()
    setError('')
    setSuccess('')
    setIsLoading(true)

    try {
      await profileAPI.createOrUpdateProfile(profile)
      setSuccess('Profile updated successfully')
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to save profile')
    } finally {
      setIsLoading(false)
    }
  }

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

    try {
      const response = await photoAPI.uploadPhoto(file)
      setPhotos((prev) => [...prev, response.data])
      setSuccess('Photo uploaded successfully')
    } catch (err) {
      setError('Failed to upload photo')
    }
  }

  const handleDeletePhoto = async (photoId) => {
    try {
      await photoAPI.deletePhoto(photoId)
      setPhotos((prev) => prev.filter((p) => p.id !== photoId))
      setSuccess('Photo deleted')
    } catch (err) {
      setError('Failed to delete photo')
    }
  }

  return (
    <div className="profile-editor">
      <h1>Edit Profile</h1>
      {error && <div className="error-message">{error}</div>}
      {success && <div className="success-message">{success}</div>}

      <form onSubmit={handleSaveProfile}>
        <div className="form-group">
          <label>Display Name</label>
          <input
            type="text"
            name="display_name"
            value={profile.display_name}
            onChange={handleInputChange}
            required
          />
        </div>

        <div className="form-group">
          <label>Age</label>
          <input
            type="number"
            name="age"
            value={profile.age}
            onChange={handleInputChange}
            min="18"
            required
          />
        </div>

        <div className="form-group">
          <label>Gender</label>
          <select name="gender" value={profile.gender} onChange={handleInputChange}>
            <option value="">Select Gender</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
          </select>
        </div>

        <div className="form-group">
          <label>Location</label>
          <input
            type="text"
            name="location"
            value={profile.location}
            onChange={handleInputChange}
            placeholder="City, Country"
          />
        </div>

        <div className="form-group">
          <label>Bio</label>
          <textarea
            name="bio"
            value={profile.bio}
            onChange={handleInputChange}
            rows="4"
            placeholder="Tell us about yourself..."
          />
        </div>

        <div className="form-group">
          <label>Interests</label>
          <div className="interest-input">
            <input
              type="text"
              value={newInterest}
              onChange={(e) => setNewInterest(e.target.value)}
              placeholder="Add an interest..."
            />
            <button type="button" onClick={handleAddInterest}>
              Add
            </button>
          </div>
          <div className="interests-list">
            {profile.interests.map((interest) => (
              <span key={interest} className="interest-tag">
                {interest}
                <button
                  type="button"
                  onClick={() => handleRemoveInterest(interest)}
                >
                  ×
                </button>
              </span>
            ))}
          </div>
        </div>

        <div className="photo-section-inline">
          <h3>Photos</h3>
          <div className="photo-upload">
            <input
              type="file"
              accept="image/*"
              onChange={handlePhotoUpload}
              id="photo-input"
            />
            <label htmlFor="photo-input">Upload Photo</label>
          </div>
          <div className="photos-grid">
            {photos.map((photo) => (
              <div key={photo.id} className="photo-card">
                <img src={`${API_BASE_URL}/media/${photo.file_path}`} alt="Profile" />
                <button
                  type="button"
                  onClick={() => handleDeletePhoto(photo.id)}
                  className="delete-btn"
                >
                  Delete
                </button>
              </div>
            ))}
          </div>
        </div>

        <button type="submit" disabled={isLoading}>
          {isLoading ? 'Saving...' : 'Save Profile'}
        </button>
      </form>

      <div className="photo-section" style={{display: 'none'}}>
        <h2>Photos</h2>
        <div className="photo-upload">
          <input
            type="file"
            accept="image/*"
            onChange={handlePhotoUpload}
            id="photo-input"
          />
          <label htmlFor="photo-input">Upload Photo</label>
        </div>
        <div className="photos-grid">
          {photos.map((photo) => (
            <div key={photo.id} className="photo-card">
              <img src={`${API_BASE_URL}/media/${photo.file_path}`} alt="Profile" />
              <button
                type="button"
                onClick={() => handleDeletePhoto(photo.id)}
                className="delete-btn"
              >
                Delete
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
