import { useEffect, useState, useRef } from 'react'
import { useParams, Link } from 'react-router-dom'
import { Dog, GitBranch, Edit, Upload, Trash2 } from 'lucide-react'
import axios from 'axios'
import DogForm from '../components/DogForm'

function DogDetail() {
  const { id } = useParams()
  const [dog, setDog] = useState(null)
  const [loading, setLoading] = useState(true)
  const [showEditModal, setShowEditModal] = useState(false)
  const [uploading, setUploading] = useState(false)
  const fileInputRef = useRef(null)

  useEffect(() => {
    fetchDog()
  }, [id])

  const fetchDog = async () => {
    try {
      const res = await axios.get(`/api/dogs/${id}`)
      setDog(res.data)
      setLoading(false)
    } catch (error) {
      console.error('Error fetching dog:', error)
      setLoading(false)
    }
  }

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

    setUploading(true)
    const formData = new FormData()
    formData.append('photo', file)

    try {
      await axios.post(`/api/dogs/${id}/photos`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      fetchDog()
    } catch (error) {
      console.error('Error uploading photo:', error)
      alert('Failed to upload photo')
    } finally {
      setUploading(false)
      if (fileInputRef.current) fileInputRef.current.value = ''
    }
  }

  const handleDeletePhoto = async (photoIndex) => {
    if (!confirm('Delete this photo?')) return

    try {
      await axios.delete(`/api/dogs/${id}/photos/${photoIndex}`)
      fetchDog()
    } catch (error) {
      console.error('Error deleting photo:', error)
      alert('Failed to delete photo')
    }
  }

  if (loading) {
    return <div className="container loading">Loading...</div>
  }

  if (!dog) {
    return <div className="container">Dog not found</div>
  }

  return (
    <div className="container">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem' }}>
        <h1>{dog.name}</h1>
        <div style={{ display: 'flex', gap: '0.5rem' }}>
          <Link to={`/pedigree/${dog.id}`} className="btn btn-primary">
            <GitBranch size={20} />
            View Pedigree
          </Link>
          <button className="btn btn-secondary" onClick={() => setShowEditModal(true)}>
            <Edit size={20} />
            Edit
          </button>
        </div>
      </div>

      <div className="grid grid-2">
        <div className="card">
          <h2 style={{ marginBottom: '1rem' }}>Basic Information</h2>
          <div style={{ display: 'grid', gap: '0.75rem' }}>
            <div>
              <strong>Breed:</strong> {dog.breed}
            </div>
            <div>
              <strong>Sex:</strong> {dog.sex === 'male' ? 'Male ♂' : 'Female ♀'}
            </div>
            {dog.birth_date && (
              <div>
                <strong>Birth Date:</strong> {new Date(dog.birth_date).toLocaleDateString()}
              </div>
            )}
            {dog.color && (
              <div>
                <strong>Color:</strong> {dog.color}
              </div>
            )}
            {dog.registration_number && (
              <div>
                <strong>Registration:</strong> {dog.registration_number}
              </div>
            )}
            {dog.microchip && (
              <div>
                <strong>Microchip:</strong> {dog.microchip}
              </div>
            )}
          </div>
        </div>

        <div className="card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
            <h2>Photos</h2>
            <button 
              className="btn btn-primary" 
              onClick={() => fileInputRef.current?.click()}
              disabled={uploading}
            >
              <Upload size={18} />
              {uploading ? 'Uploading...' : 'Upload'}
            </button>
            <input 
              ref={fileInputRef}
              type="file" 
              accept="image/*" 
              onChange={handlePhotoUpload} 
              style={{ display: 'none' }}
            />
          </div>
          {dog.photo_urls && dog.photo_urls.length > 0 ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: '0.5rem' }}>
              {dog.photo_urls.map((url, index) => (
                <div key={index} style={{ position: 'relative' }}>
                  <img 
                    src={url} 
                    alt={`${dog.name} ${index + 1}`} 
                    style={{ width: '100%', aspectRatio: '1', objectFit: 'cover', borderRadius: '0.375rem' }} 
                  />
                  <button
                    className="btn-icon"
                    onClick={() => handleDeletePhoto(index)}
                    style={{ 
                      position: 'absolute', 
                      top: '0.25rem', 
                      right: '0.25rem', 
                      background: 'rgba(255,255,255,0.9)'
                    }}
                  >
                    <Trash2 size={16} color="var(--danger)" />
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: '2rem', background: 'var(--bg-secondary)', borderRadius: '0.375rem' }}>
              <Dog size={48} style={{ color: 'var(--text-secondary)', margin: '0 auto 0.5rem' }} />
              <p style={{ color: 'var(--text-secondary)' }}>No photos uploaded</p>
            </div>
          )}
        </div>
      </div>

      {dog.notes && (
        <div className="card" style={{ marginTop: '1.5rem' }}>
          <h2 style={{ marginBottom: '1rem' }}>Notes</h2>
          <p style={{ whiteSpace: 'pre-wrap' }}>{dog.notes}</p>
        </div>
      )}

      <div className="card" style={{ marginTop: '1.5rem' }}>
        <h2 style={{ marginBottom: '1rem' }}>Parents</h2>
        <div className="grid grid-2">
          <div>
            <h3>Sire (Father)</h3>
            {dog.sire ? (
              <Link to={`/dogs/${dog.sire.id}`} style={{ color: 'var(--primary)' }}>{dog.sire.name}</Link>
            ) : (
              <p style={{ color: 'var(--text-secondary)' }}>Unknown</p>
            )}
          </div>
          <div>
            <h3>Dam (Mother)</h3>
            {dog.dam ? (
              <Link to={`/dogs/${dog.dam.id}`} style={{ color: 'var(--primary)' }}>{dog.dam.name}</Link>
            ) : (
              <p style={{ color: 'var(--text-secondary)' }}>Unknown</p>
            )}
          </div>
        </div>
      </div>

      {dog.offspring && dog.offspring.length > 0 && (
        <div className="card" style={{ marginTop: '1.5rem' }}>
          <h2 style={{ marginBottom: '1rem' }}>Offspring ({dog.offspring.length})</h2>
          <div style={{ display: 'grid', gap: '0.5rem' }}>
            {dog.offspring.map(child => (
              <Link key={child.id} to={`/dogs/${child.id}`} style={{ color: 'var(--primary)' }}>
                {child.name} - {child.sex === 'male' ? '♂' : '♀'}
              </Link>
            ))}
          </div>
        </div>
      )}

      {showEditModal && (
        <DogForm
          dog={dog}
          onClose={() => setShowEditModal(false)}
          onSave={() => {
            fetchDog()
            setShowEditModal(false)
          }}
        />
      )}
    </div>
  )
}

export default DogDetail